Skip to main content

Agent

A voice agent: instructions plus tools, optional sub-agents, and call-control behavior. Subclass it and decorate methods as tools, give it a Pipeline, then register it with serve and start calls against it with invoke - the serving worker runs each call in an AgentSession. Within a live call, this.session resolves to the current AgentSession.

Constructor

instructions
string
required
The system prompt / instructions for the agent.
tools
FunctionTool[] | null
Tools the agent exposes to its model. Defaults to none.
name
string | null
Display name. Defaults to the agent’s id.
agentId
string | null
Stable agent id. Defaults to the class name.
pipeline
unknown
The Pipeline this agent runs on. Defaults to null.
maxSessionDurationSeconds
number | null
Maximum call duration in seconds, or null for no limit. Defaults to null.
mcpServers
unknown[] | null
MCP servers to attach. Defaults to none.
inheritContext
boolean
Whether the agent inherits conversation context on handoff. Defaults to false.
voiceSuffix
string | null
Suffix appended to instructions to steer voice/style, or null. Defaults to null.
appendVoiceSuffix
boolean
Whether AgentOptions.voiceSuffix is appended. Defaults to true.
agents
Agent[] | null
Sub-agents available for handoff via agentSwitch. Defaults to none.
contextWindow
ContextWindow | null
Context-window policy for trimming conversation history. Defaults to null.

addServer

Attach an MCP server at runtime. Override to add custom handling.

captureFrames

Capture the most recent vision frame(s) from the active session’s pipeline. Returns an empty array if vision frames are unavailable.
numOfFrames
Number of most-recent frames to return. Defaults to 1.
returns
unknown[]

cleanup

Release agent resources. Override for custom teardown.

closeEmitter

Close the emitter: drop all handlers and stop emitting. Waits up to 2 seconds for in-flight async handlers to settle before returning.

emit

event
string
required

hangup

End the current call, if a session is active.

initializeMcp

Initialize attached MCP servers. Override to add custom MCP setup.

interrupt

Interrupt the current utterance and cancel any in-flight generation. No-op when no session is active. Also reachable as ctx.session.interrupt(...).
opts
Record<string, unknown>
returns
Promise<unknown>

listenerCount

event
string
required
returns
number

off

event
string
required
handler
EventHandler
required

on

event
string
required
handler
EventHandler
required
returns
EventHandler

once

event
string
required
handler
EventHandler
required
returns
EventHandler

onEnter

Lifecycle hook run when the agent becomes active in a call. Override it.

onExit

Lifecycle hook run when the agent leaves the call. Override it.

playBackgroundAudio

Play a background audio clip during the call. No-op without an active session or file.
file
string | null
volume
Playback volume 0.0-1.0. Defaults to 1.0.
looping
Whether to loop the clip. Defaults to false.
overrideThinking
Whether this clip overrides any thinking audio. Defaults to true.

preloadBackgroundAudio

Preload a background audio clip for low-latency playback.
file
string | null
volume
Playback volume 0.0-1.0. Defaults to 1.0.

registerA2a

Register an agent-to-agent (A2A) card. Override to add custom handling.

registerTools

Scan this instance (and its prototype chain) for methods marked as tools and add them to Agent.tools. Called automatically by the constructor.

removeAllListeners

event
string

reply

Ask the model to produce a reply given instructions, then speak it. No-op when no session is active. Also reachable as ctx.session.reply(...).
instructions
string
required
opts
Record<string, unknown>
returns
Promise<unknown>

say

Speak message through the pipeline’s text-to-speech (no model call). No-op when no session is active. Also reachable as ctx.session.say(...).
message
string
required
opts
Record<string, unknown>
returns
Promise<unknown>

setThinkingAudio

Set the audio looped while the agent is “thinking” (generating). Pass a falsy file to clear it.
file
string | null
volume
Playback volume 0.0-1.0. Defaults to 0.3.

stopBackgroundAudio

Stop any background audio, if a session is active.

unregisterA2a

Unregister the agent’s A2A card. Override to add custom handling.

updateTools

Replace the agent’s tool set with tools.
tools
FunctionTool[]
required

AgentSession

Create an AgentSession for agent running on pipeline. Low-level constructor used internally by serve for each dispatched session. Prefer serve + invoke; call this directly only when building a custom worker that manages sessions itself.

Constructor

