Reference

Defining and starting an agent

Reference for defineAgent, every AgentConfig field, defineProcess, startAgents and agent.start().

defineAgent takes an AgentConfig and returns a handle; the voicelayer CLI reads the handle to build and deploy the agent, and .start() runs it. The sections below list the config, the types it is made of, and the calls that run it.

Import from @voicelayer/sdk. For a walk-through, see Voice agents in code.

defineAgent

function · @voicelayer/sdk

defineAgent<TProcess extends Record<string, ProcessField>>(config: AgentConfig<TProcess>): AgentHandle<TProcess>

Define an agent. It returns a handle that the voicelayer CLI reads to dev, deploy and build the manifest, and that your production process runs with .start(). Defining an agent runs nothing and opens no connection.

Parameters
NameTypeRequiredDescription
configAgentConfig<TProcess>yesThe agent: prompt, tools, models, process and the rest of AgentConfig.
Returns

AgentHandle<TProcess>: The agent's handle: .manifest(), .onMessage(handler) and .start(options).

Example
import { defineAgent, defineTool } from '@voicelayer/sdk';

const agent = defineAgent({
  name: 'front-desk',
  prompt: 'You answer the phone for Acme and book appointments.',
  greeting: 'Thanks for calling Acme. How can I help?',
  tools: {
    ...defineTool({
      name: 'lookup_order',
      description: 'Find an order by its number.',
      input: { orderId: 'string' },
      run: async ({ orderId }) => ({ orderId, status: 'shipped' }),
    }),
  },
});

await agent.start();

AgentConfig

interface · @voicelayer/sdk

interface AgentConfig<TProcess extends Record<string, ProcessField> = Record<string, ProcessField>>

Everything that defines an agent: who it is, what it says, what it collects, which tools and models it uses and how calls end. Pass it to defineAgent. It is sealed when you deploy, so a change applies to the next call only.

Fields

