SDK
@herald-voice/sdk: install it, handle a call, and every method with an example.
@herald-voice/sdk is the TypeScript SDK for herald. Your program uses it to take the workspace's calls (herald()), to work with the caller's audio (call.stream()), to run voice models, and to place and control calls (HeraldClient).
Install
npm install @herald-voice/sdk wsThe package is ESM only and needs Node 22 or later. ws is needed for app.listen(), app.attach(), the voice models and testCall(); over HTTP the app opens the call's stream with the platform's own WebSocket. The integrations have their own peers:
| Import | Needs |
|---|---|
@herald-voice/sdk | ws |
@herald-voice/sdk/verbs | nothing: the verb builders, for call.next() |
@herald-voice/sdk/testing | ws: testCall() |
@herald-voice/sdk/ai-sdk | ai (7 or later); @ai-sdk/gateway for a model given as a string |
@herald-voice/sdk/mastra | a Mastra agent or voice |
@herald-voice/sdk/tanstack | @tanstack/ai (1.8 or later) |
Handle a call
import { herald, to } from "@herald-voice/sdk";
const app = herald({
secret: process.env.HERALD_SECRET,
onCall: async (call) => {
await call.play("https://cdn.example.com/hello.wav");
const { digits } = await call.digits({ max: 1, timeout: "6s", prompt: "https://cdn.example.com/menu.wav" });
if (digits === "1") await call.dial(to.number("+390212345678"));
await call.hangup();
},
onEnded: (ev) => console.log(ev.call.id, ev.end_reason),
});
await app.listen(4000, { path: "/herald" });HERALD_SECRET is the workspace's signing secret (herald-cloud env, or Developers → Signing secret). Point the workspace's voice URL at the path the app serves: through the tunnel (herald-cloud tunnel 4000 --path /herald) or a public URL (herald-cloud backend --url https://api.example.com/herald).
How the call runs
The voice URL picks the transport:
https://…: herald posts the call, and the app opens a WebSocket to herald (the request'sstream_url) and runsonCallon it: everyawaitwaits on that stream, and herald holds the request until the code is done. Works on any HTTP host, serverless included: the function only dials out.wss://…: herald opens a WebSocket to the app for each call. Needs a long-running process (app.listen()orapp.attach()).
The same onCall works on both, and runs once: nothing is replayed, so a lookup, an email or a write is plain code. call.transport says which one carries the call.
herald answers the call when the code needs its audio: a play, a digits, a record, call.stream(), audio of the app's own. Before that, call.reject() refuses the call and call.dial() rings someone while the caller hears ringing.
Over HTTP the function lives while its code runs: on serverless, a call lasts at most the platform's maximum duration, counted from the request. To let the function go while herald waits (keys, a transfer, a queue), or to give an agent a whole function's time, the call goes on in a handler with call.next().
herald()
herald(options: HeraldAppOptions): HeraldApp| Option | ||
|---|---|---|
secret | string | the workspace's signing secret. Requests and WebSocket connections herald did not sign are refused (401), and the state call.next() passes on is sealed with it |
onCall | (call: Call) => unknown | runs for every call. When it returns, the call ends; when it returns a voice session, when the session closes |
accept | (info: CallInfo) => boolean | false refuses the call: SIP 404 before answering over HTTP, a hangup on a live call |
onError | (call: Call, err) => unknown | what onCall or a handler threw, with the call still there (play an apology, call.next() somewhere); when it returns, the call hangs up. Default: the error is logged and the call hangs up |
onEnded | (ev: CallEndedEvent) => void | call.ended, with every verb's result, when the status webhook is this app |
auth | (user, realm) => AppAccount | null | answers app.auth for SIP apps registering to herald |
wake | (req: WakeRequest) => string[] | void | answers app.wake: send the pushes, return the users to wait for |
log | false | (line: string) => void | one line per call.next() (herald 4f1c…: menu → support (dial_app)) and errors; default console.info |
maxState | number | the largest state call.next() may pass on, sealed, in bytes (default 2048) |
auth, wake, to.user() and to.group() are for herald's own SIP apps; herald cloud workspaces have no app accounts.
import { herald } from "@herald-voice/sdk";
const app = herald({
secret: process.env.HERALD_SECRET,
accept: (info) => info.number === "+390212345678",
onCall: async (call) => {
await call.play("https://cdn.example.com/hello.wav");
},
onEnded: (ev) => console.log(`${ev.call.id}: ${ev.end_reason}`),
});The app
What herald() returns: the ways to serve it.
app.listen()
listen(port: number, o?: { host?: string; path?: string }): Promise<http.Server>HTTP and WebSocket on one port, at path (default /); other paths answer 404.
await app.listen(4000, { path: "/herald" });app.http()
http(): { POST: (req: Request) => Promise<Response> }The app as a route export: Next.js route handlers, Vercel functions. HTTP only.
export const { POST } = app.http();
export const maxDuration = 300; // the longest a call (or a handler) runs hereapp.handle()
handle(req: Request): Promise<Response>A fetch handler for any runtime: Hono, Bun, Deno, Workers. It takes every event herald posts.
hono.post("/herald", (c) => app.handle(c.req.raw));app.node()
node(): (req: IncomingMessage, res: ServerResponse) => Promise<void>The app for Node's http, Express or Connect. It reads the raw body itself: put no body parser on that route.
expressApp.post("/herald", app.node());app.attach()
attach(server: http.Server, o?: { path?: string }): voidTakes herald's WebSocket connections (for a wss:// voice URL) on a server of yours. Serve the HTTP side on the same path with app.node().
import { createServer } from "node:http";
const server = createServer(app.node());
app.attach(server, { path: "/herald" });
server.listen(4000);The call
What onCall gets.
| Property | |
|---|---|
call.id | herald's id of the call |
call.from | the caller, as a SIP URI: sip:+393331234567@carrier |
call.to | the To URI |
call.number | the number dialled, E.164 |
call.info | all of the above, plus direction ("outbound" for calls you placed), customer and tenant (the workspace id, over HTTP) |
call.transport | "http" or "live" |
call.live | the call's stream (HeraldCall); taking it answers the call |
Durations in the call's options are a string ("5s", "1500ms", "2m") or a number of seconds.
call.play()
play(audio: Audio, o?: { loop?: number }): Promise<void>Plays audio: a WAV URL (absolute, or relative to the voice URL), WAV bytes, 8 kHz PCM16 samples such as tone(), or speech from a persona. WAVs are 8 kHz mono, PCM16, A-law or μ-law. Audio that is not a URL goes down the call's stream.
await call.play("/audio/welcome.wav", { loop: 2 });call.digits()
digits(o?: { max?: number; timeout?: Duration; interDigitTimeout?: Duration; terminator?: string; prompt?: Audio }):
Promise<GatherResult>Waits for keys. prompt plays while it waits and stops at the first key. Defaults: timeout 5 s, interDigitTimeout the same as timeout, terminator #. reason is max_digits, terminator, timeout or no_input.
const { digits, reason } = await call.digits({ max: 4, timeout: "8s", prompt: "/audio/pin.wav" });
if (reason === "no_input") await call.hangup();call.record()
record(o: { uploadUrl: string; uploadHeaders?: Record<string, string>; beep?: boolean; maxDuration?: Duration;
silenceTimeout?: Duration; finishOnKey?: string }): Promise<RecordingResult>Records the caller. herald PUTs the WAV to uploadUrl. Defaults: a beep first, no maximum, no stop on silence, # ends it. The result has recording_url, duration_ms and reason (silence, digit, max_duration, hangup).
const r = await call.record({ uploadUrl: "https://bucket.example.com/rec.wav?X-Amz-Signature=…", maxDuration: "2m", silenceTimeout: "5s" });
console.log(r.recording_url, r.duration_ms);To get the upload URL from your storage, see s3().
call.dial()
dial(target: Target, o?: { timeout?: Duration; summary?: string }): Promise<DialResult>Rings a target and connects the caller to whoever answers; the caller hears ringing (or music) meanwhile. The target is made with to, each kind with its own options:
to.number(number, { trunk?, callerId? }) | a number, through an outbound trunk. Defaults: the workspace's first trunk with calls out, that trunk's caller id ("inherit" shows the caller's) |
to.user(name, { hold?, holdFile? }), to.group(name, { hold?, holdFile? }) | the SIP apps registered to herald as that user or group, with hold: "music" and a WAV URL while it rings. For herald run on your own; herald cloud workspaces have no app accounts |
timeout (default 30 s of ringing) and summary (shown to the person who answers) go on dial. The result's outcome is answered, no_answer, busy or failed. After an answered dial the call ends when the two hang up.
import { to, type Target } from "@herald-voice/sdk";
const r = await call.dial(to.number("+390212345601", { callerId: "inherit" }), { timeout: "25s" });
if (r.outcome !== "answered") await call.play("/audio/nobody.wav");call.connect()
connect(url: string, params?: Record<string, string>): Promise<ConnectResult>Hands the call to another program over WebSocket (wss://…, or a path relative to the voice URL) until it closes the connection. params reach it in the stream's start message.
await call.connect("wss://agent.example.com/media", { order: "1234" });call.stream()
stream(fn: (live: HeraldCall) => unknown): Promise<VerbResult>Answers the call and gives fn a view of its stream (HeraldCall). When fn is done, or the voice session it returns closes, the call goes on with what follows. On serverless it lasts at most what is left of the function's maximum duration; an agent that talks longer can start in a handler of its own, or be behind call.connect().
await call.stream(async (live) => {
live.on("audio", (ulaw) => live.sendAudio(ulaw)); // the caller hears themselves
await new Promise((r) => setTimeout(r, 5000));
});
await call.hangup();call.run()
run<R>(verb: VerbOf<R>): Promise<R>
run(verb: Verb): Promise<VerbResult>Runs any verb: one from the builders (v.digits(...)), with its result type, or one of herald's protocol, as JSON. hangup, reject and redirect end the code.
await call.run({ verb: "play", file: "https://cdn.example.com/hello.wav", loop: 1 });| Verb | Fields |
|---|---|
answer | |
play | file, loop |
gather | prompt, max_digits, timeout, inter_digit_timeout, terminator |
record | upload_url, upload_headers, beep, max_duration, silence_timeout, finish_on_key |
dial | number, trunk, caller_id, timeout, summary |
dial_app | target, timeout, hold, hold_file, summary |
connect | url, params |
redirect | url |
reject | reason: busy, not_found, decline, unavailable |
hangup |
call.hangup()
hangup(): Promise<never>Hangs up. The code after it does not run.
await call.hangup();call.reject()
reject(reason?: "busy" | "not_found" | "decline" | "unavailable"): Promise<never>Refuses the call before answering it (the default is decline, SIP 603). Once the call is answered (a play before it, or a live call), it hangs up instead.
if (!call.from.includes("+39")) await call.reject("busy");call.next()
next(h: Handler<void, void>): Promise<never>
next<S>(h: Handler<S, void>, state: S): Promise<never>
next<S, R>(h: Handler<S, R>, state: S, verb: VerbOf<R>): Promise<never>Goes on in handler h, in a new invocation: herald runs verb (if any) without this function, then posts its result to h, with state. The code after it does not run. The verb builders make one verb with its result type, and their audio fields are URLs, since herald plays them without the function:
import * as v from "@herald-voice/sdk/verbs";
return call.next(menu, { customerId }, v.digits({ max: 1, prompt: "/audio/menu.wav" }));v. | result |
|---|---|
play(url, { loop? }) | none |
digits({ max?, timeout?, interDigitTimeout?, terminator?, prompt? }) | GatherResult |
record({ uploadUrl, ... }) | RecordingResult |
dial(target, { timeout?, summary? }) | DialResult |
connect(url, params?) | ConnectResult |
call.next(menu, ctx, v.dial(...)) does not compile when menu takes a GatherResult, nor does a state of the wrong shape.
Handlers
A handler is where call.next() goes on: a function (call, state, result) defined on the app, with a name. Defining it registers it.
import { herald, to } from "@herald-voice/sdk";
import * as v from "@herald-voice/sdk/verbs";
type Ctx = { customerId: string };
const app = herald({
secret: process.env.HERALD_SECRET,
onCall: async (call) => {
const customer = await db.customers.byPhone(call.from);
if (!customer) return call.reject("not_found");
return call.next(menu, { customerId: customer.id }, v.digits({ max: 1, prompt: "/audio/menu.wav" }));
},
});
const menu = app.handlers.digits<Ctx>("menu", async (call, ctx, { digits }) => {
if (digits === "1") return call.next(agent, ctx);
if (digits === "2") return call.next(afterSales, ctx, v.dial(to.number("+390212345601")));
return call.next(menu, ctx, v.digits({ max: 1, prompt: "/audio/retry.wav" }));
});
const agent = app.handlers.new<Ctx>("agent", async (call, { customerId }) => {
await call.stream((live) => connectRealtime(live, { model: "openai/gpt-realtime-2", instructions: "..." }));
});
const afterSales = app.handlers.dial<Ctx>("afterSales", async (call, ctx, r) => {
if (r.outcome !== "answered") await call.play("/audio/nobody.wav");
});
export const { POST } = app.http();app.handlers. | the handler's result |
|---|---|
new<State, Result>(name, fn) | any, or none (call.next(h, state)) |
digits<State>(name, fn) | GatherResult |
record<State>(name, fn) | RecordingResult |
dial<State>(name, fn) | DialResult, whatever the target |
connect<State>(name, fn) | ConnectResult |
- The state travels with the call, sealed with the secret and bound to the call: keep it small (at most 2 KB sealed), an id rather than a record. A Standard Schema (zod, valibot...) types and checks it:
app.handlers.digits("menu", { state: z.object({ customerId: z.string() }) }, fn). A state that does not match goes toonError. - The name is the handler's id in the URLs herald posts to: keep it, and the state's shape, stable across deploys. A name defined twice is an error.
- Handlers are defined outside
onCall: the next invocation finds the function from the URL, and a closure's variables are not there. - On a
wss://voice URL the process lives, andcall.next()goes on in it.
Testing an app
testCall() from @herald-voice/sdk/testing is a herald in memory: the app gets signed events and opens their streams as with herald, and you script the caller.
import { testCall } from "@herald-voice/sdk/testing";
const t = await testCall(app).answer({ digits: "2" }).answer({ outcome: "no_answer" }).run();
assert.deepEqual(t.handlers, ["onCall", "menu", "afterSales"]);
assert.deepEqual(t.verbs.map((x) => x.verb), ["gather", "dial", "play"]);.answer(result) is the result of the next verb that waits for the caller; .hangup() hangs up there. run() gives end, handlers, verbs, results, answered and audioBytes; a verb with nothing scripted, or steps left over, fail it.
The stream
HeraldCall is the call's audio and control: what call.stream(fn) gives fn, and call.live. Audio is G.711 μ-law at 8 kHz, in 20 ms frames.
The methods below run in your process on the stream; call.play, call.digits and call.record have herald do it. Durations here are milliseconds or a string ("3s").
| Property | |
|---|---|
live.callId | herald's id of the call |
live.params | call_id, from, to, number, customer, direction, and the params of a connect |
live.paused | true while a person has the call (a transfer that returns) |
live.closed | the stream has closed |
Events
live.on("audio", (ulaw) => {}); // 20 ms of μ-law 8 kHz from the caller
live.on("dtmf", (key) => {}); // a key the caller pressed
live.on("transferStarted", ({ target }) => {});
live.on("resumed", (result) => {}); // the call is back from a person
live.on("stop", () => {}); // the caller hung up, or herald ended the stream
live.on("close", () => {});
live.on("error", (err) => console.warn(err.message));Add an error listener when you send raw messages with live.send().
live.sendAudio()
sendAudio(ulaw: Uint8Array): voidPlays μ-law 8 kHz audio of any length; herald paces it.
live.sendAudio(ulawEncode(tone(440, 500)));live.onPcm24k() and live.sendPcm24k()
onPcm24k(cb: (pcm: Int16Array) => void): void
sendPcm24k(pcm: Int16Array): voidThe caller's audio as 24 kHz PCM16, and audio to play in the same format, resampled for you.
live.onPcm24k((pcm) => model.input(pcm));
model.onOutput((pcm) => live.sendPcm24k(pcm));live.mark()
mark(name?: string): Promise<void>Resolves when the caller has heard everything sent before it, or the call ends.
live.sendAudio(greeting);
await live.mark();
console.log("the greeting has played");live.clear()
clear(): voidDrops the audio not played yet: for barge-in, when the caller starts talking.
live.on("dtmf", () => live.clear());live.play()
play(src: string | URL | Uint8Array | Int16Array | AsyncIterable<Uint8Array>, o?: { interruptible?: boolean; loop?: number; signal?: AbortSignal }):
Promise<{ interruptedBy?: string; hungUp?: boolean }>Plays in your process: a WAV URL (fetched and cached), μ-law bytes, 8 kHz PCM16 samples, or μ-law chunks as they come, such as a Speech. With interruptible, a key stops it.
const r = await live.play("https://cdn.example.com/menu.wav", { interruptible: true });
if (r.interruptedBy) console.log("pressed", r.interruptedBy);live.digits()
digits(o?: { max?: number; timeout?: Ms; interDigitTimeout?: Ms; terminator?: string; prompt?: AudioSource; signal?: AbortSignal }):
Promise<{ digits: string; reason: "max" | "terminator" | "timeout" | "hangup" }>Collects keys in your process. Defaults: timeout 5 s, interDigitTimeout 3 s, terminator # ("" for none).
const pin = await live.digits({ max: 4, timeout: 8000 });live.dtmf()
dtmf(): AsyncGenerator<string>The keys as they come, until the call ends.
for await (const key of live.dtmf()) {
if (key === "#") break;
}live.record()
record(o?: { maxDuration?: Ms; silence?: Ms; finishOnKey?: string; beep?: boolean; signal?: AbortSignal }):
Promise<{ wav: Uint8Array; durationMs: number; reason: "silence" | "max" | "key" | "hangup" }>Records the caller in your process, as an 8 kHz WAV in memory. Defaults: at most 60 s, stops after 3 s of silence (0: never), # ends it, a beep first.
const rec = await live.record({ silence: "3s", maxDuration: "2m" });
await writeFile(`${live.callId}.wav`, rec.wav);live.transfer()
transfer(o: { target: Target; mode?: "return" | "handoff"; timeout?: string; reason?: string; summary?: string }): Promise<TransferResult>Passes the call to a person after the queued audio plays. target is a target: to.number("+39…", { trunk, callerId }), or to.user() / to.group() apps on herald run on your own. With mode: "return" (the default) it resolves when the call comes back, with outcome (answered, no_answer, busy, failed), talked_ms and the note the person left; with "handoff" the stream ends. It rejects with CallEndedError if the call ends meanwhile.
try {
const t = await live.transfer({ target: to.number("+390212345601"), summary: "Order 1234, damaged on arrival" });
console.log(t.outcome, t.note);
} catch (err) {
if (!(err instanceof CallEndedError)) throw err;
}live.run()
run(verb: Verb): Promise<VerbResult>Has herald run a verb; the stream pauses meanwhile.
await live.run({ verb: "play", file: "https://cdn.example.com/hold.wav" });live.redirect()
redirect(to: Verb[] | { url: string }): voidEnds the stream, and herald runs the verbs, or what the URL answers.
live.redirect([{ verb: "play", file: "https://cdn.example.com/bye.wav" }, { verb: "hangup" }]);live.hangup()
hangup(): Promise<void>Hangs up once the queued audio has played.
await live.hangup();live.end()
end(): voidCloses the stream; the call goes on with what follows call.stream().
live.end();liveOf()
liveOf(call: Call | HeraldCall): HeraldCallThe stream of a live call, or the stream itself. Over HTTP it throws: use call.stream().
const stream = liveOf(call);Voice agents
A speech-to-speech model talks to the caller, with barge-in and tools. It needs the call's audio: return it from onCall on a live call, or run it inside call.stream() over HTTP.
connectRealtime
From @herald-voice/sdk/ai-sdk, with the Vercel AI SDK.
connectRealtime(call: Call | HeraldCall, o: RealtimeOptions): Promise<VoiceSession>npm install @herald-voice/sdk ws ai @ai-sdk/gateway zodimport { herald } from "@herald-voice/sdk";
import { connectRealtime } from "@herald-voice/sdk/ai-sdk";
import { tool } from "ai";
import { z } from "zod";
const app = herald({
secret: process.env.HERALD_SECRET,
onCall: (call) =>
call.stream((live) =>
connectRealtime(live, {
model: "openai/gpt-realtime-2",
instructions: "You book visits for a dentist. Speak in short sentences.",
greeting: "Greet the caller and ask how you can help.",
tools: {
freeSlots: tool({
description: "The free slots on a day",
inputSchema: z.object({ day: z.string() }),
execute: async ({ day }) => [`${day} 10:00`, `${day} 15:30`],
}),
},
onTranscript: (who, text) => console.log(`${who}: ${text}`),
}),
),
});| Option | ||
|---|---|---|
model | string | RealtimeModel | an AI Gateway id (AI_GATEWAY_API_KEY, or the OIDC token on Vercel) or an AI SDK realtime model |
apiKey | string | the AI Gateway key, instead of AI_GATEWAY_API_KEY |
instructions | string | what the voice is and does |
greeting | string | false | what it says first; false: the caller speaks first |
voice | string | the model's voice |
tools | AI SDK tools | tools the voice runs itself |
agent | an AI SDK Agent | your agent: the voice asks it with an ask_agent tool and says the answer |
phone | Phone | the people it can pass the call to (createPhone) |
phoneOn | "voice" | "agent" | who gets the phone's tools (default "voice") |
hangupTool | boolean | an end_call tool when there is no phone (default true) |
format | "pcmu" | "pcm" | the audio to the model: μ-law 8 kHz (default) or 24 kHz PCM16 |
silenceMs | number | the silence that ends the caller's turn (default 500) |
onTranscript | (role, text) => void | each line, caller or assistant |
onError | (err) => void |
The session closes when the model closes or the call ends. VoiceSession has close() and closed.
With your own agent:
import { herald } from "@herald-voice/sdk";
import { connectRealtime } from "@herald-voice/sdk/ai-sdk";
import { ToolLoopAgent } from "ai";
const agent = new ToolLoopAgent({ model: "openai/gpt-5-mini", instructions: "You are ACME's support agent." });
herald({
secret: process.env.HERALD_SECRET,
onCall: (call) =>
call.stream((live) =>
connectRealtime(live, {
model: "openai/gpt-realtime-2",
instructions: "You are ACME's phone voice. For orders and accounts, ask the agent.",
agent,
}),
),
});The same file also exports aiSdkOracle(agent), phoneTools(phone) (the phone's tools for an agent with phoneOn: "agent"), transcriber() and textToSpeech().
Mastra
import { herald } from "@herald-voice/sdk";
import { connectRealtime } from "@herald-voice/sdk/mastra";
herald({
secret: process.env.HERALD_SECRET,
onCall: (call) =>
call.stream((live) =>
connectRealtime(live, { model: "openai/gpt-realtime-2", agent: mastra.getAgent("support"), memory: true, instructions: "ACME's phone voice." }),
),
});agent is a Mastra agent; with memory: true its memory keeps the call as one thread (resource: the caller). connectMastraVoice(call, voice, { greet: true }) bridges a Mastra realtime voice of your own; mastraOracle(agent) and textToSpeech(voice, { id }) are exported too.
TanStack AI
import { herald } from "@herald-voice/sdk";
import { connectRealtime } from "@herald-voice/sdk/tanstack";
herald({
secret: process.env.HERALD_SECRET,
onCall: (call) =>
call.stream((live) =>
connectRealtime(live, { model: "openai/gpt-realtime-2", chat: { adapter: openaiText("gpt-5.2"), systemPrompts: ["You are ACME's support agent."] } }),
),
});chat is a TanStack AI chat() configuration. Also exported: tanstackOracle(config), tanstackPhoneTools(phone), textToSpeech(adapter).
connectVoice
connectVoice(call: Call | HeraldCall, o: VoiceOptions): Promise<VoiceSession>The same, without a framework: model is an AI Gateway id or a VoiceModel, tools are plain tools with a JSON Schema, and oracle is your agent.
import { connectVoice, perCallOracle, oraclePrompt, type Tool } from "@herald-voice/sdk";
const orderStatus: Tool = {
name: "order_status",
description: "Status of an order by number",
parameters: { type: "object", properties: { order: { type: "string" } }, required: ["order"] },
execute: async ({ order }) => ({ order, status: "shipped" }),
};
const oracle = perCallOracle(
() => ({}),
(_state, req) => myAgent.answer(oraclePrompt(req), { signal: req.signal }),
);
herald({
secret: process.env.HERALD_SECRET,
onCall: (call) => call.stream((live) => connectVoice(live, { model: "openai/gpt-realtime-2", instructions: "ACME's phone voice.", tools: [orderStatus], oracle })),
});gatewayVoice(id, { apiKey?, baseURL? }) is the AI Gateway VoiceModel a string model stands for.
Oracles
Your agent, as the voice's ask_agent tool.
perCallOracle(init, ask) | an oracle with state per call: init(live) once, then ask(state, req) for each question |
oraclePrompt(req) | the question with the last 30 lines of the transcript, as one prompt |
currentCall() | in a tool your agent runs, the call it is answering for |
withCall(live, fn) | runs fn with currentCall() set to live |
describeTransfer(result) | a transfer's result in words for a model: outcome, colleague, talked seconds, note |
askAgentTool | the ask_agent tool's name, description and parameters |
import { currentCall, describeTransfer, to } from "@herald-voice/sdk";
// A tool of your agent: it acts on the call the agent is answering.
export async function passToBilling(summary: string) {
return describeTransfer(await currentCall().transfer({ target: to.number("+390212345601"), summary }));
}createPhone
createPhone<T>(o: { contacts: Contacts<T>; onlyContacts?: boolean; hangup?: boolean; summary?: (t) => string | undefined }): PhoneThe people the agent can pass the call to; dial says who to ring for each contact (a target). The voice gets transfer_call { to, reason, summary }, end_call, and with a search, find_contact. transfer_call dials only contacts the agent got during this call (onlyContacts: false turns that off).
import { createPhone, to } from "@herald-voice/sdk";
const phone = createPhone({
contacts: {
favorites: async () => [{ name: "Billing", phone: "+390212345601", hours: "9-18" }],
search: (query) => crm.searchPeople(query), // [{ name, phone }]
dial: (c) => to.number(c.phone),
description: "every employee, by name or team",
},
});Pass it as phone to connectRealtime or connectVoice. runPhoneTool(tool, args) runs one of phone.tools on the current call; phoneToolDescriptions has their descriptions.
Ready-made pieces
Functions of the call, on both transports.
menu
menu(call: Call, o: { prompt: Audio; options: Record<string, () => T>; otherwise?: () => E; invalid?: Audio; noInput?: Audio;
retries?: number; timeout?: Duration }): Promise<T | E | undefined>Plays prompt and waits for one of the options' keys, then runs that option and returns what it returns. A wrong key plays invalid, no key noInput, and it asks again (retries: 2); after the last try it runs otherwise, if any.
await menu(call, {
prompt: "/audio/menu.wav",
invalid: "/audio/invalid.wav",
options: {
"1": () => call.dial(to.number("+390212345601")),
"2": () => call.next(support, { from: call.from }),
},
otherwise: () => voicemail(call, { storage: store }),
});collectDigits
collectDigits(call: Call, o: { prompt: Audio; length?: number; maxDigits?: number; terminator?: string; timeout?: Duration;
interDigitTimeout?: Duration; validate?: (digits, call) => boolean | Promise<boolean>; invalid?: Audio;
confirm?: { prompt: (digits, call) => Audio | Promise<Audio>; yes?: string; no?: string }; retries?: number }): Promise<string | undefined>A code from the keypad: length digits, or up to #. validate checks it, confirm reads it back (a URL, or persona.say(...)) and asks 1 (yes) or 2 (no).
const order = await collectDigits(call, {
prompt: "/audio/order-number.wav",
length: 6,
validate: (d) => db.orders.exists(d),
});voicemail
voicemail(call: Call, o: { storage: Storage; greeting?: Audio; key?: (call) => string; maxLength?: Duration;
silenceTimeout?: Duration; beep?: boolean; finishOnKey?: string }): Promise<{ key: string; durationMs: number; result: VerbResult } | undefined>A greeting, a beep, and the message to your storage (voicemail/<date>/<call id>.wav; at most 2 minutes, ends after 5 s of silence). undefined when nothing was said.
const msg = await voicemail(call, { greeting: "/audio/leave-a-message.wav", storage: store });
if (msg) await notify(msg.key);businessHours
businessHours(o: { timeZone: string; week: Record<string, string | string[]>; closed?: string[] }): BusinessHoursOpening hours. week keys are days (mon) or ranges (mon-fri); closed takes dates (2026-12-24) or yearly days (12-25). isOpen(at?) tells; route(open, closed) is an onCall that picks one.
const hours = businessHours({ timeZone: "Europe/Rome", week: { "mon-fri": "09:00-13:00, 14:00-18:00" }, closed: ["12-25"] });
herald({ secret: process.env.HERALD_SECRET, onCall: hours.route(office, leaveMessage) });screenCalls
screenCalls(o: { block?: string[]; allow?: string[]; anonymous?: "reject" | "allow"; check?: (caller, call) => boolean;
reason?: "busy" | "not_found" | "decline" | "unavailable"; onBlocked?: (caller, call) => void }, onCall: OnCall): OnCallRefuses callers before onCall runs, before answering: numbers or prefixes (+39899*) in block, numbers not in allow, hidden numbers with anonymous: "reject", or when check returns true.
herald({ secret: process.env.HERALD_SECRET, onCall: screenCalls({ block: ["+39899*"], anonymous: "reject" }, office) });callerNumber
callerNumber(call: { from: string }): stringThe caller's number from call.from; "" when hidden.
const caller = callerNumber(call); // "+393331234567"After the call
onEnded
onEnded(...handlers: ((ev: CallEndedEvent) => void | Promise<void>)[]): (ev: CallEndedEvent) => Promise<void>Several onEnded handlers in one.
herald({ secret: process.env.HERALD_SECRET, onCall, onEnded: onEnded(callLog(jsonlFile("calls.jsonl")), (ev) => metrics.count(ev.end_reason)) });CallEndedEvent has call, results (every verb's result, in order), last_result, ended_at and end_reason.
callRecord, callLog, jsonlFile
callRecord(ev: CallEndedEvent): CallRecord
callLog(write: (record: CallRecord, ev: CallEndedEvent) => void | Promise<void>): (ev: CallEndedEvent) => Promise<void>
jsonlFile(path: string): (record: CallRecord) => Promise<void>One flat record per call: id, direction, caller, number, started_at, ended_at, duration_s, end_reason, digits, recordings, transfers, errors.
const log = callLog((record) => db.calls.insert(record));
const toFile = callLog(jsonlFile("calls.jsonl"));transcribeRecordings
transcribeRecordings(o: { storage: Storage; transcribe: (wav: Uint8Array) => Promise<string>; done: (t: { call; key; text; result }) => void | Promise<void> }): (ev: CallEndedEvent) => Promise<void>When the call ends, the text of each recording it saved to storage. transcriber(model) from @herald-voice/sdk/ai-sdk makes transcribe from an AI SDK transcription model.
import { transcriber } from "@herald-voice/sdk/ai-sdk";
import { gateway } from "@ai-sdk/gateway";
const transcripts = transcribeRecordings({
storage: store,
transcribe: transcriber(gateway.transcriptionModel("openai/whisper-1")),
done: ({ call, key, text }) => db.transcripts.insert({ call: call.id, key, text }),
});Storage
A Storage gives herald URLs to upload recordings to (upload(key)) and to play files from (url(key)), and reads them back (get(key), keyOf(recordingUrl)).
s3
s3(o: { bucket: string; region?: string; endpoint?: string; accessKeyId?: string; secretAccessKey?: string;
sessionToken?: string; pathStyle?: boolean; prefix?: string; expires?: number }): StorageS3, or any S3-compatible store (R2, MinIO, B2), with presigned URLs and no AWS SDK. Credentials from the options or AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY; links last expires seconds (3600).
const store = s3({ bucket: "calls", region: "auto", endpoint: process.env.S3_ENDPOINT });
const up = store.upload(`recordings/${call.id}.wav`);
await call.record({ uploadUrl: up.upload_url, uploadHeaders: up.upload_headers });
await call.play(store.url("prompts/thanks.wav"));localStorage
localStorage(o: { dir: string; baseUrl: string; secret: string; expires?: number }): Storage & { handler(req: Request): Promise<Response> }The same on a folder of your server, with signed links. Mount store.handler at baseUrl.
const store = localStorage({ dir: "./files", baseUrl: "https://api.example.com/files", secret: process.env.FILES_SECRET! });
hono.all("/files/*", (c) => store.handler(c.req.raw));Speech
createPersona
createPersona(o: { tts: TextToSpeech; cache?: SpeechCache | SpeechCache[]; onError?: (err: Error) => void }): PersonaText to audio for the call, with any text-to-speech model. say(text) returns a Speech that plays wherever audio does (call.play, a digits prompt, live.play). On a live call and in call.stream it plays while it is generated; over HTTP, once complete. Generation starts when it first plays; the same text with the same model and voice is generated once and kept in the cache. preload(...texts) generates ahead.
import { createPersona, fileCache } from "@herald-voice/sdk";
import { textToSpeech } from "@herald-voice/sdk/ai-sdk";
const anna = createPersona({
tts: textToSpeech("openai/gpt-4o-mini-tts", { voice: "nova", language: "it" }),
cache: fileCache(".speech"),
});
await anna.preload("Premi 1 per l'assistenza, 2 per l'amministrazione.");
herald({
secret: process.env.HERALD_SECRET,
onCall: async (call) => {
await call.play(anna.say("Buongiorno, grazie per aver chiamato."));
const { digits } = await call.digits({ max: 1, prompt: anna.say("Premi 1 per l'assistenza, 2 per l'amministrazione.") });
},
});A Speech also gives its audio: await speech.ulaw(), await speech.wav(), or for await (const chunk of speech).
| Cache | |
|---|---|
memoryCache({ maxBytes? }) | in memory (32 MB by default) |
fileCache(dir) | 8 kHz WAV files in a folder |
storageCache(store, { prefix? }) | in a Storage, shared by every instance of your program |
[memoryCache(), storageCache(store)] | tried in order |
| Model | |
|---|---|
textToSpeech(model, { voice, instructions, speed, language, outputFormat, providerOptions }) from /ai-sdk | an AI SDK speech model or AI Gateway id |
textToSpeech(voice, { id, speaker, options, format }) from /mastra | a Mastra voice |
textToSpeech(adapter, { voice, speed, modelOptions }) from /tanstack | a TanStack AI speech adapter |
Your own model is a TextToSpeech:
import type { TextToSpeech } from "@herald-voice/sdk";
const tts: TextToSpeech = {
id: "my-tts/maria", // part of the cache key
format: { type: "audio/pcm", rate: 22050 }, // PCM16 at any rate, audio/pcmu, audio/pcma or audio/wav
async *synthesize(text, { signal }) {
const res = await fetch("https://tts.example.com/v1/speak", { method: "POST", body: JSON.stringify({ text }), signal });
for await (const chunk of res.body!) yield chunk;
},
};isSpeech(x) tells a Speech apart; ToUlaw converts a SpeechFormat to μ-law.
Audio
tone(freq, ms, level?) | a sine at 8 kHz, as PCM16 samples |
encodeWav(pcm, rate?) | PCM16 to WAV (8 kHz by default) |
decodeWav(wav) | a WAV (PCM16 at 8, 16, 24 or 48 kHz, A-law or μ-law) to 8 kHz mono PCM16 |
ulawEncode(pcm), ulawDecode(ulaw), alawDecode(alaw) | G.711 |
new Upsampler3(), new Downsampler3() | streaming 8 ↔ 24 kHz: .process(pcm) |
new Resampler8k(rate) | streaming, any rate to 8 kHz |
pcm16ToBase64(pcm), base64ToPcm16(b64) |
import { encodeWav, tone, ulawEncode } from "@herald-voice/sdk";
const beep = encodeWav(tone(1000, 300)); // WAV bytes: call.play(beep)
const ulaw = ulawEncode(tone(440, 200)); // μ-law: live.sendAudio(ulaw)verifySignature
verifySignature(secret: string, payload: string, timestamp: string | undefined, signature: string | undefined, maxAgeSeconds?: number): booleanChecks herald's signature on a request you handle without herald(). herald sends X-Herald-Timestamp (Unix seconds) and X-Herald-Signature: sha256=<hex HMAC-SHA256(secret, "<timestamp>.<body>")>. Requests older than maxAgeSeconds (300) fail.
import { verifySignature } from "@herald-voice/sdk";
export async function POST(req: Request) {
const body = await req.text();
const ok = verifySignature(process.env.HERALD_SECRET!, body, req.headers.get("x-herald-timestamp") ?? undefined, req.headers.get("x-herald-signature") ?? undefined);
if (!ok) return new Response("bad signature", { status: 401 });
return Response.json({ verbs: [{ verb: "play", file: "https://cdn.example.com/hi.wav" }, { verb: "hangup" }] });
}HeraldClient
new HeraldClient(baseUrl: string, apiKey: string, fetchImpl?: typeof fetch)herald's REST API: calls out and the calls in progress. baseUrl is herald's API (api in herald-cloud whoami --json); apiKey an API key of the workspace. A key sees only its workspace's calls. An error answer throws HeraldError, with status.
import { HeraldClient, HeraldError } from "@herald-voice/sdk";
const herald = new HeraldClient(process.env.HERALD_API_URL!, process.env.HERALD_API_KEY!);calls.create()
calls.create(o: { to: string; voice_url?: string; verbs?: Verb[]; trunk?: string; caller_id?: string; timeout?: string;
customer?: string; status_webhook?: string }): Promise<{ id: string }>Places a call out through a trunk with calls out. Once answered, the program at voice_url takes it (call.info.direction is "outbound"), or herald runs verbs. One of the two is required. Ringing lasts timeout (30 s); an unanswered call ends with no_answer, busy or failed on the status webhook.
const { id } = await herald.calls.create({ to: "+390212345678", voice_url: "https://api.example.com/herald", timeout: "30s" });calls.list()
calls.list(): Promise<CallState[]>The calls in progress: id, from, to, number, direction, started_at, answered, streaming, transferring.
for (const c of await herald.calls.list()) console.log(c.id, c.number, c.answered);calls.get()
calls.get(id: string): Promise<CallState>One call in progress; a 404 HeraldError once it has ended.
const state = await herald.calls.get(id);calls.hangup()
calls.hangup(id: string): Promise<{ status: string }>Ends the call (end_reason: api_hangup).
await herald.calls.hangup(id);calls.redirect()
calls.redirect(id: string, verbs: Verb[]): Promise<{ status: string }>Replaces what the call is doing with these verbs.
await herald.calls.redirect(id, [{ verb: "play", file: "https://cdn.example.com/closing.wav" }, { verb: "hangup" }]);calls.transfer()
calls.transfer(id: string, o: { target: Target; mode?: "return" | "handoff"; timeout?: string; reason?: string; summary?: string }): Promise<{ status: string }>Passes a call that is streaming to a person, as live.transfer() does. A call without a stream answers 409.
try {
await herald.calls.transfer(id, { target: to.number("+390212345601"), summary: "Callback about order 1234" });
} catch (err) {
if (err instanceof HeraldError && err.status === 409) console.log("the call has no stream");
}calls.resume()
calls.resume(id: string, note?: string): Promise<{ status: string }>Hands a transferred call back to the program, with a note it receives in the transfer's result.
await herald.calls.resume(id, "customer verified");tenants.list() and tenants.reload() need herald's admin key; a workspace key gets 403.