Reference

Custom channels

Reference for defineChannel, send and code actions, the channel store and serveChannel.

A channel connector is one declaration plus one pure function, onEvent, that maps a provider's raw event to a message. Actions and schedules add the rest of the channel's code.

Import from @voicelayer/sdk/channel. For a walk-through, see Build your own channel.

defineChannel

function · @voicelayer/sdk/channel

defineChannel(config: ChannelConfig): ChannelHandle

Define a channel connector: a declaration of what the platform does by itself (verify the provider's webhook, acknowledge it, dedupe by id, fill the declared sends) plus one pure function, onEvent, that maps a raw event to a message. The manifest is validated here with the same schema the API uses at publish.

Parameters
NameTypeRequiredDescription
configChannelConfigyesThe channel's name, inbound webhook, sends, optional actions and schedules, and onEvent.
Returns

ChannelHandle: The channel handle, for the CLI, serveChannel and testChannel.

Throws
  • ChannelDefinitionError when the name is invalid, onEvent is missing, an action is malformed or a field that is not available yet is set.
Example
import { defineChannel } from '@voicelayer/sdk/channel';

export default defineChannel({
  name: 'helpdesk',
  channel: 'telegram',
  inbound: {
    webhook: {
      verify: { scheme: 'secret_token_header', header: 'x-helpdesk-token' },
      events: [{ kind: 'message', id: { from: 'json', path: 'update_id' } }],
    },
  },
  onEvent: (raw, ctx) => {
    const update = ctx.json(raw);
    return ctx.deliver({
      id: String(update.update_id),
      conversation: String(update.message.chat.id),
      from: ctx.peer('telegram_user', update.message.from.id),
      text: update.message.text,
    });
  },
});

ChannelConfig

interface · @voicelayer/sdk/channel

interface ChannelConfig

Everything that defines a channel connector: its name, how inbound webhooks are verified and acknowledged, how replies are sent, and the one function that turns a raw event into a message. Pass it to defineChannel.

Fields

NameTypeRequiredDefaultDescription
namestringyesThe connector's name: lowercase letters, digits and -, starting with a letter, up to 40 characters. Its id is ws/<workspace>/<name>.
labelstringnoThe name people see.
channelstringyesThe existing platform channel this connector narrows, such as telegram or sms.
hostsreadonly string[]noThe provider hosts the declared sends may reach. Declaring api adds its host.
inboundobjectyesHow events arrive from the provider.
inbound.webhook{ readonly verify: DeclaredVerification; readonly events: readonly DeclaredEventSource[]; readonly ack?: DeclaredInboundInput['ack']; readonly handshakes?: DeclaredInboundInput['handshakes']; }yesThe webhook the provider calls: verify (how a delivery proves it is real), events (where each kind's id is), optionally ack (what the provider is answered) and handshakes (requests the platform answers itself).
sendsPartial<Record<DeclaredSendOperation, SendRequestTemplate>>noThe default replies as request templates, by operation (send.text, reply.in_window, send.media). The platform fills and sends them.
apiobjectnoThe provider API the channel's code may call. Every call is declared by method and typed path (GET /{id:digits}); the host is added to hosts.
api.hoststringyesThe provider's API host.
api.callsApiDeclaration['calls']yesThe calls the channel's code may make, each as METHOD /path with typed segments such as {id:digits}, {x:slug} or {x:uuid}.
actionsReadonly<Record<string, ChannelAction>>noWhat an agent or a dashboard control can run, by name: a sendAction (a template the platform sends) or a codeAction.
schedulesreadonly ChannelSchedule[]noRead-only polling: { name, everySeconds }, answered by onSchedule. A schedule cannot send.
onSchedule(name: string, ctx: ChannelActionContext) => unknown | Promise<unknown>noRuns a schedule with a read token: poll the declared GET calls and ctx.deliver what is new.
storebooleannofalseKeep per-connection state (ctx.store: cursors, seen ids). The platform holds it for one connection.
onEvent(raw: ChannelRawEvent, ctx: ChannelEventContext) => ChannelOutcome | Promise<ChannelOutcome>yesThe only code on the inbound path. It maps one stored raw event to a message with ctx.deliver, or to ctx.ignore. It reaches nothing outside the event.

ChannelHandle

interface · @voicelayer/sdk/channel

interface ChannelHandle

What defineChannel returns. The CLI reads it to build and test the channel, and serveChannel runs it.

Fields

NameTypeRequiredDescription
namestringyesThe connector's name.
configChannelConfigyesThe config you passed to defineChannel.

manifest

manifest(connectorId: string): { readonly manifest: { channels: string[]; id: string; displayName: string; inbound: { verification: { scheme: "slack_v0"; toleranceSec: number; } | { scheme: "meta_hmac_sha256"; } | { scheme: "twilio_hmac_sha1"; } | { scheme: "ed25519"; toleranceSec: number; signatureHeader: string; timestampHeader: string; } | { scheme: "secret_token_header"; header: string; }; events: { kind: string; id: { path: string; from: "json"; } | { name: string; from: "header"; }; items?: string | undefined; lane?: string | undefined; }[]; ack: { type: "fixed"; status: number; body: string; contentType: "text/plain" | "application/json" | "text/xml"; } | { type: "echo_query"; param: string; } | { path: string; type: "echo_json"; as: { format: "text"; } | { format: "json"; key: string; }; } | { path: string; type: "typed"; cases: Record<string, { type: "fixed"; status: number; body: string; contentType: "text/plain" | "application/json" | "text/xml"; }>; fallback: { type: "fixed"; status: number; body: string; contentType: "text/plain" | "application/json" | "text/xml"; }; }; handshakes: { name: string; when: { method: "GET" | "POST"; query?: { param: string; equals?: string | undefined; } | undefined; json?: { path: string; equals: string | number | boolean; } | undefined; }; authentication: { by: "signature"; } | { by: "token"; queryParam: string; }; reply: { type: "fixed"; status: number; body: string; contentType: "text/plain" | "application/json" | "text/xml"; } | { type: "echo_query"; param: string; } | { path: string; type: "echo_json"; as: { format: "text"; } | { format: "json"; key: string; }; } | { path: string; type: "typed"; cases: Record<string, { type: "fixed"; status: number; body: string; contentType: "text/plain" | "application/json" | "text/xml"; }>; fallback: { type: "fixed"; status: number; body: string; contentType: "text/plain" | "application/json" | "text/xml"; }; }; }[]; attribution: { from: "path"; } | { path: string; from: "body"; } | { name: string; from: "header"; }; }; egressHosts: string[]; api?: { host: string; calls: (string | { call: string; query?: string[] | undefined; })[]; } | undefined; sends?: { operations: Partial<Record<"send.text" | "reply.in_window" | "send.media", { path: string; method: "POST" | "PUT" | "PATCH"; recipients: string[]; messageId: string; query?: Record<string, string> | undefined; headers?: Record<string, string> | undefined; body?: { kind: "json"; template: Record<string, unknown>; } | { kind: "form"; fields: Record<string, string>; } | undefined; address?: "peer" | "answered" | undefined; }>>; } | undefined; live?: { events: string[]; protocol: "discord_gateway"; intents: number; } | { protocol: "slack_socket"; } | { protocol: "imap"; mailbox: string; } | undefined; actions?: Record<string, { kind: "send"; sends: number; send: { path: string; method: "POST" | "PUT" | "PATCH"; recipients: string[]; messageId: string; query?: Record<string, string> | undefined; headers?: Record<string, string> | undefined; body?: { kind: "json"; template: Record<string, unknown>; } | { kind: "form"; fields: Record<string, string>; } | undefined; address?: "peer" | "answered" | undefined; }; hasPrepare: boolean; describe: string; forAgent: boolean; input?: Record<string, "string" | "number" | "boolean" | "text" | "url"> | undefined; slots?: Record<string, "digits" | "uuid" | "hex"> | undefined; } | { kind: "code"; describe: string; forAgent: boolean; access: "read" | "write"; input?: Record<string, "string" | "number" | "boolean" | "text" | "url"> | undefined; }> | undefined; schedules?: { name: string; everySeconds: number; }[] | undefined; store?: boolean | undefined; } | undefined; readonly issues: readonly ChannelIssue[]; }

Build the manifest for a connector id, checked with the same schema the API uses at publish.

Parameters
NameTypeRequiredDescription
connectorIdstringyesThe connector's id, ws/<workspace>/<name>.
Returns

{ readonly manifest: { channels: string[]; id: string; displayName: string; inbound: { verification: { scheme: "slack_v0"; toleranceSec: number; } | { scheme: "meta_hmac_sha256"; } | { scheme: "twilio_hmac_sha1"; } | { scheme: "ed25519"; toleranceSec: number; signatureHeader: string; timestampHeader: string; } | { scheme: "secret_token_header"; header: string; }; events: { kind: string; id: { path: string; from: "json"; } | { name: string; from: "header"; }; items?: string | undefined; lane?: string | undefined; }[]; ack: { type: "fixed"; status: number; body: string; contentType: "text/plain" | "application/json" | "text/xml"; } | { type: "echo_query"; param: string; } | { path: string; type: "echo_json"; as: { format: "text"; } | { format: "json"; key: string; }; } | { path: string; type: "typed"; cases: Record<string, { type: "fixed"; status: number; body: string; contentType: "text/plain" | "application/json" | "text/xml"; }>; fallback: { type: "fixed"; status: number; body: string; contentType: "text/plain" | "application/json" | "text/xml"; }; }; handshakes: { name: string; when: { method: "GET" | "POST"; query?: { param: string; equals?: string | undefined; } | undefined; json?: { path: string; equals: string | number | boolean; } | undefined; }; authentication: { by: "signature"; } | { by: "token"; queryParam: string; }; reply: { type: "fixed"; status: number; body: string; contentType: "text/plain" | "application/json" | "text/xml"; } | { type: "echo_query"; param: string; } | { path: string; type: "echo_json"; as: { format: "text"; } | { format: "json"; key: string; }; } | { path: string; type: "typed"; cases: Record<string, { type: "fixed"; status: number; body: string; contentType: "text/plain" | "application/json" | "text/xml"; }>; fallback: { type: "fixed"; status: number; body: string; contentType: "text/plain" | "application/json" | "text/xml"; }; }; }[]; attribution: { from: "path"; } | { path: string; from: "body"; } | { name: string; from: "header"; }; }; egressHosts: string[]; api?: { host: string; calls: (string | { call: string; query?: string[] | undefined; })[]; } | undefined; sends?: { operations: Partial<Record<"send.text" | "reply.in_window" | "send.media", { path: string; method: "POST" | "PUT" | "PATCH"; recipients: string[]; messageId: string; query?: Record<string, string> | undefined; headers?: Record<string, string> | undefined; body?: { kind: "json"; template: Record<string, unknown>; } | { kind: "form"; fields: Record<string, string>; } | undefined; address?: "peer" | "answered" | undefined; }>>; } | undefined; live?: { events: string[]; protocol: "discord_gateway"; intents: number; } | { protocol: "slack_socket"; } | { protocol: "imap"; mailbox: string; } | undefined; actions?: Record<string, { kind: "send"; sends: number; send: { path: string; method: "POST" | "PUT" | "PATCH"; recipients: string[]; messageId: string; query?: Record<string, string> | undefined; headers?: Record<string, string> | undefined; body?: { kind: "json"; template: Record<string, unknown>; } | { kind: "form"; fields: Record<string, string>; } | undefined; address?: "peer" | "answered" | undefined; }; hasPrepare: boolean; describe: string; forAgent: boolean; input?: Record<string, "string" | "number" | "boolean" | "text" | "url"> | undefined; slots?: Record<string, "digits" | "uuid" | "hex"> | undefined; } | { kind: "code"; describe: string; forAgent: boolean; access: "read" | "write"; input?: Record<string, "string" | "number" | "boolean" | "text" | "url"> | undefined; }> | undefined; schedules?: { name: string; everySeconds: number; }[] | undefined; store?: boolean | undefined; } | undefined; readonly issues: readonly ChannelIssue[]; }: The manifest (or undefined) and a list of issues.

parse

parse(events: readonly ChannelRawEvent[]): Promise<({ eventId: string; outcome: "event"; event: { kind: "message"; from: { kind: AnyIdentifierKind; address: string; displayName?: string | undefined; }; channel: string; providerId: string; conversationKey: string; content: ({ text: string; kind: "text"; } | { kind: "media"; locator: string; format?: string | undefined; })[]; replyTo?: string | undefined; threadKey?: string | undefined; replyContext?: Record<string, unknown> | undefined; providerMetadata?: Record<string, unknown> | undefined; surface?: Record<string, unknown> | undefined; context?: string | undefined; occurredAt?: number | undefined; } | { status: "read" | "sent" | "delivered" | "failed"; kind: "status"; channel: string; providerId: string; at?: number | undefined; errorCode?: string | undefined; error?: string | undefined; metadata?: Record<string, unknown> | undefined; errors?: { code: string; message?: string | undefined; }[] | undefined; correlationTag?: string | undefined; } | { kind: "reaction"; from: { kind: AnyIdentifierKind; address: string; displayName?: string | undefined; }; channel: string; providerId: string; targetProviderId: string; emoji: string; removed: boolean; }; } | { eventId: string; outcome: "mapping_failure"; failure: { reason: string; providerId?: string | undefined; }; } | { eventId: string; outcome: "ignored"; reason: string; })[]>

Run onEvent for each raw event. One result each; a throw becomes that event's mapping_failure and never fails the batch.

Parameters
NameTypeRequiredDescription
eventsreadonly ChannelRawEvent[]yesThe raw events, as stored by the platform.
Returns

Promise<({ eventId: string; outcome: "event"; event: { kind: "message"; from: { kind: AnyIdentifierKind; address: string; displayName?: string | undefined; }; channel: string; providerId: string; conversationKey: string; content: ({ text: string; kind: "text"; } | { kind: "media"; locator: string; format?: string | undefined; })[]; replyTo?: string | undefined; threadKey?: string | undefined; replyContext?: Record<string, unknown> | undefined; providerMetadata?: Record<string, unknown> | undefined; surface?: Record<string, unknown> | undefined; context?: string | undefined; occurredAt?: number | undefined; } | { status: "read" | "sent" | "delivered" | "failed"; kind: "status"; channel: string; providerId: string; at?: number | undefined; errorCode?: string | undefined; error?: string | undefined; metadata?: Record<string, unknown> | undefined; errors?: { code: string; message?: string | undefined; }[] | undefined; correlationTag?: string | undefined; } | { kind: "reaction"; from: { kind: AnyIdentifierKind; address: string; displayName?: string | undefined; }; channel: string; providerId: string; targetProviderId: string; emoji: string; removed: boolean; }; } | { eventId: string; outcome: "mapping_failure"; failure: { reason: string; providerId?: string | undefined; }; } | { eventId: string; outcome: "ignored"; reason: string; })[]>: One parse result per event.

runAction

runAction(request: ChannelActionRequest, io: ChannelActionIo): Promise<unknown>

Run one action's code. prepare answers the slots (checked against their declared kinds), run returns a code action's data, control a read action's data and schedule what onSchedule returned.

Parameters
NameTypeRequiredDescription
requestChannelActionRequestyesWhich action and phase, with its input and settings.
ioChannelActionIoyesThe provider call and the connection's store.
Returns

Promise<unknown>: The action's result.

Throws
  • ChannelActionError when the action is refused, for example slot_invalid for a wrong slot value. A throw of your own code propagates.

ChannelEventContext

interface · @voicelayer/sdk/channel

interface ChannelEventContext

What onEvent receives beside the raw event: helpers to read it, name the sender and hand the message on. It reaches nothing else: no network, no credential, no state.

json

json(raw: ChannelRawEvent): any

Parse the raw event's body as JSON (the delivery, or the one item of a batch that the declaration's items named).

Parameters
NameTypeRequiredDescription
rawChannelRawEventyesThe raw event.
Returns

any: The parsed body.

peer

peer(kind: string, address: string | number, displayName?: string): ChannelPeer

Name a person on the channel.

Parameters
NameTypeRequiredDescription
kindstringyesAn identifier kind of the platform vocabulary, such as telegram_user or phone.
addressstring | numberyesThe person's address on the channel.
displayNamestringnoThe person's name, when the provider gives it.
Returns

ChannelPeer

Throws
  • ChannelDefinitionError when kind is not an identifier kind.

deliver

deliver(message: DeliverInput): ChannelOutcome

Hand a message to the platform for the connection's agent. Return the result from onEvent.

Parameters
NameTypeRequiredDescription
messageDeliverInputyesThe message.
Returns

ChannelOutcome

ignore

ignore(reason: string): ChannelOutcome

Say the event is genuine and this channel chose to do nothing with it. The reason is kept on the connection's record (200 characters at most; never the person's words). Return the result from onEvent.