NameTypeRequiredDefaultDescription
namestringyesThe agent's name: lowercase letters, digits, - and _. With the deploy's environment it picks the agent's row in the dashboard.
promptstringyesThe system prompt the model follows. Calls use the version you deployed; editing it later applies to the next call only.
greetingstringnoA fixed opening line, spoken straight away with no model call, so the caller does not wait. Absent: the model writes the greeting from the prompt.
routingInstructionsstringnoPlain-language guidance on when the agent should act, added below the prompt under a "Routing" heading.
capabilitiesreadonly string[]noCapability tags shown for the agent in the dashboard.
versionstringnoYour own version string, shown in the dashboard. It is a label, not what the platform pins a call to.
processProcessDefinition<TProcess>noThe values the agent collects from the caller, and what happens when it has them. Build it with defineProcess to get typed data in onComplete.
process.collectTyesThe fields to capture, by name.
process.completeWhenCompletionStrategynoThe rule that decides when the process is complete.
process.backendAckProcessBackendAcknoAn endpoint the platform tells when the process completes.
process.onComplete(data: InferProcessData<T>, ctx: HandlerContext) => Promise<void> | voidnoRuns when the process completes, with the captured data. It has 5 seconds; it is awaited, errors are logged, and the process stays complete.
process.onField<K extends keyof T>(field: K, value: InferFieldValue<T[K]>, ctx: HandlerContext) => Promise<void> | voidnoRuns each time a field is captured, with the field name and value. It has 2 seconds; it is awaited, errors are logged, and the field stays captured.
triggersReadonly<Record<string, TriggerDefinition>>noRules that watch the conversation and act when a condition is met, by name.
handoffHandoffConfignoWhere and how the agent hands a call to a person.
handoff.fallbackstringyesThe destination used when no route matches.
handoff.routesReadonly<Record<string, string>>noNamed destinations the agent or a trigger can hand off to, by name, for example { billing: '+15551230000' }.
handoff.briefing| string | ((args: { readonly data: Record<string, unknown>; readonly transcript: TranscriptHandle; readonly call: CallInfo }) => string | Promise<string>)noWhat the receiving person is told: fixed text, or a function of the captured data, the transcript and the call. A function has 2 seconds; when it is late the platform's own briefing is used.
handoff.mode'warm' | 'cold'nowarm briefs the receiver before connecting the caller; cold connects straight away.
handoff.headers{ readonly context?: boolean; readonly reason?: boolean }noSIP headers a contact centre reads on the transfer. context sends User-to-User with a reference (128 characters at most) to a read-only summary of the call; reason sends X-VL-Reason with the reason the platform's output guard let through. The names and shapes are fixed by the platform. Off unless you switch them on.
memoryMemoryConfignoHow far the agent's memory reaches and how long it is kept.
memory.scopeMemoryScopenoHow far remembered values reach. One of call, caller, participant, account, platform.
memory.retentionDaysnumbernoHow many days remembered values are kept before they are deleted.
memory.piiFieldsreadonly string[]noNames of fields that hold personal details, kept tokenised.
memory.platformOptInbooleannofalseWhether the agent takes part in platform-wide memory.
participantsParticipantsConfignoHandlers for people joining and leaving the call, and a cap on how many may.
participants.onJoin(participant: Participant, ctx: HandlerContext) => Promise<void> | voidnoRuns when someone joins. A notification: delivered in call order, never waited on.
participants.onLeave(participant: Participant, ctx: HandlerContext) => Promise<void> | voidnoRuns when someone leaves. A notification: delivered in call order, never waited on.
participants.attributes(participant: Participant) => Readonly<Record<string, string>> | Promise<Readonly<Record<string, string>>>noAdds attributes to a participant as they join. It has 1 second; when it is late no attributes are added.
participants.maxnumbernoThe most participants the call allows.
connectorsReadonly<Record<string, ConnectorInstance>>noConnector objects for your own integration code, by key. They stay in your process. With expose: true each function becomes a tool the model can call.
compliancereadonly ComplianceTag[]noThe compliance regimes the agent operates under.
modelsModelsConfignoWhich models the agent uses for the language model, speech to text and text to speech.
modelModelDescriptor | string | ModelConfignoThe agent's language model in the AI SDK's words: shorthand for models.llm. Setting both is a build error.
outboundOutboundCallConfignoHow the agent behaves on calls it places, such as answering-machine detection.
outbound.amd'off' | 'detect' | 'detectMessageEnd'no'off'Answering-machine detection, judged from the words the callee says. off treats every answer as a person, detect acts the moment a machine greeting is recognised, detectMessageEnd waits for the greeting to finish first. Inbound calls never run it.
outbound.voicemailScriptstringnoWhat to say when a machine answers. Without it the agent hangs up when a machine is detected.
speechSpeechConfignoHow the agent sounds: pronunciations, background audio, interruptions and when a caller's turn ends.
speech.pronunciationsReadonly<Record<string, string>>noHow to say particular words: a map from the written word to how it should be pronounced.
speech.backgroundAudiostring | { readonly url?: string; readonly volume?: number }noA sound under the conversation: a URL, or { url, volume }.
speech.interruption{ readonly enabled?: boolean; readonly minWords?: number; readonly minDuration?: number }noHow easily the caller can interrupt the agent: enabled (default true; false makes the agent uninterruptible), minWords the caller must say first (0 to 10, default 0) and minDuration, the milliseconds of speech that count (0 to 5000, default 500).
speech.endpointing{ readonly minDelay?: number; readonly maxDelay?: number }noWhen the caller's turn is over: minDelay, the silence in milliseconds before it counts as done (0 to 5000, default 500), and maxDelay, the ceiling after which it ends regardless (0 to 15000, default 3000).
endCallEndCallPolicynoWhen and how a call ends: teardown, silence and length limits and a hook that can take over.
endCall.teardown'room' | 'agent'no'room'What to close when the call ends. room ends the whole call, including the phone leg, so the carrier sees a hangup; agent only removes the agent and leaves the other side connected, for when something else owns the call.
endCall.guaranteeMsnumber | falseno4000How long, in milliseconds, the platform keeps retrying teardown until the room is really gone, so a hangup that did not land is repeated. false tries once.
endCall.idleHangupMsnumber | falseno20000Hang up when the agent is waiting on the caller and the line has been silent this many milliseconds, so a stuck call does not run on. Never fires while the agent is speaking or a tool runs. false turns it off.
endCall.maxCallDurationMsnumber | falseno3600000Hang up once the call has run this many milliseconds, whatever else is happening. false turns off this default. The agent's own limit in the dashboard wins over it, and the workspace's plan ceiling caps every call either way.
endCall.onEnd(ctx: HandlerContext, info: EndCallInfo) => boolean | { veto?: boolean } | void | Promise<boolean | { veto?: boolean } | void>noRuns just before the call ends, for every cause. It has 2 seconds. Return false (or { veto: true }) to take over teardown yourself; anything else, a throw or a late answer runs the default teardown. A hangup by the host cannot be vetoed.
toolsReadonly<Record<string, ToolEntry>>noTools the model can call, by name. Each is a defineTool or httpTool result, an AI SDK tool, or a ToolDefinition. Spread several in with ...defineTool({...}).
toolBindingsreadonly string[]noTools you created in the dashboard (HTTP tools) that this agent may use, by name. Absent or empty means none.
actionsreadonly (string | ActionDeclaration)[]noCatalog actions the agent offers, by tool name: VoiceLayer's own (vl_book_meeting, vl_check_availability, vl_send_text, vl_send_email) or a connected app's (int_hubspot_contacts_create). The list is sealed at publish like tools. What an action may do (the connection it uses, argument rules, limits, whether it sees real values) is set by an Admin in the dashboard, and each call runs through VoiceLayer's action door under the call's own credential, so your process never holds a provider credential. Absent: none.
storeobjectnoThe workspace store a hosted agent reads and writes: collections of JSON documents. Mark the fields you query by indexed and those that hold people's details personal; an indexed personal field is also hashed, so only a keyed hash of it is kept in the clear. The person sees the indexed and personal fields when they confirm a publish. Absent: no store.
store.collectionsreadonly { /** The collection's name. */ readonly name: string; /** The fields the agent queries or flags; documents may hold other fields too. */ readonly fields?: readonly { /** The field's name. */ readonly name: string; /** The kind of value it holds. */ readonly type: 'string' | 'number' | 'boolean'; /** Whether the agent queries by this field. @default false */ readonly indexed?: boolean; /** Whether the field holds a person's details, which are protected in storage. @default false */ readonly personal?: boolean; /** Keep only a keyed hash of the value in the clear, so it can be matched but not read. Implied for an indexed personal field. */ readonly hashed?: boolean; }[]; }[]yesThe collections the agent may use.
schedulesobject[]noCron schedules for a hosted agent, in UTC and at most once a minute. Each calls the published endpoint of kind schedule named in endpoint, which must be declared in endpoints. Absent: none.
schedules.namestringyesThe schedule's name.
schedules.cronstringyesA cron expression, in UTC, firing at most once a minute.
schedules.endpointstringyesThe name of the schedule endpoint in endpoints that each run calls.
schedules.missed'skip' | 'run_once'no'skip'What to do with a run that fell due while the platform could not run it: skip drops it, run_once runs it once when it can.
endpointsobject[]noThe addresses a hosted agent publishes at run.vlayers.ai (api, hook, mcp or schedule), who may call each (auth: a key, a signature or anyone) and what the handler may ask the platform for. Absent: none.
endpoints.namestringyesThe endpoint's name, used in its address and by schedules.
endpoints.kind'api' | 'hook' | 'mcp' | 'schedule'yesWhat the endpoint is: an api, a hook (webhook receiver), an mcp server or a schedule target.
endpoints.authRecord<string, unknown>yesWho may call it: a key, a signature or anyone.
endpoints.capabilitiesreadonly string[]noWhat the handler may ask the platform to do, such as store.put or messages.send.
endpoints.realValuesreadonly string[]noThe subset of capabilities that may return people's real details instead of placeholders; each release is recorded.
endpoints.idleTimeoutMsnumbernoFor a streaming response, how long it may sit idle before it is closed, in milliseconds (1000 to 3600000). Absent: the platform default.
publishedEndpointsAgentConfig['endpoints']noThe manifest's own name for endpoints, accepted as an alias. Setting both is a build error.
declaredEndpointsobject[]noThe hosts a hosted agent's process may call out to: { host: 'api.github.com' }, or { name, host, connection, methods } to call a host through a vault connection. Everything else the process tries to reach is refused by name. Absent: no outbound access.
declaredEndpoints.namestringnoA name for the host, used by the connection.
declaredEndpoints.hoststringyesThe host the process may call, for example api.github.com.
declaredEndpoints.connectionstringnoA vault connection whose credential is added to calls to this host.
declaredEndpoints.methodsreadonly ('GET' | 'POST' | 'PUT' | 'PATCH' | 'DELETE')[]noThe HTTP methods allowed.
guardGuardConfignoFlags replies that look wrong, such as too long or containing banned text.
guard.maxLengthnumberno8000Flag a reply longer than this many characters.
guard.bannedSubstringsreadonly string[]nononeSubstrings that flag a reply (case-insensitive).
consultationConsultationPolicynoLimits and wording for when the agent asks a connected assistant for help mid-call: the hold phrase, the timeouts and the cumulative cap.
onUtterance(text: string, ctx: HandlerContext) => Promise<void> | voidnoRuns after each thing the caller says, with the text. A notification: delivered at least once and in call order, and the call never waits for it.
onFieldCaptured(field: string, value: unknown, ctx: HandlerContext) => Promise<void> | voidnoRuns each time a process field is captured, with the field and value. A notification: the call never waits for it.
onCallEnd(outcome: OnCallEndOutcome, ctx: HandlerContext) => Promise<void> | voidnoRuns when the call ends, with how it went. A notification: the call never waits for it.
onDtmf(event: DtmfEvent, ctx: HandlerContext) => Promise<void> | voidnoRuns when the caller presses a phone key. A notification: the call never waits for it. This replaces ctx.onDtmf(handler), because a closure cannot outlive a stateless invocation.
onQueryOnQuerynoMake your own function the model. It is handed the latest utterance and the text history with the turn's abort signal, and returns a string or an async iterable of strings that is spoken. Text only: a brain that needs VoiceLayer's tools uses brain with a framework adapter. Excludes brain and a bound brain connector.
brainBrainTurnHandler | { readonly handler: BrainTurnHandler; readonly firstTokenDeadlineMs?: number }noA framework brain: the handler an adapter builds (openaiAgentsBrain, claudeAgentBrain or langgraphBrain from @voicelayer/sdk/brain), or { handler, firstTokenDeadlineMs } to set how long the first token may take. Excludes onQuery.
puppetModebooleannoRun the agent as a remote-controlled puppet: no autonomous model loop, and a connected assistant says what is spoken.
hostControlledbooleannoLet a connected assistant interject during an autonomous agent's calls and answer its questions.
mcpExposedbooleannotrueMake the agent visible to connected assistants (MCP) and the API, so they can list it and drive its live calls.

