The handler context
Reference for ctx, the object every handler receives, with say, ask, handoff, endCall, memory, metadata and the errors they throw.
Every tool, hook and trigger handler receives a ctx beside its input. It is a snapshot of the call plus calls back to the platform. It is built fresh for each invocation, so keep state in ctx.metadata, not in worker memory.
A call that the platform refuses rejects with a HandlerContextError. Branch on its code.
HandlerContext
interface · @voicelayer/sdk
interface HandlerContextWhat every handler receives beside its input: a snapshot of the call and calls back to the platform that speak, hand off or end the call. It is built fresh for each invocation and nothing in it outlives the invocation, so keep state in ctx.metadata, never in worker memory. Each call back needs the invocation to be open: once the call has ended, the platform cancelled the invocation or its deadline passed, the call rejects with a HandlerContextError.
Fields
| Name | Type | Required | Description |
|---|---|---|---|
call | CallInfo | yes | A snapshot of the call: its id, the caller, the number called and when it started. |
channel | object | yes | What kind of conversation this is. kind is voice or text; label is for display only. Branch on ctx.capabilities, never on the label. |
channel.kind | ChannelKind | yes | voice or text. One of voice, text. |
channel.label | string | yes | A display name for the channel. Never branch on it. |
capabilities | WorkerCapabilities | yes | What this conversation supports: canBargeIn, canReceiveDtmf, canPublishDtmf, hasStreamingTranscripts and canUpdateInstructions. Branch on these instead of on channel. |
language | string | yes | The language the call is in now, as a BCP 47 tag such as gu-IN: the language the platform has followed the caller into, or the one the call started in. It is read again on every invocation, so a handler sees a change at its next call. |
process | ProcessSnapshot | undefined | yes | The agent's captured process fields so far, refreshed each invocation. undefined when the agent declares no process. |
metadata | Record<string, unknown> | yes | Scratch space held by the platform for the call. It arrives with each invocation and the keys this handler changes go back with its reply (a JSON merge patch, the last writer wins per key). Two invocations of one call may run on two processes, so never keep call state in worker memory. A real caller value written here reaches a handler that was not allowed real values as a placeholder. |
memory | MemoryHandle | yes | The agent's memory: get and set for the call's own values, search for what the platform remembers about the caller. |
connectors | Readonly<Record<string, unknown>> | yes | The connector objects you passed in the agent's connectors, by key. They stay in your process and never cross to the platform. |
signal | AbortSignal | yes | Aborted when the platform cancels the invocation (the caller interrupted, a newer turn took over, the call ended) or its time limit passes. Pass it to fetch and other cancellable work. |
handler | string | yes | The id of the handler this invocation runs, such as tool.lookup_order or hook.onCallEnd. |
realValues | boolean | yes | Whether this invocation's arguments and snapshots carry the caller's real values. True only for a tool or agent that set sendRealValues; each release is recorded. |
recordEvent
recordEvent(event: RecordEventInput): voidAdd an event to the call's timeline. It returns at once and does not wait for the platform.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
event | RecordEventInput | yes | The event to record. |
Returns
void
Throws
- HandlerContextError with code
invalid_argswhen the event is malformed.
watchFormSession
watchFormSession(token: string): () => voidSubscribe the call to the values a person enters on a form page, so the agent hears them as they are typed. Returns the function that stops watching; watching ends with the call at the latest.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
token | string | yes | The form session's token, from the form link. |
Returns
() => void
Throws
- HandlerContextError with code
unsupported_on_channelon a text conversation.
say
say(text: string, opts?: SayOptions): Promise<SayResult>Speak exactly this text to the caller, without a model call. The text passes the agent's output checks before it is spoken.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
text | string | yes | What to say. |
opts | SayOptions | no | Set waitPlayout to wait until the caller has heard it. |
Returns
Promise<SayResult>
Throws
- HandlerContextError with code
scope_closedwhen the call or invocation has ended,guard_deniedwhen the agent's capabilities do not allow it,unsupported_on_channelon a text conversation.
Example
await ctx.say('One moment while I look that up.', { waitPlayout: true });respond
respond(instructionsOrOpts?: string | RespondOptions): Promise<void>Have the model produce the next reply now, optionally with extra instructions for that reply.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
instructionsOrOpts | string | RespondOptions | no | Extra instructions as a string, or a RespondOptions object. |
Returns
Promise<void>
Throws
- HandlerContextError with code
scope_closedwhen the call or invocation has ended,guard_deniedwhen the agent's capabilities do not allow it.
Example
await ctx.respond('Confirm the order number back to the caller.');ask
ask(question: string): Promise<string>Ask the caller a question and resolve with what they answer. Voice only.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
question | string | yes | The question to speak. |
Returns
Promise<string>
Throws
- HandlerContextError with code
unsupported_on_channelon a text conversation,scope_closedwhen the call or invocation has ended,cancelledwhen the invocation is cancelled while waiting.
Example
const email = await ctx.ask('What email address should I send the receipt to?');handoff
handoff(to: string, opts?: HandoffOptions): Promise<void>Transfer the call to a person or number. The destination must be declared in the agent's handoff or allowed by the workspace's outbound policy.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
to | string | yes | The destination: a phone number, or a name from handoff.routes. |
opts | HandoffOptions | no | Why, what to brief the receiver with, and whether to brief first (warm) or connect at once (cold). |
Returns
Promise<void>
Throws
- HandlerContextError with code
guard_deniedwhen the destination is not allowed,scope_closedwhen the call or invocation has ended.
Example
await ctx.handoff('billing', { reason: 'refund over the limit', mode: 'warm' });endCall
endCall(opts?: { reason? }): Promise<void>End the call. The agent's endCall.onEnd handler runs first and may take over teardown.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
opts | object | no | A reason recorded on the call. |
opts.reason | string | no | Why the call is ending, recorded on the call. |
Returns
Promise<void>
Throws
- HandlerContextError with code
scope_closedwhen the call has already ended.
sendDtmf
sendDtmf(digits: string, opts?: SendDtmfOptions): Promise<void>Press keys on the line, for example to move through another phone menu.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
digits | string | yes | The keys to press: 0 to 9, *, #. |
opts | SendDtmfOptions | no | Set delayMs to space the digits out. |
Returns
Promise<void>
Throws
- HandlerContextError with code
unsupported_on_channelon a text conversation,invalid_argswhendigitshas any other character,scope_closedwhen the call has ended.
CallInfo
interface · @voicelayer/sdk
interface CallInfoThe call a handler is running in, as a snapshot taken when the handler was invoked. Caller values are placeholders unless the handler's tool, or the agent, opted in with sendRealValues.
Fields
| Name | Type | Required | Description |
|---|---|---|---|
callId | string | yes | The call's id, the same one the dashboard and the API show. |
callerId | string | yes | The caller's number (a placeholder like <PII_PHONE_1> unless real values were released to this handler). |
to | string | null | yes | The number that was called. |
startedAt | Date | yes | When the call started. |
metadata | Readonly<Record<string, unknown>> | yes | The metadata the call was started with, read only. To keep state across handlers, use ctx.metadata. |
ProcessSnapshot
interface · @voicelayer/sdk
interface ProcessSnapshotThe fields the agent's process has captured so far, refreshed on every invocation. Values are placeholders unless the handler was allowed real values.
Fields
| Name | Type | Required | Description |
|---|---|---|---|
data | Readonly<Record<string, unknown>> | yes | The captured fields by name. A field that is not captured yet is absent. |
complete | boolean | yes | Whether the process's completeWhen rule is met. |
MemoryHandle
interface · @voicelayer/sdk
interface MemoryHandleRead and write what the agent remembers. get and set are the call's own key-value space; search asks the platform's memory about the caller.
get
get(key: string): Promise<unknown>Read a value stored under key; resolves undefined when there is none.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
key | string | yes | The name the value was stored under. |
Returns
Promise<unknown>
set
set(key: string, value: unknown): Promise<void>Store a JSON value under key, for the lifetime set by the agent's memory.scope.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
key | string | yes | The name to store it under. |
value | unknown | yes | Any JSON value. |
Returns
Promise<void>
search
search(query: string): Promise<{ readonly facts: readonly { readonly text: string; readonly type: "fact" | "observation"; readonly occurredAt: string | null; readonly mentionedAt: string | null; }[]; readonly degraded: boolean; }>What the platform remembers about the person matching query: remembered facts, screened before they reach you. The person is the call's own, bound by the platform, so you never name them. On a voice call the search waits at most 100 ms: a late or failed search resolves { facts: [], degraded: true }. Code running outside the platform gets facts only when the agent version opted in; without it the result is { facts: [], degraded: false }.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
query | string | yes | What to look for, in plain words. |
Returns
Promise<{ readonly facts: readonly { readonly text: string; readonly type: "fact" | "observation"; readonly occurredAt: string | null; readonly mentionedAt: string | null; }[]; readonly degraded: boolean; }>
SayOptions
interface · @voicelayer/sdk
interface SayOptionsOptions for ctx.say.
Fields
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
waitPlayout | boolean | no | false | Resolve only after the speech has played out, with what the caller heard. |
SayResult
interface · @voicelayer/sdk
interface SayResultWhat ctx.say resolves with.
Fields
| Name | Type | Required | Description |
|---|---|---|---|
interrupted | boolean | yes | Whether the caller talked over the speech before it finished. |
heard | string | no | The part of the text the caller heard. Set only when the call used waitPlayout. |
RespondOptions
interface · @voicelayer/sdk
interface RespondOptionsOptions for ctx.respond.
Fields
| Name | Type | Required | Description |
|---|---|---|---|
instructions | string | no | Extra guidance for this one reply, added to the agent's prompt for the turn. |
HandoffOptions
interface · @voicelayer/sdk
interface HandoffOptionsOptions for ctx.handoff.
Fields
| Name | Type | Required | Description |
|---|---|---|---|
reason | string | no | Why the call is being handed off. Recorded on the call and shown to the receiving person. |
briefing | string | no | What to tell the receiving person before they take the call. |
mode | 'warm' | 'cold' | no | warm briefs the receiver before connecting the caller; cold connects straight away. Overrides the agent's handoff.mode for this handoff. |
SendDtmfOptions
interface · @voicelayer/sdk
interface SendDtmfOptionsOptions for ctx.sendDtmf.
Fields
| Name | Type | Required | Description |
|---|---|---|---|
delayMs | number | no | Milliseconds between consecutive digits. |
RecordEventInput
interface · @voicelayer/sdk
interface RecordEventInputAn event for the call's timeline, recorded with ctx.recordEvent.
Fields
| Name | Type | Required | Description |
|---|---|---|---|
kind | string | yes | A name for the event, for example order_looked_up. It appears on the conversation timeline. |
source | 'agent' | 'caller' | 'form' | 'platform' | no | Who the event is attributed to. |
data | Record<string, unknown> | no | Extra JSON details shown with the event. |
HandlerContextError
class · @voicelayer/sdk
class HandlerContextError extends ErrorThrown when a call back to the platform is refused or fails. Branch on code, never on the message text. Codes: scope_closed (the call or invocation has ended), guard_denied (the agent's capabilities do not allow it), unsupported_on_channel (voice-only on a text conversation), invalid_args (the arguments are malformed), cancelled (the platform cancelled the invocation), deadline_exceeded (it ran past its time limit), lost (the connection to the platform dropped) and no_scope (called outside a handler).
new HandlerContextError(code: string, message: string, reason?: string)Fields
| Name | Type | Required | Description |
|---|---|---|---|
code | string | yes | The refusal or failure code, listed above. |
reason | string | no | A longer reason when the platform gave one. |