Parameters
NameTypeRequiredDescription
reasonstringyesWhy nothing was done.
Returns

ChannelOutcome

ChannelPeer

interface · @voicelayer/sdk/channel

interface ChannelPeer

A person on the channel, as the platform names them. Build one with ctx.peer.

Fields

NameTypeRequiredDescription
kindstringyesThe identifier kind, from the platform's vocabulary: telegram_user, phone and so on.
addressstringyesThe person's address on the channel, such as a chat id or phone number.
displayNamestringnoThe person's name, when the provider gives it.

DeliverInput

interface · @voicelayer/sdk/channel

interface DeliverInput

A message handed to the platform for the connection's agent, with ctx.deliver.

Fields

NameTypeRequiredDescription
idstringyesThe provider's id of this message; the building prefixes it and dedupes on it.
conversationstringyesWhich conversation it belongs to (a chat id, a thread id): messages with one key are one conversation.
fromChannelPeeryesWho wrote it: ctx.peer(kind, address).
textstringnoThe message text.
mediaobject[]noAttachments, each a locator the platform can fetch and an optional format.
media.locatorstringyesWhere the attachment can be fetched.
media.formatstringnoThe attachment's format, such as image/png.
replyTostringnoThe provider's id of the message this answers.
threadstringnoThe provider's thread id, when the message belongs to a thread.
atnumbernoWhen the provider says it was written, epoch ms.
contextstringnoThe owner's note for this event: stored with the message and shown to the agent as labelled input (never in the sealed prompt). At most 2000 characters.

