How-to guide

Run your agent on VoiceLayer (hosted)

Have VoiceLayer run your agent's code in a room so there is no worker to operate, with an API, saved data, schedules, or an image in any language.

What you'll build

An agent whose code runs on VoiceLayer. You write the same defineAgent file as in Voice agents in code. One command builds it into an image, uploads it and publishes it. VoiceLayer starts a room for it, runs your tools there, and sleeps the room when nobody uses it.

You also get four things a worker you run yourself does not have: addresses at run.vlayers.ai that people and programs can call, saved data, cron schedules, and a list of the hosts your code may reach.

What a room is

A room is a small, sealed machine that runs your code. It has no open ports. VoiceLayer opens every connection to it, and your code can reach only the hosts you list. One room serves several calls at once. A published version runs in one or more rooms, and each room is billed while it runs.

You choose the room size (small, medium or large), how many rooms to keep ready, and when a quiet agent goes to sleep. Prices come from your plan and are shown on the agent's Hosting page.

Prerequisites

  • Node.js 22 or later. @voicelayer/sdk needs 22; the @voicelayer/api client alone needs only 18.
  • Docker, running on your machine. deploy --hosted builds the image with it.
  • A secret API key in VOICELAYER_API_KEY. See Authentication and API keys.
  • @voicelayer/sdk in your project's dependencies (not devDependencies): the image installs your dependencies and runs the SDK's room server.
  • Provider keys saved in the dashboard under Settings → Provider accounts, as for any agent.

Step 1: Write the agent

Start from npx @voicelayer/sdk init my-agent --template hosted: it writes this agent, a test and the package.json.

npm install @voicelayer/sdk

This agent also answers phone calls, so it has models. An agent that only serves endpoints and schedules needs no models and no provider keys: name and prompt are enough. It uses a model only if it takes calls or texts.

This agent has a tool, saved data, two published endpoints and a nightly schedule. Save it as agent.ts.

// agent.ts
import { anthropic, deepgram, defineAgent, defineTool, HandlerContextError, isRoomEnvironment, type RoomRequest } from '@voicelayer/sdk';

const agent = defineAgent({
  name: 'order-desk',
  prompt: 'You answer the phone for an online shop. Look up orders with the order_status tool. Be brief.',
  greeting: 'Thanks for calling. What is your order number?',
  capabilities: ['system.say'],
  toolBindings: [],
  models: {
    stt: deepgram.stt({ model: 'nova-3' }),
    llm: anthropic.llm({ model: 'claude-haiku-4-5' }),
    tts: deepgram.tts({ model: 'aura-2-harmonia-en' })
  },

  // The only hosts this agent's code may call. Anything else is refused by name.
  declaredEndpoints: [{ host: 'orders.example.com' }],

  tools: {
    ...defineTool({
      name: 'order_status',
      description: 'Look up the status of an order by its number',
      input: { orderId: 'string' },
      run: async ({ orderId }) => {
        const res = await fetch(`https://orders.example.com/v1/orders/${encodeURIComponent(orderId)}`);
        if (!res.ok) return { found: false };
        return { found: true, ...((await res.json()) as Record<string, unknown>) };
      }
    })
  },

  // Saved data: collections of JSON documents. `indexed` fields can be queried; `personal` fields hold people's details.
  store: {
    collections: [
      {
        name: 'notes',
        fields: [
          { name: 'orderId', type: 'string', indexed: true },
          { name: 'text', type: 'string' }
        ]
      }
    ]
  },

  // Published endpoints, served at https://run.vlayers.ai/<id>/api/... and so on. The schedule endpoint is
  // called only by the platform's clock.
  endpoints: [
    { name: 'notes', kind: 'api', auth: { type: 'key' }, capabilities: ['store.put', 'store.get', 'store.query'],
      // without this, store.get returns personal fields as placeholders; each release is recorded
      realValues: ['store.get']
    },
    { name: 'nightly', kind: 'schedule', auth: { type: 'platform' }, capabilities: ['store.query'] }
  ],

  // Cron in UTC, at most once a minute. If a run is missed, `run_once` runs it once when the platform can again.
  schedules: [{ name: 'count-notes', cron: '0 6 * * *', endpoint: 'nightly', missed: 'run_once' }]
});

export default agent;