agent
Agent
required
pipeline
Pipeline
required
wakeUp
number | null
Inactivity timeout in seconds after which the agent proactively wakes the user (requires an onWakeUp handler), or null to disable. Defaults to null.
wakeUpMaxAttempts
number | null
Maximum number of wake-up attempts before ending the call, or null for unlimited. Defaults to null.
backgroundAudio
any
Background audio to play during the call (config object, URL, or path). Defaults to null.
dtmfHandler
any
Handler for incoming DTMF (touch-tone) digits. Defaults to the pipeline’s, else null.
voiceMailDetector
any
Voicemail detector. Defaults to the pipeline’s, else null.
recording
any
Recording configuration applied to the session. Defaults to null.

activeAgent

The agent currently handling the call (changes across handoffs).
returns
Agent

addShutdownCallback

Register a callback to run when the session shuts down.
callback
() => unknown
required

callTransfer

Transfer the call to another destination (e.g. a SIP address).
token
string
required
Auth token for the transfer.
transferTo
string
required
Destination to transfer to; ignored if empty.

cancelGeneration

Cancel any in-flight model generation.

changePipeline

Switch the whole pipeline to a different mode mid-session.
pipelineMode
string
required
New pipeline mode (e.g. ‘cascade’, ‘hybrid_stt’).
components
Array<[string, string, Record<string, string> | null]>
required
Array of [component, provider, params] triples to reconfigure.

clearContext

Clear the running conversation history. With keepSystemPrompt (default true), the agent’s instructions are kept and only the turns are cleared.
opts
{ keepSystemPrompt?: boolean }
returns
Promise<boolean>
Whether the clear was applied.

close

End the session: run onExit, fire shutdown callbacks, disconnect, and clean up.
opts
{ reason?: string }

closeEmitter

Close the emitter: drop all handlers and stop emitting. Waits up to 2 seconds for in-flight async handlers to settle before returning.

contextToAnthropic

Fetch the live conversation context and render it as Anthropic Messages.
returns
Promise<{ messages: Array<Record<string, any>>; system: string | null; }>

contextToDict

Fetch the live conversation context and serialize it to a plain object.
returns
Promise<Record<string, any>>

contextToGoogle

Fetch the live conversation context and render it as Google Gemini contents.
returns
Promise<{ contents: Array<Record<string, any>>; systemInstruction: string | null; }>

contextToOpenai

Fetch the live conversation context and render it as OpenAI chat messages.
opts
{ reasoningModel?: boolean }
returns
Promise<Array<Record<string, any>>>

emit

event
string
required

fetchChatContext

Fetch the conversation as a ChatContext from the live session.
opts
{ lastN?: number }
returns
Promise<ChatContext>

fetchContextHistory

Fetch the conversation history from the live session (falling back to the local cache).
opts
{ lastN?: number; includeFunctionCalls?: boolean; includeSystemMessages?: boolean }
returns
Promise<Record<string, any>[]>

generate

Prompt the model to generate a response to text (spoken via the pipeline).
text
string
required

getContextHistory

Return the conversation history. The result is an array of message records that is also awaitable: use it synchronously for the cached snapshot, or await it to fetch the latest from the live session.
opts
{ lastN?: number; includeFunctionCalls?: boolean; includeSystemMessages?: boolean }
returns
_HistoryAwaitable

handoffs

Copy of the handoffs that have occurred this session, in order.
returns
AgentHandoff[]

hangup

Hang up the call (closes the session).
reason

injectContext

Inject every message from a ChatContext; returns true only if all succeeded.
ctx
ChatContext
required
returns
Promise<boolean>

injectMessage

Insert a message into the conversation history out-of-band.
message
| ChatMessage | { role: ChatRole | string; content: string; messageId?: string; images?: ImageContent[] }
required
opts
{ position?: string }
returns
Promise<boolean>
true if the live session accepted the message.

interceptToolResult

If a tool returned an Agent, convert it into a handoff directive; otherwise return the result unchanged.
result
any
required
returns
any

interrupt

Interrupt the agent’s pending utterances and cancel any in-flight generation.
opts
{ force?: boolean }

lastHandoffReason

Reason for the most recent handoff, or '' if none.
returns
string

leave

Leave the call (closes the session with reason 'sdk_leave').

listenerCount

event
string
required
returns
number

off

event
string
required
handler
EventHandler
required

on

event
string
required
handler
EventHandler
required
returns
EventHandler

once