defineProcess

function · @voicelayer/sdk

defineProcess<T extends Record<string, ProcessField>>(def: ProcessDefinition<T>): ProcessDefinition<T>

Declare the values the agent collects from the caller. It returns the definition unchanged and exists so the field types flow into onComplete and onField.

Parameters
NameTypeRequiredDescription
defProcessDefinition<T>yesThe fields to collect (collect) and what to do when they are in.
def.collectTyesThe fields to capture, by name.
def.completeWhenCompletionStrategynoThe rule that decides when the process is complete.
def.backendAckProcessBackendAcknoAn endpoint the platform tells when the process completes.
def.onComplete(data: InferProcessData<T>, ctx: HandlerContext) => Promise<void> | voidnoRuns when the process completes, with the captured data. It has 5 seconds; it is awaited, errors are logged, and the process stays complete.
def.onField<K extends keyof T>(field: K, value: InferFieldValue<T[K]>, ctx: HandlerContext) => Promise<void> | voidnoRuns each time a field is captured, with the field name and value. It has 2 seconds; it is awaited, errors are logged, and the field stays captured.
Returns

ProcessDefinition<T>: The same definition, typed.

Example
const booking = defineProcess({
  collect: {
    name: { type: 'string', required: true, ask: 'What name is the booking under?' },
    email: { type: 'email', required: true },
  },
  onComplete: async (data, ctx) => {
    await ctx.say(`Thanks ${data.name}, you are booked.`);
  },
});

