@voicelayer/sdk
v1.1.0
Published
Official SDK for VoiceLayer — define, run, and orchestrate voice AI agents on the VoiceLayer control plane.
Maintainers
Readme
@voicelayer/sdk
Build voice AI agents that run real business processes. VoiceLayer runs the call; your code is the handlers.
pnpm add @voicelayer/sdkWhich version is this? 1.0: a thin client. The package holds the authoring API, the handler runner, the REST client and the
voicelayerCLI, and depends onzodand@voicelayer/apialone: no LiveKit, no provider plugin, no AI framework, no runtime. Running a 0.x worker (a LiveKit worker you host)? Move with MIGRATING-1.0.md.
Hello, voice agent
// agent.ts
import { defineAgent } from '@voicelayer/sdk';
export default defineAgent({
name: 'hello',
prompt: 'You are a friendly receptionist. Ask the caller how you can help.',
});export VOICELAYER_API_KEY=… # a project API key (dashboard → Settings → API keys)
npx voicelayer dev ./agent.ts # uploads to your dev environment, serves your handlers, publishesOpen the agent in the dashboard's Playground, or call a test number bound to it. There is no LiveKit project to create, no provider key in your process and no port to open: VoiceLayer runs the call, on its own pool, behind its guard, with the models and keys you saved under Connections in the dashboard. Your process only answers when the pool calls one of your handlers.
What your code is: handlers
An agent is a manifest (the prompt, the model references, the triggers, the process, the tools it offers — plain data, uploaded and versioned) plus handlers: the functions in it. The pool invokes a handler by id, over one outbound WebSocket your worker opens to VoiceLayer's edge. The id comes from where the function sits, so you never name one:
| In your config | Handler id | Kind |
|---|---|---|
| tools.<name>.run | tool.<name> | tool: the model calls it; 10 s |
| triggers.<name>.on / .then.run (functions) | trigger.<name>.on / .run | blocking: 1 s / 2 s |
| process.completeWhen.custom, .onField, .onComplete | process.completeWhen, … | blocking: 2 s / 2 s / 5 s |
| handoff.briefing (a function), participants.attributes, endCall.onEnd | the same names | blocking: 2 s / 1 s / 2 s |
| onUtterance, onFieldCaptured, onCallEnd, onDtmf, participants.onJoin/onLeave | hook.onUtterance, … | notification: never waited on |
| onQuery, or brain | brain.onQuery | brain: one turn per model request |
A blocking handler that is slow or down takes its fail-safe default (a failed tool result, no match, the platform's own briefing),
so a crashed worker never hangs a call. A handler holds no call state in memory between invocations: two invocations of one call
can land on two processes. ctx.metadata is pool-held state, ctx.memory is durable across calls (keys starting with answers. are reserved: VoiceLayer keeps the caller's remembered answers there, in its own shape, so do not use that prefix for your own keys); module-level caches are fine.
A real agent
import { defineAgent, defineTool, httpTool, openai, deepgram } from '@voicelayer/sdk';
export default defineAgent({
name: 'venue-escalation',
prompt: 'You handle escalations from venue managers. Be brief; open a ticket, then bring in the engineer.',
greeting: 'Wifinium network operations — which venue are you calling about?',
capabilities: ['system.say', 'system.transfer_call'], // what handlers may do to the call; the guard refuses the rest
toolBindings: [], // dashboard registry tools this agent uses. `[]` means none
models: {
stt: deepgram.stt({ model: 'nova-3' }),
llm: openai.llm({ model: 'gpt-4o' }),
tts: deepgram.tts({ model: 'aura-2-harmonia-en' }),
},
tools: {
// code, served by your worker: it can reach your private network
...defineTool({
name: 'lookup_engineer',
description: 'Find the on-call engineer for a venue',
input: { venue: 'string' },
run: async ({ venue }) => rota.onCall(venue),
}),
// a declaration the pool runs: a fixed endpoint, no code
...httpTool({
name: 'open_ticket',
description: 'Open a ticket for the venue',
input: { venue: 'string', summary: 'string' },
url: 'https://tickets.example.com/api/venues/{venue}/tickets',
}),
...defineTool({
name: 'bring_in_engineer',
description: 'Transfer the caller to the on-call engineer',
input: { venue: 'string' },
run: async ({ venue }, ctx) => {
const engineer = await rota.onCall(venue);
await ctx.handoff(engineer.phone, { reason: 'sev-1', briefing: `Venue ${venue} is down; the ticket is open.` });
},
}),
},
onCallEnd: async (outcome, ctx) => audit.record(ctx.call.callId, outcome.reason),
});defineAgent returns a handle; it starts nothing. voicelayer dev and voicelayer deploy load the module, and a production
worker calls .start() (see Production).
Keys: two kinds, for two jobs
| Variable | What it is | Who uses it |
|---|---|---|
| VOICELAYER_API_KEY | A project API key. Uploads and publishes. | The voicelayer CLI (your laptop, CI) |
| VOICELAYER_WORKER_KEY | A worker credential, vlw_…, bound to one environment (dev, stg, prd). It only opens a session to the edge and can call no API. | The running worker |
The runner refuses a project key as a worker credential before any socket opens, and the edge refuses it too. It dials wss://
only (ws:// only to localhost). Provider keys are never in your process: they live under Connections, per workspace.
The CLI
voicelayer dev ./agent.ts # serve against dev; watches the file
voicelayer manifest ./agent.ts --check # build the manifest offline and run the upload's own lint; names anything that can't cross
voicelayer deploy ./agent.ts --env prd # upload (writes voicelayer.lock.json), wait for workers, publish
voicelayer deploy ./agent.ts --env prd --no-publish # upload only: roll the workers, then…
voicelayer publish --env prd --min-workers 2 # …publish once 2 sessions of the new build are connected
voicelayer versions --env prd # published versions and uploaded builds, with connected workers
voicelayer versions discard --env prd --manifest <hash>deploy writes voicelayer.lock.json: ship it with your code. A production worker registers the build the lock names, for the
environment its credential is bound to, and refuses to start if its code lacks a handler the build lists. A fresh build id per
deploy makes every deploy a new immutable version, so a handler-only change can never move a call that is already running onto new code.
Working with messages over the public API (these use VOICELAYER_API_KEY, or the key login stored):
voicelayer login --api-key vl_test_… # check the key and store it (~/.config/voicelayer/config.json, 0600)
voicelayer test inbound --channel sms --from +15550101 --text "hi" # test keys: simulate a person writing
voicelayer messages send --channel sms --to +15551234567 --text "Your order shipped"
voicelayer listen --types 'message.*' --forward http://localhost:3000/webhooks # stream events, re-POST them signed
voicelayer logs tail --errors # your API requests as they happenAnswer text from your code (direct mode)
A conversation whose controller is api is handed to your code. onMessage answers it over the public API with a scoped REST key
(messages:send, messages:read, events:read, conversations:control in VOICELAYER_API_KEY, never the vlw_ worker credential):
export default defineAgent({ name: 'support', prompt: '…' })
.onMessage(async (message, ctx) => {
if (/human|person/i.test(message.text ?? '')) return ctx.setController('human', { reason: 'asked for a person' });
await ctx.send({ text: `Thanks, we got: ${message.text}` });
});An agent that calls .onMessage declares it in its manifest (textAnsweredBy: 'direct', sealed with each version you deploy), and
that is what makes a Line on it default to controller api: VoiceLayer runs no text turn for it, your code answers. An agent without
onMessage is answered by VoiceLayer (a hosted agent answers text as it answers calls). onMessage runs beside a worker; a hosted
room ignores it, so register it on an agent you run yourself.
Every gate runs on VoiceLayer's side, the Output Guard included: a refused reply throws OutputRefusedError and nothing is sent.
A redelivered message never sends twice (each ctx.send carries an idempotency key). .start() serves it; with no lock file it
runs direct mode alone. serveDirect(handler, { channels, cursorStore }) from @voicelayer/sdk/direct is the same runner on its own.
Models
models takes references: a helper call (deepgram.stt({ model }), openai.llm({ model }), anthropic.llm, google.llm,
cartesia.tts({ voice }), elevenlabs.tts({ voice }), assemblyai.stt(), openai.realtime()) or a 'provider/model' string
('anthropic/claude-sonnet-5-5'; a bare id is OpenAI's). A slot you leave out belongs to the dashboard. A helper refuses
apiKey and baseURL: keys are never in code or in a manifest.
Real values and placeholders
A handler is handed placeholders for the caller's values (<PII_PHONE_1>) unless its definition sets sendRealValues: true
(each release is recorded on the call). ctx.call.callerId follows the same rule.
Transfers
ctx.handoff(to, { reason, briefing, mode }) asks the pool to transfer the call, and the pool checks every leg before it dials:
the destination must be declared in the manifest (handoff.fallback, handoff.routes) or allowed by the workspace's
Transfer destinations policy (an allowlist the owner sets in the dashboard, never in code — the way a looked-up engineer's number
passes), and then the leg passes the platform's outbound gate (toll-fraud deny list and velocity cap, wallet hold, do-not-call). It
is billed as a child leg of the call. A refused transfer throws from ctx.handoff with the refusal's code and the call stays up.
Bring your own brain
export default defineAgent({
name: 'support',
prompt: 'You answer for Acme.',
onQuery: async (text, { messages, signal }) => myAgent.reply(text, messages, { signal }), // a string, or an async iterable of strings
});Your worker serves the brain over the same socket as your tools. VoiceLayer keeps STT, TTS, turn-taking and telephony, speaks the
first sentence as soon as it lands, and tells your brain when the caller barges in (signal aborts; stop work, it is your tokens).
A brain that needs VoiceLayer's tools uses a framework adapter from @voicelayer/sdk as brain: — openaiAgentsBrain,
claudeAgentBrain or langgraphBrain — which registers the turn's tools as the framework's own, so a tool call crosses to the pool
and runs under the same guard as any model tool. See examples/brain-openai-agents.ts. A private model behind a firewall runs
through the vl-brain daemon instead (brain connectors).
A brain's internals are yours and outside VoiceLayer's guard. The perimeter is every conversation VoiceLayer runs. A customer brain's internals and a call handed off at SIP are outside it; VoiceLayer guards what goes to a brain, what comes back, and every action it asks for.
Run your agent hosted
No server of your own to run: VoiceLayer builds your project into an image and runs it in a room.
npm install @voicelayer/sdk # a dependency, not a devDependency: the image installs production dependencies
voicelayer deploy ./src/agent.ts --env prd --hosted./src/agent.ts exports defineAgent({...}) and nothing else is needed (do not call .start() yourself). --hosted builds the
whole project with Docker (linux/amd64, less what your .dockerignore lists: put node_modules and anything secret there),
pushes it, submits the version by image digest and waits for its room to register. With no Dockerfile in the project it
generates one: it copies the project, installs your dependencies fresh and runs voicelayer serve ./src/agent.ts. A Dockerfile
of your own takes over; end it with CMD ["npx", "voicelayer", "serve", "./src/agent.ts"], or call agent.start() from your own
entry (inside a room it serves the room instead of dialling the edge).
What runs in the room is the SDK's room server (serveRoom(agent)): the shim answers the platform, and turns each tool call and
hook into a request on your process (GET /healthz, POST /v1/tools/{name}, /v1/hooks/{handler}, /v1/events/{handler},
/v1/calls/start|end on $PORT). Your handlers are the ones you wrote for a worker: ctx.say, ctx.handoff, ctx.endCall,
ctx.memory and the rest reach the call through the shim, under the capabilities your agent lists.
export default defineAgent({
name: 'desk',
prompt: '…',
capabilities: ['system.say'],
tools: { ...defineTool({ name: 'where', description: 'Where am I running?', input: {}, run: () => ({ room: process.env.VL_ROOM_ID }) }) },
declaredEndpoints: [{ host: 'api.github.com' }], // the hosts your code may call out to
endpoints: [{ name: 'status', kind: 'api', auth: { type: 'public' } }], // run.vlayers.ai/<id>/api/…
});- Your room:
process.env.VL_ROOM_IDis the id of the room your code runs in (whatvoicelayer roomslists). - Published endpoints (
endpoints) arrive on$PUBLIC_PORT; answer them withagent.start({ room: { onRequest } })orserveRoom(agent, { onRequest }).req.platform('store.put', {…})takes a platform action under the request, within thecapabilitiesthe endpoint declares. - Egress is the hosts in
declaredEndpoints; anything else the room tries to reach is refused by name. - Check the image before you ship it:
voicelayer image test <image> ./src/agent.tsstarts it as a room would and runs the shim's conformance calls for your agent's own manifest (the manifest is written under./.voicelayer/for the run: Docker on macOS shares your home directory, not/var/folders). To run the same server on your machine,voicelayer serve ./src/agent.ts(setPORT, andVL_SHIM_PORTfor a shim to bridgectxto). - Any language:
voicelayer deploy … --image sha256:…submits an image you built elsewhere that serves the same HTTP contract (room-local.v1.jsonin@voicelayer/contracts).
Production
import agent from './agent.js';
await agent.start(); // serves the handlers named in voicelayer.lock.json; SIGTERM drainsexport VOICELAYER_WORKER_KEY=vlw_… # for the environment this worker serves
node agent.jsSeveral agents in one process share one socket and one capacity: startAgents([a, b, c]), or .start() on each in the same tick.
The rollout order is fixed: upload the build, start its workers beside the old ones, publish, and let the old build drain.
voicelayer deploy does all of it for workers you start by hand; with --no-publish / publish you roll your own fleet between.
SIGTERM is not exit: a worker drains — it keeps serving calls pinned to its version and exits when the platform sends retire.
Set your host's kill timeout (terminationGracePeriodSeconds) to your longest call plus two minutes (plans allow 30, 120 or 240
minutes; 4 h 2 min covers every plan). A host that kills sooner strands calls still on that version. Roll back with
voicelayer publish --manifest <older hash> while the old workers are still up (or the dashboard's Restore); once they are gone it
is refused (no_workers) until you redeploy the old build from its lock file.
Testing
import { assertAgent, invoke, runBrain, testContext } from '@voicelayer/sdk/testing';
const ctx = testContext({ call: { callerId: '+15550100' }, answers: { ask: 'yes' } });
expect(await invoke(agent, 'tool.lookup_engineer', { venue: 'v-12' }, ctx)).toMatchObject({ phone: '+15550100' });
expect(ctx.handoffs).toEqual([]); // what the handler asked the pool to do is recorded
assertAgent(agent); // the manifest builds and passes the upload's lintA whole conversation does not run locally — the conversation runtime is the platform's. End to end is voicelayer dev against the
Playground, and voicelayer manifest --check in CI.
What's not in this SDK
- No LiveKit, no provider plugins, no audio. Per-participant audio and a custom conversation loop run in your own runtime on your own LiveKit project, which VoiceLayer hands the call to at SIP; that tier is built on demand.
- No
onCall,ctx.livekit,ctx.audio,models.vad, instance providers,securitysettings or private-network opt-ins. The build names each one with its replacement; see MIGRATING-1.0.md.
0.x
The 0.x line was a LiveKit worker you host: defineAgent({…}).start(import.meta.url), node agent.ts dev, your LiveKit and
provider keys in the worker's environment. It stays on npm, receives no releases (security fixes included) and keeps working
against the platform until 2027-03-15. Its documentation is the 0.7 README on npm; 0.8.x prints, when a worker starts, what that
agent would have to change for 1.0.
Stability
The package commits to semver, and its contracts (the manifest and the worker protocol) change only by adding.
Reference
- SDK documentation, migrating to 1.0, brains
- Transfers and the destination policy, deploy and hosting
- Pricing — $0.05/min, providers at cost