event
string
required
handler
EventHandler
required
returns
EventHandler

playBackgroundAudio

Play a background audio clip. config may be a URL/path string or a config object with file_url/volume/looping. Set enabled: false to skip.
config
any

preloadBackgroundAudio

Preload a background audio clip for low-latency playback. Accepts the same config as playBackgroundAudio.
config
any

publishMessage

Publish a message on a pub/sub topic to other participants/agents.
config
{ topic: string; message?: unknown; options?: Record<string, unknown> | null; payload?: unknown; }
required

pushAudioFrame

Push a raw PCM audio frame into the call (e.g. for custom input).
pcm
Buffer | Uint8Array
required
sampleRate
Sample rate of the PCM data in Hz. Defaults to 48000.

registerHandoffAgent

Register an agent as a valid handoff target and return its id.
agent
Agent
required
returns
string

removeAllListeners

event
string

removeMessage

Remove a message from the conversation history by id.
messageId
string
required
returns
Promise<boolean>
true if the message was removed, false otherwise.

reply

Generate and speak a model reply to instructions, optionally grounded on image frames.
instructions
string
required
opts
{ waitForPlayback?: boolean; // eslint-disable-next-line @typescript-eslint/no-explicit-any frames?: any[]; latestFrames?: number; interruptible?: boolean; }
returns
Promise<UtteranceHandle>
A handle to await or interrupt the utterance.

say

Speak message verbatim via TTS.
message
string
required
opts
{ interruptible?: boolean; voice?: string; // eslint-disable-next-line @typescript-eslint/no-explicit-any audioData?: any; addToChatContext?: boolean; // eslint-disable-next-line @typescript-eslint/no-explicit-any [k: string]: any; }
returns
Promise<UtteranceHandle>
A handle to await or interrupt the utterance.

sendA2A

Send an agent-to-agent (A2A) message to targetAgentId. A2A is delivered over pub/sub (topic a2a/<targetAgentId>): the message is published as a JSON envelope { source_agent_id, message_json, correlation_id }. The receiving agent must have called subscribeA2A to receive it (surfaced as an a2a_message event).
targetAgentId
string
required
messageJson
string
required
correlationId

sendImage

Send an image to the model for vision. Non-byte inputs are encoded to JPEG.
data
any
required
mimeType
MIME type for raw bytes. Defaults to 'image/jpeg'.

sendMessageWithFrames

Send a message together with image frames for a vision-grounded response.
message
string | null
required
frames
any[]
required
Frames as [bytes, mime] tuples, captured vision frames, or raw bytes.
opts
{ defaultMimeType?: string; numLatestFrames?: number }

setUserInputEnabled

Enable or disable accepting user input (e.g. to mute the user during a prompt).
enabled
boolean
required

start

Connect the session to the Zero Runtime and run the agent. Optionally waits for a participant and/or runs until shutdown. See AgentSessionStartOptions.
opts
AgentSessionStartOptions

startRecording

Start recording the call.
config
any
Recording config; falls back to the session-level recording= if omitted.

startThinkingAudio

Start the agent’s configured “thinking” audio loop (see agent.setThinkingAudio).

stopBackgroundAudio

Stop any background audio playback.

stopRecording

Stop the active call recording.

stopThinkingAudio

Stop the “thinking” audio loop.

subscribeA2A

Subscribe the active agent to its agent-to-agent (A2A) topic so it receives messages addressed to its id, surfaced as a2a_message events.

subscribePubSub

Subscribe to a pub/sub topic. The optional callback fires for matching messages.
topic
string
required
callback
(msg: { topic: string; message: string; sender_id: string; sender_name: string; timestamp: string; payload: unknown; }) => void
returns
Promise<((msg: any) => void) | null>
The registered handler (or null) so it can later be removed via session.off('pubsub_message', handler).

summarizeContext

Summarize and compress the conversation now (fire-and-forget).

updateAgentState

Set the AgentState and emit agent_state_changed.
state
AgentState
required

updateContextWindow

Retune the conversation context-window budget live (mid-session). Knobs mirror ContextWindow and take effect on the next model turn; omitted knobs are left unchanged.
opts
{ maxTokens?: number; maxContextItems?: number; keepRecentTurns?: number }

updateInstructions

Replace the active agent’s instructions and apply the update to the live session.
instructions
string
required

updateInterruptConfig

Tune interruption handling at runtime. Only the fields you set are applied.
opts
{ mode?: string; interruptMinDuration?: number; interruptMinWords?: number; cooldownMs?: number; falseInterruptPauseDurationMs?: number; resumeOnFalseInterrupt?: boolean; }

updateProvider

Swap a pipeline component’s provider at runtime.
component
string
required
Component to update (e.g. 'stt', 'llm', 'tts').
provider
string
required
New provider identifier.
params
Record<string, any> | null
Optional provider parameters. Defaults to null.

updateRecordingState

Update the cached recording status and emit recording_status_changed.
status
Record<string, any>
required

updateTools

Replace the active agent’s tools and apply the update to the live session.
tools
any[]
required

updateUserState

Set the UserState and emit user_state_changed (and speech_in when speaking).
state
UserState
required

waitForParticipantArrived

Resolve once a participant has joined the call, or the session shuts down first (whichever happens sooner). Returns immediately if a participant is already present.

waitForSynthesisDone

Resolve once the agent has finished speaking.
timeout
number
Optional timeout in seconds.
returns
Promise<boolean>
true if synthesis completed, false if the timeout elapsed first.

warmTransfer

Not implemented; use agentSwitch(...) for multi-agent handoff. Always throws.
returns
Promise<never>

serve

Register an agent with the Zero Runtime and serve sessions dispatched to it. Registers under options.agentId (or the agent’s own id) and runs until the process receives a shutdown signal, starting a new AgentSession for each dispatched session. Pair with invoke to start sessions against the registered agent.
agent
Agent | AgentFactory | AgentClass
required
One of: a configured Agent instance; a zero-arg Agent subclass (the class itself, e.g. serve(MyAgent)); or an AgentFactory returning an Agent. A class or factory yields a fresh Agent + Pipeline per call - required for correct per-call state and pipeline hooks under concurrent calls. A shared instance is still accepted for simple, stateless agents. In every case the agent must carry a pipeline and an id.
options
ServeOptions
Registration, capacity, and debug settings. See ServeOptions.

invoke

Start a session for a registered agent. Dispatches to the agent registered under agentId (the id you passed to serve), gives it a room (auto-created when none is supplied) plus any SIP and per-call config, and returns the new session’s ids.
agentId
string
required
The id the target agent registered with via serve.
options
InvokeOptions
Room, SIP, routing, and timeout settings. See InvokeOptions.
returns
Promise<InvokeResult>
The started session’s ids and an optional playground URL.

Room

Create a Room config for invoke.

Constructor

roomId
string | null
Existing room to join. When omitted, a room is auto-created.
authToken
string | null
ZRT auth token. Falls back to ZRT_AUTH_TOKEN / ZRT_API_KEY + ZRT_SECRET_KEY.
agentName
string | null
Display name for the agent participant. Defaults to the agentId.
playground
boolean
Whether to return a playground URL in the result. Defaults to true.
vision
boolean
Enable video/vision input. Defaults to false.
recording
boolean
Enable session recording. Defaults to false.
backgroundAudio
boolean
Enable background audio. Defaults to false.
audioListenerEnabled
boolean
Enable the audio listener. Defaults to false.
autoEndSession
boolean
End the session automatically on completion. Defaults to true.
sessionTimeoutSeconds
number | null
Maximum session length in seconds; truncated to an integer. Defaults to 15; pass null to omit.
noParticipantTimeoutSeconds
number | null
Seconds to wait with no participant before ending; truncated to an integer. Defaults to 90; pass null to omit.
agentParticipantId
string | null
Fixed participant id for the agent. Defaults to assigned automatically.
signalingBaseUrl
string | null
Base URL of the signaling service. Defaults to the standard endpoint.
sendLogsToDashboard
boolean
Forward session logs to the dashboard. Defaults to true.
dashboardLogLevel
string
Minimum dashboard log level (DEBUG/INFO/WARNING/ERROR/CRITICAL). Defaults to 'INFO'.

Sip

Create a Sip config for invoke.

Constructor

callTo
string | null
Destination phone number / SIP URI.
callFrom
string | null
Caller phone number / SIP URI.
callType
string | null
Call direction, e.g. 'inbound' or 'outbound'.
callId
string | null
Caller-supplied unique call identifier.
webhookUrl
string | null
Webhook URL to notify about call events.
extra
Record<string, string>
Extra key/value metadata merged into the call’s dispatch metadata.