ChannelOutcome

type · @voicelayer/sdk/channel

type ChannelOutcome = | { readonly outcome: 'event'; readonly event: Record<string, unknown> } | { readonly outcome: 'ignored'; readonly reason: string }

What onEvent returns: { outcome: 'event', event } for a message to deliver, or { outcome: 'ignored', reason } when the event is genuine and the channel chooses to do nothing with it. Build either with ctx.deliver or ctx.ignore.

ChannelIssue

interface · @voicelayer/sdk/channel

interface ChannelIssue

A problem found in a channel's declaration.

Fields

NameTypeRequiredDescription
pathstringyesWhere in the declaration.
messagestringyesWhat is wrong.

sendAction

function · @voicelayer/sdk/channel

sendAction<I extends Readonly<Record<string, ActionInputType>>, S extends Readonly<Record<string, "digits" | "uuid" | "hex">>>(a: SendAction<I, S>): SendAction<I, S>

Define a send action. An identity helper that keeps input and slots literal so prepare sees its input typed.

Parameters
NameTypeRequiredDescription
aSendAction<I, S>yesThe action.
Returns

SendAction<I, S>: The same action.

Example
sendAction({
  forAgent: true,
  describe: 'Send a text reply.',
  send: { method: 'POST', path: '/sendMessage', body: { chat_id: '{{target}}', text: '{{text}}' } },
})

