Reference

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 HandlerContext

What 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

NameTypeRequiredDescription
callCallInfoyesA snapshot of the call: its id, the caller, the number called and when it started.
channelobjectyesWhat kind of conversation this is. kind is voice or text; label is for display only. Branch on ctx.capabilities, never on the label.
channel.kindChannelKindyesvoice or text. One of voice, text.
channel.labelstringyesA display name for the channel. Never branch on it.
capabilitiesWorkerCapabilitiesyesWhat this conversation supports: canBargeIn, canReceiveDtmf, canPublishDtmf, hasStreamingTranscripts and canUpdateInstructions. Branch on these instead of on channel.
languagestringyesThe 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.
processProcessSnapshot | undefinedyesThe agent's captured process fields so far, refreshed each invocation. undefined when the agent declares no process.
metadataRecord<string, unknown>yesScratch 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.
memoryMemoryHandleyesThe agent's memory: get and set for the call's own values, search for what the platform remembers about the caller.
connectorsReadonly<Record<string, unknown>>yesThe connector objects you passed in the agent's connectors, by key. They stay in your process and never cross to the platform.
signalAbortSignalyesAborted 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.
handlerstringyesThe id of the handler this invocation runs, such as tool.lookup_order or hook.onCallEnd.
realValuesbooleanyesWhether 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): void

Add an event to the call's timeline. It returns at once and does not wait for the platform.

Parameters
NameTypeRequiredDescription
eventRecordEventInputyesThe event to record.
Returns

void

Throws
  • HandlerContextError with code invalid_args when the event is malformed.

watchFormSession

watchFormSession(token: string): () => void

Subscribe 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
NameTypeRequiredDescription
tokenstringyesThe form session's token, from the form link.
Returns

() => void

Throws
  • HandlerContextError with code unsupported_on_channel on 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
NameTypeRequiredDescription
textstringyesWhat to say.
optsSayOptionsnoSet waitPlayout to wait until the caller has heard it.
Returns

Promise<SayResult>

Throws
  • HandlerContextError with code scope_closed when the call or invocation has ended, guard_denied when the agent's capabilities do not allow it, unsupported_on_channel on 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
NameTypeRequiredDescription
instructionsOrOptsstring | RespondOptionsnoExtra instructions as a string, or a RespondOptions object.
Returns

Promise<void>

Throws
  • HandlerContextError with code scope_closed when the call or invocation has ended, guard_denied when 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
NameTypeRequiredDescription
questionstringyesThe question to speak.
Returns

Promise<string>

Throws
  • HandlerContextError with code unsupported_on_channel on a text conversation, scope_closed when the call or invocation has ended, cancelled when 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
NameTypeRequiredDescription
tostringyesThe destination: a phone number, or a name from handoff.routes.
optsHandoffOptionsnoWhy, 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_denied when the destination is not allowed, scope_closed when 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
NameTypeRequiredDescription
optsobjectnoA reason recorded on the call.
opts.reasonstringnoWhy the call is ending, recorded on the call.
Returns

Promise<void>

Throws
  • HandlerContextError with code scope_closed when 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
NameTypeRequiredDescription
digitsstringyesThe keys to press: 0 to 9, *, #.
optsSendDtmfOptionsnoSet delayMs to space the digits out.
Returns

Promise<void>

Throws
  • HandlerContextError with code unsupported_on_channel on a text conversation, invalid_args when digits has any other character, scope_closed when the call has ended.

CallInfo

interface · @voicelayer/sdk

interface CallInfo

The 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

NameTypeRequiredDescription
callIdstringyesThe call's id, the same one the dashboard and the API show.
callerIdstringyesThe caller's number (a placeholder like <PII_PHONE_1> unless real values were released to this handler).
tostring | nullyesThe number that was called.
startedAtDateyesWhen the call started.
metadataReadonly<Record<string, unknown>>yesThe metadata the call was started with, read only. To keep state across handlers, use ctx.metadata.

ProcessSnapshot

interface · @voicelayer/sdk

interface ProcessSnapshot

The fields the agent's process has captured so far, refreshed on every invocation. Values are placeholders unless the handler was allowed real values.

Fields

NameTypeRequiredDescription
dataReadonly<Record<string, unknown>>yesThe captured fields by name. A field that is not captured yet is absent.
completebooleanyesWhether the process's completeWhen rule is met.

MemoryHandle

interface · @voicelayer/sdk

interface MemoryHandle

Read 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
NameTypeRequiredDescription
keystringyesThe 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
NameTypeRequiredDescription
keystringyesThe name to store it under.
valueunknownyesAny 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
NameTypeRequiredDescription
querystringyesWhat 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 SayOptions

Options for ctx.say.

Fields

NameTypeRequiredDefaultDescription
waitPlayoutbooleannofalseResolve only after the speech has played out, with what the caller heard.

SayResult

interface · @voicelayer/sdk

interface SayResult

What ctx.say resolves with.

Fields

NameTypeRequiredDescription
interruptedbooleanyesWhether the caller talked over the speech before it finished.
heardstringnoThe part of the text the caller heard. Set only when the call used waitPlayout.

RespondOptions

interface · @voicelayer/sdk

interface RespondOptions

Options for ctx.respond.

Fields

NameTypeRequiredDescription
instructionsstringnoExtra guidance for this one reply, added to the agent's prompt for the turn.

HandoffOptions

interface · @voicelayer/sdk

interface HandoffOptions

Options for ctx.handoff.

Fields

NameTypeRequiredDescription
reasonstringnoWhy the call is being handed off. Recorded on the call and shown to the receiving person.
briefingstringnoWhat to tell the receiving person before they take the call.
mode'warm' | 'cold'nowarm 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 SendDtmfOptions

Options for ctx.sendDtmf.

Fields

NameTypeRequiredDescription
delayMsnumbernoMilliseconds between consecutive digits.

RecordEventInput

interface · @voicelayer/sdk

interface RecordEventInput

An event for the call's timeline, recorded with ctx.recordEvent.

Fields

NameTypeRequiredDescription
kindstringyesA name for the event, for example order_looked_up. It appears on the conversation timeline.
source'agent' | 'caller' | 'form' | 'platform'noWho the event is attributed to.
dataRecord<string, unknown>noExtra JSON details shown with the event.

HandlerContextError

class · @voicelayer/sdk

class HandlerContextError extends Error

Thrown 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

NameTypeRequiredDescription
codestringyesThe refusal or failure code, listed above.
reasonstringnoA longer reason when the platform gave one.