// `req.path` is what follows /<id>/<kind>: /notes for an api call, /schedule/<name> for a schedule run.
// `req.endpoint` is the endpoint's name from the manifest. The platform sets it on every request, so it is
// undefined only if you call the room yourself (for example with curl against a local `voicelayer serve`).
async function onRequest(req: RoomRequest) {
  if (req.endpoint === 'nightly') {
    const found = (await req.platform('store.query', { collection: 'notes', limit: 100 })) as { documents?: unknown[] };
    console.log(`notes saved: ${found.documents?.length ?? 0}`);
    return { counted: found.documents?.length ?? 0 };
  }

  if (req.method === 'POST' && req.path === '/notes') {
    const body = req.json() as { id?: string; orderId?: string; text?: string } | undefined;
    if (!body?.id || !body.orderId || !body.text) return { status: 400, body: { error: 'send id, orderId and text' } };
    return req.platform('store.put', { collection: 'notes', id: body.id, value: { orderId: body.orderId, text: body.text } });
  }

  if (req.method === 'GET' && req.path.startsWith('/notes/')) {
    try {
      return await req.platform('store.get', { collection: 'notes', id: req.path.slice('/notes/'.length) });
    } catch (err) {
      // a document that does not exist rejects with reason `not_found`; any other refusal is not ours to hide
      if (err instanceof HandlerContextError && err.reason === 'not_found') return { status: 404, body: { error: 'no such note' } };
      throw err;
    }
  }

  return { status: 404, body: { error: 'not_found' } };
}

if (isRoomEnvironment()) {
  await agent.start({ room: { onRequest } });
}

The project needs "type": "module" in package.json for the top-level await. The same file is in the repository as examples/docs/hosted-agent.ts.

Check it builds, with no network:

npx voicelayer manifest ./agent.ts --check --offline

You see check ok.

Step 2: Run it on your machine (optional)

voicelayer serve runs the room server for your agent, the same way the image does. It listens on $PORT (8080 by default).

PORT=8080 npx voicelayer serve ./agent.ts
curl http://127.0.0.1:8080/healthz

Outside a room there is no platform to bridge ctx to, so a handler that calls ctx.say or ctx.memory is refused. Test those with testContext: see Testing agents and channels.

To check the image before you publish it, build it and run the platform's own conformance calls against it. This starts your image the way a room does, then calls readiness and each tool you declared with an example input:

docker build --platform linux/amd64 -t order-desk .
npx voicelayer image test order-desk ./agent.ts

image test needs Docker. It pulls a conformance image on first use; --conformance-image <ref> names another. It prints ok: the image answers readiness and every declared handler when your image passes.

Step 3: Deploy

export VOICELAYER_API_KEY=vl_...
npx voicelayer deploy ./agent.ts --env dev --hosted

The command uploads the manifest, builds an image for linux/amd64, pushes it in chunks, submits the version by its digest and waits for the room to register. You see lines like these:

order-desk: uploaded build 3f9c1a2b7d10 as 09411fb06d39 (dev, ...)
  building registry.vlayers.ai/...
order-desk: submitted version 1 (sha256:...); waiting for its room to register
  waiting: starting
order-desk: published as version 1; its room is registered
  • If your project has no Dockerfile, one is generated: Node 22, your whole project less what .dockerignore lists, dependencies installed fresh in the image, and voicelayer serve as the command. Add a .dockerignore that lists node_modules and any secret file. A Dockerfile of your own takes over; end it with CMD ["npx", "voicelayer", "serve", "./agent.ts"].
  • The command also writes voicelayer.lock.json, as deploy does for a worker.
  • A scan of the image reports known vulnerabilities and never blocks a publish.
  • --timeout <seconds> sets how long it waits (600 by default). Exit code 0 means published, 1 an error, 2 that it is still waiting or the version conflicted.
  • If the room never becomes ready, the version fails with the room's log tail and the readiness error, and calls on the live version are untouched.

Production is the same command with --env prd.

Find your agent id and endpoint URL

  1. Agent id. deploy writes it to voicelayer.lock.json, in agents[].agent for your agent's name and environment. It is a UUID.
  2. Endpoint URL. Ask the API for the agent's endpoints:
curl https://api.vlayers.ai/v1/agents/<agent id>/endpoints -H "Authorization: Bearer $VOICELAYER_API_KEY"

