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
| Name | Type | Required | Description |
|---|---|---|---|
handler | MessageHandler | yes | Called with each inbound message and a context to answer through. |
opts | ServeDirectOptions | no | The 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 ServeDirectOptionsOptions for direct mode. The defaults read the scoped API key and API address from the environment, so a program often passes none.
Fields
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
apiKey | string | no | A scoped REST key (messages:send, messages:read, events:read, conversations:control). Default VOICELAYER_API_KEY. A vlw_ worker credential is refused. | |
baseUrl | string | no | Default VOICELAYER_API_URL, else https://api.vlayers.ai. | |
channels | readonly string[] | no | Only these channels' messages reach the handler (one channel also narrows the stream server-side). | |
cursorStore | CursorStore | no | Where to keep the place in the event stream, so a restart continues where it stopped. | |
signal | AbortSignal | no | Stops the runner (as stop()). | |
log | DirectLogger | no | Where 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) => void | no | Told about a handler that threw (after it is logged); the runner moves on to the next message. | |
fetch | typeof fetch | no | Tests and proxies. | |
reconnect | object | no | Stream reconnect tuning (defaults: 500 ms first delay, 30 s cap, 45 s idle timeout). | |
reconnect.initialDelayMs | number | no | 500 | The wait before the first reconnect, in milliseconds. |
reconnect.maxDelayMs | number | no | 30000 | The longest wait between reconnects, in milliseconds. |
reconnect.idleTimeoutMs | number | no | 45000 | Reconnect when the stream is silent this long, in milliseconds. |
env | NodeJS.ProcessEnv | no | Read in tests: the process environment the defaults come from. |
DirectRunner
class · @voicelayer/sdk
class DirectRunnerThe 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
| Name | Type | Required | Description |
|---|---|---|---|
client | Client | yes | The scoped REST client the runner uses, for anything else the key may do. |
done | Promise<void> | yes | Settles when the runner has stopped: resolves on stop() or the abort signal, rejects when the stream gives up. |
cursor | string | undefined | yes | The 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 InboundMessageA message from a person, handed to your onMessage handler.
Fields
| Name | Type | Required | Description |
|---|---|---|---|
id | string | yes | The message's public id. |
channel | string | yes | The channel it arrived on, such as sms or whatsapp. |
conversationId | string | yes | The conversation it belongs to. |
from | string | null | yes | The person's address on the channel (a phone number, a chat id); null when the channel hides it. |
text | string | null | yes | The message text, or null for a message with only media. |
media | object[] | yes | Attachments, each with a URL and a content type (or null). |
media.url | string | yes | Where the attachment can be fetched. |
media.contentType | string | null | yes | The attachment's content type, or null when unknown. |
window | object | yes | The 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.open | boolean | yes | Whether you can still reply freely. |
window.closesAt | string | null | yes | When the window closes, as an ISO timestamp, or null. |
controller | Controller | yes | Always api when a handler runs: other conversations are skipped. One of agent, api, human. |
createdAt | string | yes | When the message was created, as an ISO timestamp. |
MessageContext
interface · @voicelayer/sdk
interface MessageContextWhat your handler answers through.
Fields
| Name | Type | Required | Description |
|---|---|---|---|
conversation | PublicConversation | yes | The conversation as read when the message was handed over. |
client | Client | yes | The scoped REST client, for anything else the key may do. |
signal | AbortSignal | yes | Aborted 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
| Name | Type | Required | Description |
|---|---|---|---|
input | SendInput | yes | The 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
| Name | Type | Required | Description |
|---|---|---|---|
to | Controller | yes | Who answers from now on. One of agent, api, human. |
opts | object | no | A reason recorded on the conversation. |
opts.reason | string | no | Why 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
| Name | Type | Required | Description |
|---|---|---|---|
userId | string | null | yes | The 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 SentMessageThe message that was sent.
Fields
| Name | Type | Required | Description |
|---|---|---|---|
id | string | yes | The message's id. |
status | string | yes | Its 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 CursorStoreWhere 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
| Name | Type | Required | Description |
|---|---|---|---|
cursor | string | yes | The 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
| Name | Type | Required | Default | Description |
|---|---|---|---|---|
initial | string | null | no | null | A cursor to start with. |
Returns
CursorStore & { readonly value: string | null; }: The store.
assertDirectKey
function · @voicelayer/sdk/direct
assertDirectKey(key: string | undefined): stringCheck that a key is a scoped REST key for direct mode and return it.
Parameters
| Name | Type | Required | Description |
|---|---|---|---|
key | string | undefined | yes | The 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 ErrorThrown 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): DirectKeyErrorOutputRefusedError
class · @voicelayer/sdk
class OutputRefusedError extends ErrorThrown 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
| Name | Type | Required | Description |
|---|---|---|---|
code | "output_refused" | yes | Always output_refused. |
requestId | string | undefined | yes | The API request's id, to quote to support. |
details | Record<string, unknown> | undefined | yes | What the checks reported, when they said. |
apiError | VoiceLayerApiError | yes | The underlying API error. |