ProcessField

interface · @voicelayer/sdk

interface ProcessField

One value a process captures from the caller, for example an email address.

Fields

NameTypeRequiredDefaultDescription
typeProcessFieldTypeyesWhat kind of value to capture. datetime, email and phone are captured as strings. One of string, number, boolean, string[], datetime, email, phone.
requiredbooleannofalseWhether the process needs this field before it counts as complete (with completeWhen: 'all-required-captured').
patternRegExpnoA pattern a captured string (or each string[] item) must match. Its flags are kept, so case sensitivity carries over.
minnumbernoThe lower bound: the smallest value for a number, the shortest length for a string.
maxnumbernoThe upper bound: the largest value for a number, the longest length for a string.
enumreadonly string[]noThe only values the field may take.
askstringnoWhat the agent says to ask for this field.
extractstringnoA hint to the model for pulling this field out of what the caller said.
fromCallerbooleannotrueSet to false when the agent writes the field itself; it is then never extracted from the caller's words.

TriggerDefinition

interface · @voicelayer/sdk

interface TriggerDefinition

A rule that watches the conversation and acts when its condition is met.

Fields

NameTypeRequiredDescription
onTriggerConditionyesThe condition that fires the trigger.
thenTriggerActionyesWhat to do when it fires.
onlyWhilestringnoRestrict the trigger to one step of the flow, by step name.