Each item of endpoints has an id (the <id> in the address) and routes, one per kind, each with its full url, for example https://run.vlayers.ai/<id>/api. Add your path to it. An endpoint appears once its version has published. voicelayer rooms shows rooms, not endpoints, and deploy does not print the URL. A new version starts its room before the old one drains.

Step 4: See and stop your rooms

npx voicelayer rooms
npx voicelayer logs <roomId> --follow
npx voicelayer rooms drain <roomId>

rooms lists the rooms that are running: id, agent, size, state, version and age. --agent <agentId> and --env dev|stg|prd narrow the list, --all adds rooms that ended in the last week, and --json prints JSON.

logs <roomId> prints what the room's containers printed.

FlagWhat it does
--container process|shimOnly your process (process) or the platform's side of the room (shim)
--stdout or --stderrOnly one stream. Not both.
--since <iso>Only lines after this time, for example 2026-11-04T09:00:00Z
--grep <text>Only lines that contain this text
--tail <n>The newest n lines (200 by default)
--follow, -fKeep printing new lines until you stop it
--jsonOne JSON object per line

Room logs can hold what was said on calls. They need an API key with the room_logs:read scope, or full access, and every read is recorded on your workspace's access log.

rooms drain <roomId> stops sending a room new work. It ends when its current calls are done. If the version still needs a room, a replacement starts first.

Published endpoints

An endpoint is an address at https://run.vlayers.ai/<id>/... that reaches your code. You declare it in endpoints. Each has a name, a kind and an auth.

KindAddressWho may callYour code sees
api/<id>/api/<path>anyone (public), a holder of an endpoint key (key), or a signed request (signature)/<path>
hook/<id>/hooks/<name>a signed request (signature) or an endpoint key (key)/hooks/<name>
mcp/<id>/mcpan endpoint key (key) or OAuth (oauth)/mcp
schedulenoneonly VoiceLayer's clock (platform)/schedule/<name>
  • Which auth to use. public lets anyone call it, so use it only for something you would put on a public web page, and cap its spend. key needs an endpoint key, so use it for servers and scripts. For a form on your website, post to your own server and have that server call the endpoint with a key. Do not put a key in a web page, and do not call the endpoint straight from browser JavaScript on another origin: VoiceLayer drops Access-Control-Allow-* headers from responses, so a cross-origin browser request is blocked. signature is for a provider that signs its webhooks (hook, or api).
  • <id> is the id of the endpoint (one per endpoint name and environment), not of the agent. It is an opaque string, or a name your workspace claims. It is an address, not a secret. GET /v1/agents/{id}/endpoints lists each endpoint's id, its full url per kind, who may call it, its limits and what it has spent this month. Copy the URL from there.
  • A public endpoint can be called by anyone, and its traffic is billed to your workspace. Set a monthly spend cap with PUT /v1/endpoints/{endpoint} (monthlySpendCapUsd).
  • An endpoint key looks like vle_…. Make one with POST /v1/endpoints/{endpoint}/keys (body { "name": "…", "kind": "api" }; kind is api, hook or mcp, and the endpoint must use key auth for that kind; expiresAt is optional) and give it to your caller, who sends it as Authorization: Bearer vle_… or x-api-key. The secret is shown once. A key opens one endpoint and cannot call the VoiceLayer API.
  • VoiceLayer removes cookies and any VoiceLayer credential from a request before your code sees it, and adds x-vl-caller with who called.
  • Endpoints answer machines. A response of type text/html or XML is refused.
  • A preview opens one version of an endpoint, for your workspace only, at run.vlayers.ai/<id>--<version>/...: POST /v1/endpoints/{endpoint}/previews. The link works for 60 seconds and opens once.
  • An endpoint that VoiceLayer switched off can be appealed with POST /v1/endpoints/{endpoint}/appeal.

Your code answers requests through onRequest, as in Step 1. req has:

FieldType
method, path, endpoint, caller, requestIdstrings. path is what follows /<id>/<kind>. endpoint is the name from your manifest. caller is x-vl-caller: the endpoint key's id, the OAuth subject, anonymous, or scheduler.
querya URLSearchParams
headersNode's IncomingMessage['headers'] (lowercase names)
bodya Buffer
json()the body parsed, or undefined when it is empty or not JSON
platform(kind, params)a platform action, below