SendAction

interface · @voicelayer/sdk/channel

interface SendAction<I extends InputShape = InputShape, S extends SlotShape = SlotShape>

An action that reaches a person: the platform fills the send template and sends it after its checks. prepare may run first to fill the declared slots.

Fields

NameTypeRequiredDefaultDescription
forAgentbooleannofalseOffer the action to the agent as a tool.
describestringyesWhat the action does. It becomes the tool's description for an agent action.
sendsnumberno1How many messages one run sends, for metering.
inputInoThe inputs the caller passes, by name and type (text, string, url, number or boolean).
slotsSnoTyped identifiers prepare fills, such as { mediaId: 'digits' }. Each sits as the whole value of a body field or path segment in send.
sendimport('@voicelayer/contracts').SendRequestTemplateyesThe request template, as for sends. It must hold {{text}}.
address'peer' | 'answered'noShorthand for send.address: peer addresses the person, answered addresses the message being answered.

prepare

prepare(input: InputValues<I>, ctx: ChannelActionContext<I>): void | SlotValues<S> | Promise<void | SlotValues<S>>

Runs once before the send, with the input, and returns one string per declared slot, each matching its kind.

Parameters
NameTypeRequiredDescription
inputInputValues<I>yesThe action's validated input.
ctxChannelActionContext<I>yesThe action context.
Returns

