Reference

Direct mode

Reference for serveDirect, onMessage and the types of a message and its context in direct mode.

Direct mode lets your own code answer text conversations through the API, with every platform check still running on the server. Use agent.onMessage(handler), or serveDirect on its own.

Import from @voicelayer/sdk/direct (also exported from @voicelayer/sdk). For a walk-through, see Direct mode.

serveDirect

function · @voicelayer/sdk/direct

serveDirect(handler: MessageHandler, opts?: ServeDirectOptions): Promise<DirectRunner>

Serve a handler in direct mode. Resolves once the stream is being consumed; runner.stop() or the signal ends it.

Parameters
NameTypeRequiredDescription
handlerMessageHandleryesCalled with each inbound message and a context to answer through.
optsServeDirectOptionsnoThe scoped API key, channel filter, cursor store and the rest of ServeDirectOptions.
Returns

Promise<DirectRunner>: The running DirectRunner.

Throws
  • DirectKeyError when there is no key, or it is a worker credential.
Example
import { serveDirect } from '@voicelayer/sdk/direct';

const runner = await serveDirect(async (message, ctx) => {
  await ctx.send({ text: `You said: ${message.text}` });
}, { channels: ['sms'] });

ServeDirectOptions

interface · @voicelayer/sdk/direct

interface ServeDirectOptions

Options for direct mode. The defaults read the scoped API key and API address from the environment, so a program often passes none.

Fields

NameTypeRequiredDefaultDescription
apiKeystringnoA scoped REST key (messages:send, messages:read, events:read, conversations:control). Default VOICELAYER_API_KEY. A vlw_ worker credential is refused.
baseUrlstringnoDefault VOICELAYER_API_URL, else https://api.vlayers.ai.
channelsreadonly string[]noOnly these channels' messages reach the handler (one channel also narrows the stream server-side).
cursorStoreCursorStorenoWhere to keep the place in the event stream, so a restart continues where it stopped.
signalAbortSignalnoStops the runner (as stop()).
logDirectLoggernoWhere the runner writes its log lines: an object with debug, info, warn and error functions that take a message and fields.
onHandlerError(err: unknown, message: InboundMessage) => voidnoTold about a handler that threw (after it is logged); the runner moves on to the next message.
fetchtypeof fetchnoTests and proxies.
reconnectobjectnoStream reconnect tuning (defaults: 500 ms first delay, 30 s cap, 45 s idle timeout).
reconnect.initialDelayMsnumberno500The wait before the first reconnect, in milliseconds.
reconnect.maxDelayMsnumberno30000The longest wait between reconnects, in milliseconds.
reconnect.idleTimeoutMsnumberno45000Reconnect when the stream is silent this long, in milliseconds.
envNodeJS.ProcessEnvnoRead in tests: the process environment the defaults come from.

DirectRunner

class · @voicelayer/sdk

class DirectRunner

The runner behind direct mode. It reads the event stream of conversations whose controller is api, calls your handler for each inbound message in order per conversation, and stops with stop() or its abort signal. Create one with serveDirect.

new DirectRunner(handler: MessageHandler, opts?: ServeDirectOptions)

Fields

NameTypeRequiredDescription
clientClientyesThe scoped REST client the runner uses, for anything else the key may do.
donePromise<void>yesSettles when the runner has stopped: resolves on stop() or the abort signal, rejects when the stream gives up.
cursorstring | undefinedyesThe newest cursor whose event and every earlier one are finished.

start

start(): Promise<void>

Start consuming the event stream. Resolves once it is being consumed.

Returns

Promise<void>

stop

stop(): Promise<void>

Stop consuming and wait for the running handlers to finish.

Returns

Promise<void>

MessageHandler

type · @voicelayer/sdk

type MessageHandler = (message: InboundMessage, ctx: MessageContext) => unknown | Promise<unknown>

Your function for direct mode: called with each inbound message and a context to answer through. What it returns is ignored. A throw is logged and reported to onHandlerError; the runner moves on to the next message.

InboundMessage

interface · @voicelayer/sdk

interface InboundMessage

A message from a person, handed to your onMessage handler.

Fields