Return a plain value to send it as JSON with status 200, or { status, headers, body }. Without onRequest, a request gets a 404 that says the agent has no handler.

req.platform(kind, params) asks the platform to act for this request. It runs only if the endpoint lists the kind in capabilities (for example capabilities: ['store.put']), and it goes through the same checks as the REST API. The result is the REST route's JSON body. A refusal rejects with a HandlerContextError that has a code and a message.

KindparamsResult
store.put{ collection, id, value }{ document: { collection, id, value, updatedAt }, created }
store.get{ collection, id }{ document: { collection, id, value, updatedAt } }
store.delete{ collection, id }{ deleted }
store.query{ collection, where?, orderBy?, limit?, cursor? }{ documents: [{ collection, id, value, updatedAt }], nextCursor }
messages.sendthe body of POST /v1/messages (channel, to, content, from), plus an optional idempotencyKeythe send response
conversations.read{ conversationId, messages?, limit? }the conversation, with messages when you ask
memory.read{ subjectId, query?, k?, space? }the subject's profile, or search results when query is set
memory.write{ subjectId, text, wait?, space? }the new fact
calls.createthe outbound-call request (to, phoneNumberId, agentId?, variables?, amd?), plus an optional idempotencyKeythe call

store.get and store.query return people's details as placeholders. To get the real values, list the kind in that endpoint's realValues, as the notes endpoint in Step 1 does with realValues: ['store.get']. Each release is recorded.

Inside a room, your process learns where it is from these environment variables: PORT (your handlers, 8080 by default), VL_SHIM_PORT (the platform's side, 7070 by default), PUBLIC_PORT (published requests; set only for an agent with endpoints) and VL_ROOM_ID (this room's id, the one voicelayer rooms lists).

agent.start({ room: { onRequest } }) and serveRoom(agent, { onRequest }) do the same thing inside a room. start is the one to use: it serves the room when VL_SHIM_PORT is set and otherwise connects a worker. serveRoom is exported by @voicelayer/sdk for when you want the server without start. Both take port, shimPort, publicPort, host, signals, exit and drainMs. A room runs one agent. Starting the same agent twice returns the same server.

Errors. To answer an error yourself, return { status: 400, body: { error: '...' } }. If your handler throws, or a req.platform call rejects and you do not catch it, the caller gets a 500 with handler_error and the error message, so catch what you can explain. A rejected req.platform is a HandlerContextError (exported by @voicelayer/sdk) with a code and a reason: guard_denied for a blocked send, capacity for money or rate limits, not_authorized for a missing capability, invalid_args for a bad request or a missing document, handler_error for a server fault. store.get of a document that does not exist rejects with code invalid_args and reason not_found; the example in Step 1 turns that into a 404. Import the request type with import type { RoomRequest } from '@voicelayer/sdk' when you pass req to your own functions. RoomResponse is the shape of { status, headers, body }.

req.endpoint is set by the platform on every request. It is undefined only if you call the room yourself, outside the platform.

A caller whose request is refused by VoiceLayer itself gets a body like { "error": "unauthorized", "message": "..." } with a named reason, never a silent drop.

Saved data

A hosted room keeps no state of its own. Data that has to outlive a request goes in the agent's store: collections of JSON documents that you declare in store.

  • A collection name is lowercase letters, digits, - and _, and starts with a letter.
  • A field has a name, a type (string, number or boolean) and optionally indexed, personal and hashed. Only indexed fields can be queried. where is equality on indexed fields, all of which must match. There is no range filter ("older than"): to find old documents, orderBy an indexed number field (a hashed field can be matched but not ordered) and page with cursor, or keep your own index field. A cursor is a position in the list, not a bookmark on a document. If you delete documents while paging, later pages skip some. To delete in bulk, collect the ids first and delete afterwards, or query again from the start (no cursor) after each batch.
  • A personal field holds a person's details. A handler without the real-values capability reads it as a placeholder. An indexed and personal field must also be hashed: only a keyed hash of it is kept in the clear, so you can match it but not order by it. The build refuses the mix without hashed.
  • A document id is 1 to 128 characters: letters, digits and . _ : -. A document is a JSON object. Limits on document size, documents per collection and total bytes come from your plan, and a write over a limit is refused with the reason.
  • store.query takes where, orderBy ({ field, direction: 'asc' | 'desc' }), limit (1 to 100, 50 by default) and cursor, and answers { documents, nextCursor }.