ActionDeclaration

interface · @voicelayer/sdk

interface ActionDeclaration

A catalog action the code declares, with its own settings. The declaration is the grant. A connected app's action (and the built-ins) still waits for an Admin to switch it on in the dashboard before it runs, so a deploy never widens what the agent may do on its own.

Fields

NameTypeRequiredDefaultDescription
namestringyesThe action's tool name, for example vl_send_text or int_hubspot_contacts_create.
confirmbooleannofalseAsk the person before running.
sendRealValuesbooleannofalseLet real caller values reach the connected app; each use is recorded.
connectionstringnoThe connection a connected app's action uses, by id or name. Resolved when the agent is published.

OnCallEndOutcome

interface · @voicelayer/sdk

interface OnCallEndOutcome

How the call went, handed to onCallEnd.

Fields

NameTypeRequiredDescription
reasonstringyesWhy the call ended.
durationMsnumberyesHow long the call lasted, in milliseconds.
processCompletedbooleanyesWhether the process completed.
fieldsCapturednumberyesHow many process fields were captured.
handoffOccurredbooleanyesWhether the call was handed to a person.

EndCallInfo

interface · @voicelayer/sdk

interface EndCallInfo

Handed to endCall.onEnd: why the call is ending.

Fields

NameTypeRequiredDescription
reasonstringnoWhy the call is ending, for example the reason the agent gave when it ended the call.
triggerEndCallTriggeryesWhat caused the end: see EndCallTrigger. One of tool, host, idle, max_duration, participant-left, flow, engine-closed, user, admission, agent-disconnected.
teardown'room' | 'agent'yesWhat the platform is about to close: the whole room or only the agent.

DtmfEvent

interface · @voicelayer/sdk

interface DtmfEvent

A key the caller pressed on their phone, handed to onDtmf.

Fields

NameTypeRequiredDescription
participantIdstringyesThe participant who pressed the key.
codenumberyesThe key's DTMF code number.
digitstringyesThe key as a character: 0 to 9, * or #.
atDateyesWhen the key was pressed.

Participant

interface · @voicelayer/sdk

interface Participant

Someone on the call, handed to participants.onJoin and participants.onLeave.

Fields

NameTypeRequiredDescription
idstringyesThe participant's id within the call.
kindstringyesWhat kind of participant this is, for example a caller, a person you transferred to, or the agent.
isAgentbooleanyesWhether this participant is the agent itself.
phonestring | nullyesThe participant's phone number, or null when they do not have one.
displayNamestring | nullyesThe participant's name when the platform knows it, otherwise null.
attributesReadonly<Record<string, string>>yesExtra attributes attached to the participant, including any participants.attributes returned.
joinedAtDateyesWhen the participant joined.
leftAtDate | nullyesWhen the participant left, or null while they are still on the call.

TranscriptHandle

interface · @voicelayer/sdk