void | SlotValues<S> | Promise<void | SlotValues<S>>

codeAction

function · @voicelayer/sdk/channel

codeAction<I extends Readonly<Record<string, ActionInputType>>>(a: CodeAction<I>): CodeAction<I>

Define a code action. An identity helper that keeps input literal so run sees its input typed.

Parameters
NameTypeRequiredDescription
aCodeAction<I>yesThe action.
Returns

CodeAction<I>: The same action.

Example
codeAction({
  forAgent: true,
  describe: 'Look up a ticket.',
  input: { ticketId: 'string' },
  run: async ({ ticketId }, ctx) => ctx.fetch(`/tickets/${ticketId}`),
})

CodeAction

interface · @voicelayer/sdk/channel

interface CodeAction<I extends InputShape = InputShape>

An action that runs your code. For the agent (forAgent, access write by default) or a dashboard control (always read).

Fields

NameTypeRequiredDefaultDescription
forAgentbooleannofalseOffer the action to the agent as a tool.
describestringnoWhat the action does. Required for an agent action: it becomes the tool's description.
inputInoThe inputs the caller passes, by name and type (text, string, url, number or boolean).
access'read' | 'write'no`write` for an agent action, otherwise `read`Whether the action only reads or may change things at the provider.

run

run(input: InputValues<I>, ctx: ChannelActionContext<I>): unknown