In an endpoint, use req.platform('store.put', { collection, id, value }), store.get and store.delete ({ collection, id }) and store.query ({ collection, where, orderBy, limit, cursor }), as in Step 1.

From outside, use the REST API with a key that has workspace:read or workspace:write:

REST routeSDK method
GET /v1/agents/{id}/storehosting.describeAgentStore
GET /v1/agents/{id}/store/{collection}/docs/{docId}hosting.getStoreDocument
PUT /v1/agents/{id}/store/{collection}/docs/{docId}hosting.putStoreDocument
DELETE /v1/agents/{id}/store/{collection}/docs/{docId}hosting.deleteStoreDocument
POST /v1/agents/{id}/store/{collection}/queryhosting.queryStoreDocuments
// store-rest.ts
import { VoiceLayer } from '@voicelayer/api';

const agentId = process.env.AGENT_ID;
if (!agentId) throw new Error('set AGENT_ID to the hosted agent id');

const voicelayer = new VoiceLayer(); // reads VOICELAYER_API_KEY

console.log(await voicelayer.hosting.describeAgentStore(agentId));

await voicelayer.hosting.putStoreDocument(agentId, 'notes', 'note-1', {
  value: { orderId: 'A-1001', text: 'Customer wants a call back after 5pm' }
});

console.log(await voicelayer.hosting.getStoreDocument(agentId, 'notes', 'note-1'));

console.log(
  await voicelayer.hosting.queryStoreDocuments(agentId, 'notes', {
    where: { orderId: 'A-1001' },
    orderBy: { field: 'orderId', direction: 'asc' },
    limit: 20
  })
);

await voicelayer.hosting.deleteStoreDocument(agentId, 'notes', 'note-1');
npm install @voicelayer/api
export VOICELAYER_API_KEY=vl_...
export AGENT_ID=<the agent's id>
npx tsx store-rest.ts

A tool handler or a call hook has no ctx.store. Reach saved data from an endpoint with req.platform, or over REST.

Schedules

A schedule calls a published endpoint of kind schedule on a cron timetable.

endpoints: [{ name: 'nightly', kind: 'schedule', auth: { type: 'platform' } }],
schedules: [{ name: 'count-notes', cron: '0 6 * * *', endpoint: 'nightly', missed: 'run_once' }]
  • cron has five fields: minute, hour, day of month, month, day of week. It is in UTC. Seconds and names like @hourly are not accepted.
  • A schedule runs at most once a minute.
  • missed says what to do with a run that fell due while the platform could not run it, for example during an outage or with an empty wallet. skip (the default) drops it. run_once runs it once when the platform can again.
  • Each run is one request to /schedule/<name> with a run key. A retried run is the same run, and the platform actions it takes are not repeated.
  • A schedule keeps an agent awake if it fires more often than the sleep time.
  • Previews never run schedules.
  • A run succeeds when your handler answers with a 2xx status, within the endpoint's timeout (30 seconds by default). If it fails, the platform tries again with a growing wait, for up to 3 attempts in all and within an hour of the scheduled time. After that the run is recorded as failed with its reason. A run that runs more than once never repeats the platform actions it already took.
  • Schedules change only by publishing a new version.

See when each schedule runs next and how recent runs ended with GET /v1/agents/{id}/schedules. Run one now to test it with POST /v1/agents/{id}/schedules/{name}/run.

Hosts your code may reach

declaredEndpoints is the list of hosts your room may call. Everything else is refused by name.

declaredEndpoints: [{ host: 'orders.example.com' }]
  • host is a lowercase DNS name over TLS on port 443. No port, no IP address, no wildcard.
  • To call a host with a credential that VoiceLayer holds for you, bind a saved connection: { name: 'crm', host: 'api.crm.example.com', connection: 'my-crm', methods: ['GET', 'POST'] }. Your code then calls http://crm.keys.vl/.... VoiceLayer adds the credential and allows only that host and those methods. Your code never holds the key.
  • With no declaredEndpoints, the room can reach VoiceLayer and nothing else.

Sleep and always on

