Primitives

AI streams

Text or AG-UI runs that survive a refresh, with approvals and Stop on the same channel.

A stream channel holds a run: plain text, or an agent's AG-UI events with tool calls and approvals. Each event has an offset. Viewers see tokens as they're written; a refreshed tab, a second device or a late joiner replays the run so far and then follows it live. Stop travels back on the same channel.

Using the AI SDK's useChat? See Vercel AI SDK.

Stream text

pipe takes any source of strings (an async iterable or a ReadableStream), starts a run, writes it token by token and finishes the run. Writes are gathered into frames, so writing every token never hits a rate limit.

route.ts
typescript
import { Pulse } from "@anishroy/pulse/server"import { streamText } from "ai"
const rt = new Pulse()
export async function summarize(id: string, prompt: string) { const s = rt.stream(`doc:${id}`) const result = streamText({ model, prompt, abortSignal: s.signal }) await s.pipe(result.textStream) // starts a run, writes at any speed, finishes it}

useStream gives the latest run's text and its status (running, finished, interrupted or error).

summary.tsx
tsx
import { useStream } from "@anishroy/pulse/react"
function Summary({ id }: { id: string }) { const { text, status, interrupt } = useStream(`doc:${id}`) return ( <> <p>{text}</p> {status === "running" && <button onClick={interrupt}>Stop</button>} </> )}
  • If the source throws, the run ends with an error (status is error) and pipe rethrows.
  • If a viewer presses Stop, pipe cancels the source and ends the run as interrupted. Pass s.signal to your model call so it stops too.
  • Without pipe, write text yourself and finish the run:
route.ts
typescript
const s = rt.stream(`doc:${id}`)for await (const chunk of anyTextSource) s.write(chunk) // the first write starts a runawait s.finish()

Write an agent run

For chat with tool calls and approvals, write AG-UI events from your server, token by token. Deltas are gathered into frames too.

agent.ts
typescript
import { Pulse } from "@anishroy/pulse/server"
const rt = new Pulse()
export async function answer(thread: string, question: string) { const s = rt.stream(`chat:${thread}`) s.start() // RUN_STARTED
const ask = s.message({ role: "user" }) ask.write(question) ask.end()
const reply = s.message() for await (const token of llm.stream(question, { signal: s.signal })) { reply.write(token) // write at any speed; Pulse batches the frames } reply.end() await s.finish() // RUN_FINISHED}

Tool calls

agent.ts
typescript
const call = s.toolCall("get_order", { parentMessageId: reply.id })call.args(JSON.stringify({ orderId: "42" })) // stream arguments as they comecall.end()call.result(JSON.stringify(await getOrder("42")))

Ask the viewer

requestApproval shows an approval card to everyone watching and waits for the answer, which a viewer sends back on the channel. It resolves { approved: false } if the run is stopped first.

agent.ts
typescript
const { approved, reason } = await s.requestApproval({  title: "Refund order #42?",  description: "Two items, back to the original card",  details: { Amount: "€18.40" },  approveLabel: "Refund",  rejectLabel: "Not now",})if (approved) await refund("42")

Read in the browser

useStream replays the channel on mount and folds the events into chat messages: text, tool calls and approval cards, with the run's status (running, awaiting-approval, finished, interrupted or error).

chat.tsx
tsx
import { useStream } from "@anishroy/pulse/react"
function Chat({ thread }: { thread: string }) { const { messages, status, approval, approve, reject, interrupt } = useStream(`chat:${thread}`)
return ( <> {messages.map((m) => <Message key={m.id} message={m} />)} {approval && ( <ApprovalCard request={approval} onApprove={() => approve(approval.id)} onReject={() => reject(approval.id, "Not now")} /> )} {status === "running" && <button onClick={interrupt}>Stop</button>} </> )}

Or render the whole thread with the optional components: AgentThread for a channel, or AgentMessage for one message.

chat.tsx
tsx
import { AgentThread } from "@anishroy/pulse/ui"import "@anishroy/pulse/ui/styles.css"
<AgentThread channel={`chat:${thread}`} empty={<p>Ask anything.</p>} />

Stop

interrupt() in the browser asks the agent to stop. On the server, s.signal aborts and s.interrupted turns true, so pass the signal to your model call.

agent.ts
typescript
// s.signal aborts when a viewer presses Stopconst res = await fetch(modelUrl, { body, signal: s.signal })
// Or check between stepsif (s.interrupted) return s.finish({ interrupted: true })

Durability

By default, frames reach viewers as soon as they're written and are stored a moment later. That suits chat: in the rare case the channel restarts mid-run, viewers may have to reload the answer, and nothing is stored twice. durability: "frame" stores every frame before anyone sees it, so nothing a viewer saw can be lost:

agent.ts
typescript
const s = rt.stream(`orders:${id}:agent`, { durability: "frame" })
// Or for every streamconst rt = new Pulse({ durability: "frame" })
  • Choose it when a viewer acts on what it sees mid-run: tool calls that drive your UI, a transcript you keep as a record, another system reading the stream.
  • Keep the default for chat answers, which a restart only interrupts.

Bring your own AG-UI agent

The channel stores AG-UI events as they are: the event name is the type and the data is the event. (Plain text is a text event with the string as its data.) If your agent already speaks AG-UI, write its events straight through, and any AG-UI client can read the channel.

agent.ts
typescript
for await (const event of myAgUiAgent.run(input)) {  s.write(event) // any AG-UI event, as is}