interface TranscriptHandle

The conversation so far, handed to a handoff.briefing function.

tail

tail(n: number): string

The last n turns, one speaker: text line per turn.

Parameters
NameTypeRequiredDescription
nnumberyesHow many turns to include.
Returns

string

full

full(): string

The whole transcript, one speaker: text line per turn.

Returns

string

AgentHandle

interface · @voicelayer/sdk

interface AgentHandle<TProcess extends Record<string, ProcessField> = Record<string, ProcessField>>

What defineAgent returns. The CLI reads it to build and deploy the agent, and .start() runs it.

Fields

NameTypeRequiredDescription
namestringyesThe agent's name, from its config.
configAgentConfig<TProcess>yesThe config you passed to defineAgent.
messageHandlerMessageHandler | undefinedyesThe direct-mode handler set by onMessage, if any.

manifest

manifest(opts?: BuildOptions): BuildResult

Build the agent's manifest, its handler table and any problems with the config, without running anything. Use it in tests and in CI to catch a bad definition early.

Parameters
NameTypeRequiredDescription
optsBuildOptionsnoBuild options such as the build identity.
Returns

BuildResult: The manifest, the handler table and a list of issues.

onMessage

onMessage(handler: MessageHandler): AgentHandle<TProcess>

Answer text in direct mode. Each inbound message of a conversation whose controller is api is handed to handler, which replies with ctx.send (every platform check, including the output checks, runs on the server) and hands the conversation over with ctx.setController. It runs on a scoped API key (VOICELAYER_API_KEY), never the worker credential. Returns a new handle carrying the handler; call .start() on it.

Parameters
NameTypeRequiredDescription
handlerMessageHandleryesCalled with each inbound message and a context to answer through.
Returns

AgentHandle<TProcess>: A handle that serves the handler.

Throws
  • TypeError when handler is not a function.
Example
const agent = defineAgent({ name: 'text-bot', prompt: 'You answer questions.' }).onMessage(async (message, ctx) => {
  await ctx.send({ text: `You said: ${message.text}` });
});
await agent.start();

start

start(opts?: StartOptions): Promise<WorkerRunner | DirectRunner | RoomServer>

Run this agent. With a lock file it serves your handlers to the platform and, with onMessage, runs direct mode beside them. With onMessage and no lock file it runs direct mode alone, so a program that only answers text needs no deploy. Inside a hosted room it serves the room's local contract instead. Resolves once running.

Parameters
NameTypeRequiredDescription
optsStartOptionsnoThe lock file, signal handling, logger and the rest of StartOptions.
Returns

Promise<WorkerRunner | DirectRunner | RoomServer>: The worker runner, the direct runner, or the room server, depending on where it runs.

Throws
  • LockError when there is no lock file and the agent has no onMessage.
  • BuildError when the agent's definition has errors.
Example
await agent.start({ log: consoleLogger('debug') });

startAgents

function · @voicelayer/sdk

startAgents(handles: readonly AgentHandle[], opts?: StartOptions): Promise<WorkerRunner>

Start several agents in one process. They share one connection and one capacity, and each is registered by its sealed hash from the lock file voicelayer deploy wrote. An agent with onMessage also answers text in direct mode beside it. Calling .start() on several handles in the same tick has the same effect.

Parameters
NameTypeRequiredDescription
handlesreadonly AgentHandle[]yesThe agents to serve.
optsStartOptionsnoThe lock file, signal handling, exit behaviour, logger and the rest of StartOptions.
Returns

Promise<WorkerRunner>: The runner. Call runner.drain() to finish current calls and stop, or runner.stop() to stop at once.

Throws
  • BuildError when an agent's definition has errors.
  • LockError when there is no lock file, or it has no build of the agent for the credential's environment.
  • TypeError when more than one handle has onMessage in the same process.
Example
import { startAgents } from '@voicelayer/sdk';
import { sales, support } from './agents.js';

await startAgents([sales, support]);

StartOptions

interface · @voicelayer/sdk

interface StartOptions extends Omit<RunnerOptions, 'builds'>

Options for starting an agent: the lock file to read, how the process handles signals and exits, and where the connection goes. Everything has a default that works for a deployed worker.