By default a hosted agent sleeps after 30 minutes with no call, text, request or schedule run. A sleeping agent has no room running and is not billed for one. The next call, message or request wakes it. The first answer after a sleep takes a few seconds longer, and VoiceLayer waits up to about 10 seconds for the room.

You can change this:

  • Sleep time. Choose 5 minutes to 7 days on the agent's Hosting page, or send sleepAfterIdleMinutes to PUT /v1/agents/{id}/hosting.
  • Always on. The rooms stay up every hour, and you pay the room's hourly price for each, around the clock. Turn it on from the Hosting page or with POST /v1/agents/{id}/hosting/always-on, which is the only way to turn it on, so you see the price first. Your plan limits how many always-on rooms you can have. When the limit is used up the request is refused with always_on_full, and the refusal is recorded on the agent.
  • Size and rooms. sizeClass is small, medium or large. warmCount is how many rooms to keep ready for each version that takes traffic. maxInFlight lowers the number of calls one room takes at once. A setting your plan does not allow is refused and names the limit.

Anything that wakes an agent also keeps it awake: calls, texts, requests to its endpoints, schedule runs and a new publish.

Bring an image in any language

The room does not care what language your process is written in. It cares that your process answers a small HTTP contract on $PORT:

RouteWhat it is
GET /healthzReady when it answers 200
POST /v1/tools/{name}Run a tool
POST /v1/hooks/{handler}An awaited hook, such as process.onComplete
POST /v1/events/{handler}A notification, delivered at least once: dedupe by x-vl-scope
POST /v1/calls/start, POST /v1/calls/endA call starts, a call ends
POST /v1/brain, POST /v1/brain/cancelA brain turn, in the OpenAI chat-completions streaming shape
POST /v1/actions on $VL_SHIM_PORTYou act on a call or request, under the scope you were handed

Published endpoint requests arrive on $PUBLIC_PORT at the caller's path, with x-vl-caller, x-vl-endpoint and x-vl-scope set.

To publish such an image:

Describe the agent in TypeScript

deploy reads the agent's prompt, tools and endpoints from a defineAgent file, and publishes that manifest with your image. The file does not have to contain the tool code. The tools you declare must be the ones your image serves, and image test checks that they are. The CLI is a Node program, so this step needs Node even if the image does not.

Build and test the image

docker build --platform linux/amd64 -t my-agent .
npx voicelayer image test my-agent ./agent.ts

Push it to VoiceLayer's registry

Images enter only through VoiceLayer's own registry, registry.vlayers.ai/<workspace>/<agent>. POST /v1/hosting/registry-credentials with { "agentId": "…" } returns a registry, repository, username and password that last an hour and open that one repository. The password is shown once. Push in chunks: a layer over 100 MB is refused by a plain docker push.

Submit it by digest

npx voicelayer deploy ./agent.ts --env prd --image sha256:<digest>

--image implies --hosted. It takes the sha256: digest, or registry.vlayers.ai/<workspace>/<agent>@sha256:<digest>. A tag such as :latest is refused, because a tag can move and what you published must be exactly what runs. One --image names one agent.

Test it

  1. npx voicelayer rooms shows a room in state ready for your version.
  2. Call the agent in the Playground, or hit your endpoint:
curl -X POST "https://run.vlayers.ai/<id>/api/notes" \
  -H "Authorization: Bearer vle_..." \
  -H "content-type: application/json" \
  -d '{"id":"n1","orderId":"A-1001","text":"hello"}'
  1. npx voicelayer logs <roomId> --grep "notes saved" shows what the room printed.

Common errors

ProblemFix
docker is not available or the image does not buildStart Docker. The default Dockerfile needs @voicelayer/sdk in dependencies.
The version fails with a readiness errorThe process did not answer GET /healthz on $PORT. Read the room log tail printed with the failure.
… is a tagUse the sha256: digest that the push printed.
A request to your endpoint answers 404 no_endpoint_handlerPass onRequest to agent.start({ room: { onRequest } }) or serveRoom.
collection_not_declaredAdd the collection to store and publish a new version.
field_not_indexedMark the field indexed: true in store, then publish again.
A call to a host is refusedAdd the host to declaredEndpoints.
always_on_fullYour plan's always-on rooms are used up. Free one or ask your admin to raise the limit.
voicelayer logs says the key needs room_logs:readAdd the scope to the key on the Access page, or use a key with full access.

Next steps

On this page