NameTypeRequiredDescription
idstringyesThe message's public id.
channelstringyesThe channel it arrived on, such as sms or whatsapp.
conversationIdstringyesThe conversation it belongs to.
fromstring | nullyesThe person's address on the channel (a phone number, a chat id); null when the channel hides it.
textstring | nullyesThe message text, or null for a message with only media.
mediaobject[]yesAttachments, each with a URL and a content type (or null).
media.urlstringyesWhere the attachment can be fetched.
media.contentTypestring | nullyesThe attachment's content type, or null when unknown.
windowobjectyesThe reply window of a channel that has one (WhatsApp's 24 hours): whether it is open and when it closesAt. null on a channel without one.
window.openbooleanyesWhether you can still reply freely.
window.closesAtstring | nullyesWhen the window closes, as an ISO timestamp, or null.
controllerControlleryesAlways api when a handler runs: other conversations are skipped. One of agent, api, human.
createdAtstringyesWhen the message was created, as an ISO timestamp.

MessageContext

interface · @voicelayer/sdk

interface MessageContext

What your handler answers through.

Fields

NameTypeRequiredDescription
conversationPublicConversationyesThe conversation as read when the message was handed over.
clientClientyesThe scoped REST client, for anything else the key may do.
signalAbortSignalyesAborted when the runner stops.

send

send(input: SendInput): Promise<SentMessage>

Reply in this conversation. Idempotent per inbound message and call order, so a redelivered event never sends twice.

Parameters
NameTypeRequiredDescription
inputSendInputyesThe reply: { text } or { content }.
Returns

Promise<SentMessage>: The sent message.

Throws
  • OutputRefusedError when the output checks refuse the text; nothing is sent.
  • VoiceLayerApiError for any other API failure.
Example
await ctx.send({ text: 'Thanks, we will call you back.' });

setController

setController(to: Controller, opts?: { reason? }): Promise<PublicConversation>

Hand the conversation to the agent or a person (human), or keep it with your code (api).

Parameters
NameTypeRequiredDescription
toControlleryesWho answers from now on. One of agent, api, human.
optsobjectnoA reason recorded on the conversation.
opts.reasonstringnoWhy the conversation changed hands, recorded on it.
Returns

Promise<PublicConversation>: The updated conversation.

assign

assign(userId: string | null): Promise<PublicConversation>

Assign the conversation to one person on your team, by user id, or to nobody with null. It does not change whose turn it is to answer.

Parameters
NameTypeRequiredDescription
userIdstring | nullyesThe team member's user id, or null.
Returns

Promise<PublicConversation>: The updated conversation.

SendInput

type · @voicelayer/sdk

type SendInput = { readonly text: string } | { readonly content: ReplyContent }

What ctx.send takes: { text }, or { content } for any reply content the API accepts.

ReplyContent

type · @voicelayer/sdk/direct

type ReplyContent = | { readonly type: 'text'; readonly text: string } | { readonly type: 'media'; readonly media: readonly { readonly url: string }[]; readonly caption?: string } | { readonly type: 'template'; readonly template: { readonly name: string; readonly language?: string; readonly variables?: Readonly<Record<string, string>> } }

Reply content: text, media (URLs with an optional caption) or a template (a name, a language and variables).

SentMessage

interface · @voicelayer/sdk/direct

interface SentMessage

The message that was sent.

Fields

NameTypeRequiredDescription
idstringyesThe message's id.
statusstringyesIts delivery status when sent.

Controller

type · @voicelayer/sdk/direct

type Controller = 'agent' | 'api' | 'human'

Who answers a conversation: the agent (the platform's model), your code over the API (api), or a human.

One of agent, api, human.

CursorStore

interface · @voicelayer/sdk

interface CursorStore

Where the runner keeps its place in the event stream across restarts: a file, a row, a key. Without one a restart resumes live.

load

load(): Promise<string | null>

Read the saved cursor, or null when there is none.

Returns

Promise<string | null>

save

save(cursor: string): Promise<void>

Save the newest cursor.

Parameters
NameTypeRequiredDescription
cursorstringyesThe cursor to keep.
Returns

Promise<void>

memoryCursorStore

function · @voicelayer/sdk/direct

memoryCursorStore(initial?: string | null): CursorStore & { readonly value: string | null; }

A cursor store kept in memory. A restart loses it, so use it for tests and demos; value shows the saved cursor.

Parameters
NameTypeRequiredDefaultDescription
initialstring | nullnonullA cursor to start with.
Returns

CursorStore & { readonly value: string | null; }: The store.

assertDirectKey

function · @voicelayer/sdk/direct

assertDirectKey(key: string | undefined): string

Check that a key is a scoped REST key for direct mode and return it.

Parameters
NameTypeRequiredDescription
keystring | undefinedyesThe key to check.
Returns

string: The same key.

Throws
  • DirectKeyError when the key is missing or is a worker credential (vlw_…).

DirectKeyError

class · @voicelayer/sdk

class DirectKeyError extends Error

Thrown when direct mode has no API key, or was given a worker credential (vlw_…) instead of a scoped REST key.

new DirectKeyError(message?: string)
new DirectKeyError(message?: string | undefined, options?: ErrorOptions | undefined): DirectKeyError

OutputRefusedError

class · @voicelayer/sdk

class OutputRefusedError extends Error

Thrown by ctx.send when the output checks refuse the reply. Nothing was sent. code is output_refused, with the API error and requestId for support.

new OutputRefusedError(apiError: VoiceLayerApiError)

Fields

NameTypeRequiredDescription
code"output_refused"yesAlways output_refused.
requestIdstring | undefinedyesThe API request's id, to quote to support.
detailsRecord<string, unknown> | undefinedyesWhat the checks reported, when they said.
apiErrorVoiceLayerApiErroryesThe underlying API error.