Fields

NameTypeRequiredDefaultDescription
lockstring | LockFileno`VOICELAYER_LOCK_FILE`, else `./voicelayer.lock.json`The lock file voicelayer deploy wrote: a path, or the parsed lock.
signalsbooleannotrueInstall SIGTERM and SIGINT handlers: the first drains current calls, a second exits at once.
exitbooleannotrueExit the process when the runner finishes (every build retired, or drained after SIGTERM).
directOmit<ServeDirectOptions, 'signal' | 'log'>nokey from `VOICELAYER_API_KEY`Direct-mode options for an agent with onMessage, such as the scoped API key.
direct.apiKeystringnoA scoped REST key (messages:send, messages:read, events:read, conversations:control). Default VOICELAYER_API_KEY. A vlw_ worker credential is refused.
direct.baseUrlstringnoDefault VOICELAYER_API_URL, else https://api.vlayers.ai.
direct.channelsreadonly string[]noOnly these channels' messages reach the handler (one channel also narrows the stream server-side).
direct.cursorStoreCursorStorenoWhere to keep the place in the event stream, so a restart continues where it stopped.
direct.onHandlerError(err: unknown, message: InboundMessage) => voidnoTold about a handler that threw (after it is logged); the runner moves on to the next message.
direct.fetchtypeof fetchnoTests and proxies.
direct.reconnect{ /** The wait before the first reconnect, in milliseconds. @default 500 */ readonly initialDelayMs?: number; /** The longest wait between reconnects, in milliseconds. @default 30000 */ readonly maxDelayMs?: number; /** Reconnect when the stream is silent this long, in milliseconds. @default 45000 */ readonly idleTimeoutMs?: number; }noStream reconnect tuning (defaults: 500 ms first delay, 30 s cap, 45 s idle timeout).
direct.envNodeJS.ProcessEnvnoRead in tests: the process environment the defaults come from.
roomOmit<ServeRoomOptions, 'log'>noOptions for a hosted agent: ports and onRequest, which answers requests to the agent's published endpoints. Used only when the process runs inside a hosted room.
room.hoststringnoThe address to listen on. Default 0.0.0.0: the shim reaches the process over the room's loopback, and voicelayer image test over a docker network.
room.fetchtypeof fetchnoThe fetch that reaches the shim. Default the global one.
room.envReadonly<Record<string, string | undefined>>noThe environment to read PORT, VL_SHIM_PORT, PUBLIC_PORT and VL_ROOM_ID from. Default process.env.
room.portnumbernoThe handlers' port ($PORT, 8080 by default).
room.shimPortnumbernoThe shim's actions port ($VL_SHIM_PORT, 7070 by default).
room.publicPortnumbernoWhere published requests arrive ($PUBLIC_PORT). Not listened on when unset (the controller sets it only for an agent with endpoints).
room.onRequest(req: RoomRequest) => RoomResponse | unknown | Promise<RoomResponse | unknown>noAnswers published endpoint requests. Without it, they get a 404 that says the agent has no handler.
room.signalsbooleannoInstall SIGTERM/SIGINT handlers: stop accepting, finish what is running (up to drainMs), exit. Default true.
room.exitbooleannoExit the process when the server stops after a signal. Default true.
room.drainMsnumbernoHow long to let running requests finish after a stop signal, in milliseconds.
workerKeystringno`VOICELAYER_WORKER_KEY`The worker credential (vlw_…). A project API key is refused before any connection opens.
edgeUrlstringno`VOICELAYER_EDGE_URL`, else `wss://edge.vlayers.ai/worker`The platform's worker address. ws:// is accepted only for localhost.
capacitynumberno20 (or `VOICELAYER_WORKER_CAPACITY`)How many invocations the process runs at once, shared by every agent in it.
regionstringnoA region label sent with the connection, shown in the dashboard.
logRunnerLoggerno`consoleLogger()`Where the runner writes its log lines: an object with debug, info, warn and error functions that take a message and fields. consoleLogger(level) writes JSON lines to stderr, silentLogger writes nothing.
onEvent(event: RunnerEvent) => voidnoCalled with runner lifecycle events: connected, registered, register_rejected, draining, retired, fatal and the rest.