Your function, called with the validated input and the context. What it returns is the action's result.

Parameters
NameTypeRequiredDescription
inputInputValues<I>yesThe action's validated input.
ctxChannelActionContext<I>yesThe action context.
Returns

unknown

ChannelActionContext

interface · @voicelayer/sdk/channel

interface ChannelActionContext<I extends InputShape = InputShape>

What action code receives: the input and settings, fetch to the declared provider API, the store, and helpers to hand messages on.

Fields

NameTypeRequiredDescription
inputInputValues<I>yesThe values of the action's declared inputs.
settingsReadonly<Record<string, any>>yesThe connection's saved settings.
storeChannelStoreyesThe connection's store.

fetch

fetch(path: string, init?: ChannelFetchInit): Promise<any>

Call the declared provider API, for example ctx.fetch('/me/media', { query: { limit: 5 } }). Returns the JSON answer.

Parameters
NameTypeRequiredDescription
pathstringyesThe call's path.
initChannelFetchInitnoMethod, JSON body and query.
Returns

Promise<any>

Throws
  • ChannelFetchError when the provider answers with a non-2xx status.

deliver

deliver(message: DeliverInput): ChannelOutcome

Hand the platform a message, as onEvent does. For a schedule's handler.

Parameters
NameTypeRequiredDescription
messageDeliverInputyesThe message.
Returns

ChannelOutcome

peer

peer(kind: string, address: string | number, displayName?: string): ChannelPeer

Name a person on the channel.

Parameters
NameTypeRequiredDescription
kindstringyesAn identifier kind of the platform vocabulary.
addressstring | numberyesThe person's address on the channel.
displayNamestringnoThe person's name, when the provider gives it.
Returns

ChannelPeer

ignore

ignore(reason: string): ChannelOutcome

Say there is nothing to do.

Parameters
NameTypeRequiredDescription
reasonstringyesWhy nothing was done.
Returns

ChannelOutcome

ChannelActionRequest

interface · @voicelayer/sdk/channel

interface ChannelActionRequest

One action invocation as the room receives it.

Fields

NameTypeRequiredDescription
phaseChannelActionPhaseyesWhich step is running. One of schedule, prepare, run, control.
actionstringyesThe action's name.
inputReadonly<Record<string, unknown>>noThe input the caller passed.
settingsReadonly<Record<string, unknown>>noThe connection's saved settings.

ChannelActionIo

interface · @voicelayer/sdk/channel

interface ChannelActionIo

What the room gives action code: the call to the provider and the connection's store.

Fields

NameTypeRequiredDescription
fetch(path: string, init?: ChannelFetchInit) => Promise<any>yesCall the provider's declared API.
storeChannelStoreyesThe connection's store. Used only when the channel declares store: true.

ChannelFetchInit

interface · @voicelayer/sdk/channel

interface ChannelFetchInit

Options for a call to the provider's declared API with ctx.fetch.

Fields

NameTypeRequiredDefaultDescription
method'GET' | 'HEAD' | 'POST' | 'PUT' | 'PATCH' | 'DELETE'no`POST` when `json` is given, else `GET`The HTTP method. The call must be one the declaration's api.calls lists.
jsonunknownnoA JSON request body.
queryReadonly<Record<string, string | number | boolean | undefined>>noQuery parameters. Keys must be declared on the call; undefined values are dropped.

ChannelStore

interface · @voicelayer/sdk/channel

interface ChannelStore

Per-connection state: a cursor, the ids already seen. Declare store: true in defineChannel. The platform keeps it, sealed, for one connection. A key is 1 to 200 characters: letters, digits and . _ : / @ + = -. A refusal (a bad key, a value over the plan's size, too many keys) names its reason.

get

get(key: string): Promise<unknown>

The value kept under key, or undefined when there is none.

Parameters
NameTypeRequiredDescription
keystringyesThe key to read.
Returns

Promise<unknown>

put

put(key: string, value: unknown): Promise<void>

Keep any JSON value under key, replacing what was there.

Parameters
NameTypeRequiredDescription
keystringyesThe key to write.
valueunknownyesAny JSON value.
Returns

Promise<void>

delete

delete(key: string): Promise<void>

Remove the value under key.

Parameters
NameTypeRequiredDescription
keystringyesThe key to remove.
Returns

Promise<void>

list

list(prefix?: string): Promise<readonly { readonly key: string; readonly value: unknown; }[]>

The entries whose key starts with prefix (default: all), by key, at most 200.

Parameters
NameTypeRequiredDescription
prefixstringnoOnly keys that start with this.
Returns

Promise<readonly { readonly key: string; readonly value: unknown; }[]>

memoryStore

function · @voicelayer/sdk/channel

memoryStore(initial?: Readonly<Record<string, unknown>>): ChannelStore & { readonly entries: ReadonlyMap<string, unknown>; }

A ChannelStore kept in memory, for tests. entries shows what it holds.

Parameters
NameTypeRequiredDescription
initialReadonly<Record<string, unknown>>noEntries to start with.
Returns

ChannelStore & { readonly entries: ReadonlyMap<string, unknown>; }: A store with an entries map.

serveChannel

function · @voicelayer/sdk/channel

serveChannel(handle: ChannelHandle, opts?: ServeChannelOptions): Promise<ChannelServer>

Serve a channel in its room: GET /healthz, POST /v1/channel/parse and POST /v1/channel/action. The platform's shim sends the events and relays your answers; the process holds no credential.

Parameters
NameTypeRequiredDescription
handleChannelHandleyesThe channel from defineChannel.
optsServeChannelOptionsnoPort, logging and shutdown behaviour.
Returns

Promise<ChannelServer>: The running server.

Example
await serveChannel(channel);

ServeChannelOptions

interface · @voicelayer/sdk/channel

interface ServeChannelOptions

Options for serving a channel in its room.

Fields

NameTypeRequiredDefaultDescription
portnumberno`$PORT`The port to listen on.
hoststringnoThe address to listen on.
logRunnerLoggernoWhere the server writes its log lines: an object with debug, info, warn and error functions.
signalsbooleannotrueInstall SIGTERM and SIGINT handlers and exit when stopped by one.
envReadonly<Record<string, string | undefined>>noprocess.envThe environment to read ports and the key proxy address from.
transportActionTransportnothe key proxy at `$VL_KEYS_URL` (`http://api.keys.vl`)How ctx.fetch reaches the provider and ctx.store the platform's store.

ChannelServer

interface · @voicelayer/sdk/channel

interface ChannelServer

A running channel server.

Fields

NameTypeRequiredDescription
portnumberyesThe port it listens on.
donePromise<void>yesResolves when the server has stopped.

stop

stop(): Promise<void>

Stop accepting requests and finish those running.

Returns

Promise<void>

ChannelDefinitionError

class · @voicelayer/sdk/channel

class ChannelDefinitionError extends Error

Thrown by defineChannel and ctx.peer when the declaration or a call is invalid, with a sentence saying what to change.

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

ChannelActionError

class · @voicelayer/sdk/channel

class ChannelActionError extends Error

A refusal of the action itself, not a throw from your code. code is one of unknown_action, wrong_phase, bad_input, slot_invalid, not_available, bad_result, handler_error.

new ChannelActionError(code: ChannelActionErrorCode, message: string)

Fields

NameTypeRequiredDescription
codeChannelActionErrorCodeyesWhy the action was refused. One of unknown_action, wrong_phase, bad_input, slot_invalid, not_available, bad_result, handler_error.

ChannelFetchError

class · @voicelayer/sdk/channel

class ChannelFetchError extends Error

A provider call through ctx.fetch that failed: the status and the parsed answer, so your code can read the provider's message.

new ChannelFetchError(status: number, body: unknown, path: string)

Fields

NameTypeRequiredDescription
statusnumberyesThe HTTP status.
bodyunknownyesThe provider's parsed answer.