# Build your own channel

> Connect a provider VoiceLayer does not support yet by declaring how its webhook is verified and how replies are sent, with one function that turns an event into a message.

Source: https://docs.vlayers.ai/developers/sdks/custom-channels

Kind: How-to guide

## What you'll build

A channel connector for a provider of your own, written with `@voicelayer/sdk/channel`. VoiceLayer does the work that must be the platform's: it verifies the provider's webhook, answers it, drops duplicates, stores the raw event, applies opt-out and the output guard, and sends your replies. You write the part only you know: how one stored event becomes a message for the agent, and, if you need them, actions and a poll.

The channel holds no credential. You enter the provider's token in the dashboard when you connect the channel (Step 5), and it is kept in your workspace's vault. When a send or `ctx.fetch` goes out, VoiceLayer adds the token to the request. Your code never sees it, and a call to an address you did not declare in `api` or `hosts` is refused. By default the token is sent as `Authorization: Bearer <token>`. A provider that needs it in the URL path or a query parameter needs a placement that only the API sets today.

## Prerequisites

- Node.js 22 or later and Docker. Deploy builds your channel into an image.
- A secret API key in `VOICELAYER_API_KEY` with the `workspace:write` scope (a full-access key has it). `channel deploy` creates the connector and publishes with it. A worker key (`vlw_…`) is refused. A test key or a live key both work for this. A connector belongs to your workspace, not to dev, stg or prd.
- `@voicelayer/sdk` in your project's `dependencies`.
- The provider's webhook secret or token, and its API token if your channel calls it.

```bash
npm install @voicelayer/sdk
```

## How a channel works

1. The provider POSTs a webhook to VoiceLayer.
2. VoiceLayer checks the signature, answers the provider, drops a duplicate by the id you declared, and stores the raw event.
3. Your `onEvent` runs in a room and returns `ctx.deliver(...)` (a message for the agent) or `ctx.ignore(reason)`. `ctx.deliver` is not async, so do not `await` it. In `onEvent`, return what it gives you. In a schedule, just call it.
4. When the agent answers, VoiceLayer fills your `sends` template and sends it to the provider.

`channel` names a channel the platform already has: `email`, `sms`, `whatsapp`, `telegram`, `discord` and the like. A new kind of channel is not offered yet. Pick the one whose people and rules match yours: `email` for people known by email address, `sms` or `whatsapp` for phone numbers, `telegram` or `discord` for those apps' users. The channel decides how a person is identified (`ctx.peer`), and the opt-out, pacing and output checks applied to replies.

## Step 1: Define the channel

Start from `npx @voicelayer/sdk init my-channel --template channel`: it writes a minimal channel, a test and the `package.json`.

This is `examples/telegram-channel.ts` in the repository. It connects a Telegram bot for private chats.

```ts
// telegram-channel.ts
import { defineChannel } from '@voicelayer/sdk/channel';

export default defineChannel({
  name: 'my-telegram',
  label: 'My Telegram bot',
  channel: 'telegram',
  hosts: ['api.telegram.org'],
  inbound: {
    webhook: {
      verify: { scheme: 'secret_token_header', header: 'x-telegram-bot-api-secret-token' },
      events: [{ kind: 'message', id: { from: 'json', path: 'update_id' }, lane: 'message.chat.id' }],
      ack: { type: 'fixed', status: 200, contentType: 'text/plain', body: 'ok' },
    },
  },
  sends: {
    'reply.in_window': {
      method: 'POST',
      path: '/sendMessage',
      body: { kind: 'json', template: { chat_id: '{{target}}', text: '{{text}}' } },
      recipients: ['body.chat_id'],
      messageId: '$.result.message_id',
    },
  },
  onEvent(raw, ctx) {
    const update = ctx.json(raw) as { update_id: number; message?: { text?: string; chat: { id: number; type: string }; from: { id: number; username?: string } } };
    const m = update.message;
    if (!m?.text || m.chat.type !== 'private') return ctx.ignore('not a private text message');
    return ctx.deliver({
      id: String(update.update_id),
      conversation: String(m.chat.id),
      from: ctx.peer('telegram_user', m.from.id, m.from.username),
      text: m.text,
    });
  },
});
```

What each field does:

| Field | Meaning |
|---|---|
| `name` | The connector's name: lowercase letters, digits and `-`, starting with a letter, up to 40 characters. Its id is `ws/<workspace>/<name>`. |
| `label` | The name people see. |
| `channel` | The platform channel this connector narrows. |
| `hosts` | The provider hosts your `sends` may reach. If you declare `api`, its `host` is added for you, so list only extra hosts. A channel with `sends` or send actions needs at least one host, from `hosts` or `api.host`. |
| `inbound.webhook.verify` | How the provider proves a delivery is real. One of `slack_v0`, `meta_hmac_sha256`, `twilio_hmac_sha1`, `ed25519` (with `signatureHeader`, `timestampHeader`) and `secret_token_header` (with `header`). There is no "no verification". The secret itself is kept in the vault, never in your code. |
| `inbound.webhook.events` | Per event kind: where its provider id is (`id: { from: 'json', path }` or `{ from: 'header', name }`), `items` if one delivery holds a batch (`entry[*].changes[*]`), and `lane`, the field that orders events of one conversation. |
| `inbound.webhook.ack` | What the provider is answered. A fixed 2xx body, an echoed query value or body field. |
| `inbound.webhook.handshakes` | Requests VoiceLayer answers itself, for example Meta's `hub.challenge`. |
| `sends` | The default reply as a request template, by operation: `send.text`, `reply.in_window`, `send.media`. Slots are `{{target}}`, `{{text}}`, `{{replyTo}}` and `{{media.url}}`. VoiceLayer fills and sends it. `recipients` names the fields that hold the recipient. |
| `onEvent(raw, ctx)` | The only code on the inbound path. |

### Slots, paths and references

Three small syntaxes appear in the declaration. They are different on purpose.

- **Slots in a send template** are filled by VoiceLayer: `{{target}}` is the person you are sending to (the `address` you gave `ctx.peer`, such as a chat id), `{{replyTo}}` is the id of the message being answered (the `id` you delivered), `{{text}}` is the reply, already checked by the guard, and `{{media.url}}` is a media address. `reply.in_window` must carry `{{target}}`, `{{text}}` and `{{replyTo}}`; `send.text` needs `{{target}}` and `{{text}}`. `{{target}}` and `{{replyTo}}` may fill a whole path segment, a query value, or a value in the JSON or form body. `{{text}}` and `{{media.url}}` go in the body only. A slot never goes in a header or a key. With `address: 'answered'` the recipient is `{{replyTo}}` instead of `{{target}}`.
- **`recipients`** names the field or fields that hold the recipient, by reference: `'path'` (a path segment), `'query.<name>'`, `'form.<name>'` or `'body.<a>.<b>'` (a dotted path into the JSON body). Each named field must hold exactly the recipient slot.
- **`messageId`** is a JSONPath into the provider's answer that reads the sent message's id: `$.id`, `$.result.message_id`, `$.items[0].id`. Nothing else of the answer is read.
- **Event `id`, `lane` and `items`** are dotted paths into the delivery's JSON, without the `$`: `update_id`, `value.id`, `entry[*].changes[*]`.
- **`api.calls`** are `METHOD /path` strings with typed segments, `{id:digits}`, `{x:slug}` or `{x:uuid}`.

An event `kind` is a name you choose for one kind of delivery (lowercase letters, digits and `_`). `testChannel` uses the first one you declared unless you pass `kind`.

`ctx` in `onEvent` has `json(raw)`, `peer(kind, address, displayName?)`, `deliver({...})` and `ignore(reason)`. `deliver` takes `id`, `conversation`, `from`, `text`, and optionally `media`, `replyTo`, `thread`, `at` and `context` (a note to the agent, up to 2000 characters). `peer` kinds come from the platform's identifier list (`telegram_user`, `discord_user`, `email`, `phone`, `external_user` and others).

`onEvent` has no network, no credential and no `ctx.store`. A throw becomes a recorded mapping failure for that one event, never a failure of the batch. An `ignore` reason is kept on the connection's record (200 characters; do not put a person's words in it).

## Step 2: Check it

```bash
npx voicelayer channel manifest ./telegram-channel.ts
```

This builds the manifest and checks it with the same rules the API applies at publish. Add `--json` to print it.

## Step 3: Test it with no network

`testChannel` is in `@voicelayer/sdk/testing`. See [Testing agents and channels](https://docs.vlayers.ai/developers/sdks/testing) for the full file.

```ts
import { testChannel } from '@voicelayer/sdk/testing';
import channel from './telegram-channel.js';

const t = testChannel(channel);
console.log(t.manifest().issues); // []
const [result] = await t.parse({ body: { update_id: 1, message: { text: 'hi', chat: { id: 7, type: 'private' }, from: { id: 7 } } } });
console.log(result); // { outcome: 'event', ... }
```

## Step 4: Deploy

```bash
npx voicelayer channel deploy ./telegram-channel.ts
```

This creates the connector, builds your project into an image with Docker, pushes it to VoiceLayer's own registry with a short-lived credential it mints for you, submits a version and waits for its room. You do not log in to a registry or push by hand. `--image <digest>` submits an image you built, `--note` adds a note, `--timeout <seconds>` changes the wait (600 by default). There is no `--env`: a connector belongs to your workspace, not to dev, stg or prd. When it finishes it prints that the version is published and its room is registered; then connect the provider's credentials in the dashboard (Step 5). A channel has no agent and no lock file: the API keeps its versions. Like a hosted agent, it uses your own `Dockerfile` if the project has one, and otherwise generates one that runs `voicelayer channel serve`. To run the channel's server yourself, for example inside your own image, use `voicelayer channel serve <entry> [--port <n>]`.

## Step 5: Connect it and register the webhook

In the dashboard, open **Channels**, then the **Custom** tab, then **Connect a channel you wrote**. Choose your channel, name the connection and enter the secrets it asks for: the webhook signing secret (or token), and the account key or token if your channel calls the provider. Assign the agent that answers.

The connection then shows **Give your provider this address**. Copy it. You register it with the provider yourself, with the same secret you entered. For Telegram:

```bash
curl "https://api.telegram.org/bot<BOT_TOKEN>/setWebhook" \
  --data-urlencode "url=<the address>" \
  --data-urlencode "secret_token=<the secret you entered>"
```

The address contains `%2F`, so send it with `--data-urlencode`. A provider that needs its token in the URL path, as Telegram's sends do, needs a credential placement that only the API sets today.

## Actions: what the agent can do besides reply

`actions` are named operations. Mark one `forAgent: true` and the agent gets it as a tool. Without `forAgent`, it is a read-only control for the dashboard. There are two kinds.

- **A send action** reaches a person. You give a request template, and VoiceLayer fills and sends it after its checks (opt-out, output guard, pacing). It may have a `prepare(input, ctx)` that runs first and returns typed `slots`, ids and never words: `digits`, `uuid` or `hex`. A slot that does not match its kind fails the action with `slot_invalid`. `address: 'answered'` addresses the message being answered (`{{replyTo}}`), for example a reply to a comment.
- **A code action** reaches no one in particular, for example posting to the account or closing a ticket. It has `run(input, ctx)`. `describe` is required for an agent action: it becomes the tool's description. `access` is optional. It defaults to `write` for an agent action and `read` for a control, and a control cannot be `write`.

Helpers `sendAction({...})` and `codeAction({...})` keep `input` typed. `input` types are `text` (words, checked by the guard before your code sees them), `string`, `url`, `number` and `boolean`.

Action code gets `ctx.input`, `ctx.settings`, `ctx.fetch(path, { method, json, query })`, `ctx.store`, and `ctx.deliver`/`ctx.peer`/`ctx.ignore`. `ctx.fetch` reaches only the calls you declare, on the declared host with the connection's token added for you:

```ts
api: { host: 'api.helpdesk.example.com', calls: [{ call: 'GET /api/tickets', query: ['since', 'limit'] }, 'POST /api/tickets/{id:digits}/close'] }
```

A path segment is a literal or a typed placeholder (`{id:digits}`, `{x:slug}`, `{x:uuid}`). A bare `{x}` is refused. Query keys are declared per call. A non-2xx answer throws `ChannelFetchError` with `status` and `body`.

## State and polling

Set `store: true` and action code and schedules get `ctx.store`, kept by the platform for one connection:

| Call | Result |
|---|---|
| `get(key)` | The value, or `undefined` |
| `put(key, value)` | Saves any JSON value, replacing what was there |
| `delete(key)` | Removes it |
| `list(prefix?)` | Entries whose key starts with `prefix`, by key, at most 200 |

A key is 1 to 200 characters: letters, digits and `. _ : / @ + = -`, starting with a letter or digit. A bad key, a value over your plan's size or too many keys fail with the reason named. `ctx.store` is there only when you set `store: true`. Without it, every call to `ctx.store` fails with `not_available`. `onEvent` never has a store.

`schedules: [{ name, everySeconds }]` with `onSchedule(name, ctx)` polls on a timetable. `name` is lowercase letters, digits and `_`. `everySeconds` is 60 to 86400. A schedule is read-only: `ctx.fetch` reaches your declared GETs, `ctx.store` keeps the cursor, and what you give to `ctx.deliver` is recorded as a message (the same message twice is recorded once). It cannot send. A run delivers at most 100 messages, so keep your cursor at the last one delivered. It runs for a connection an agent answers, and only while the workspace can pay.

Here is a complete channel with a webhook, a send action, a code action and a poll. Save it as `custom-channel.ts`.

```ts
// custom-channel.ts
import { codeAction, defineChannel, sendAction } from '@voicelayer/sdk/channel';

type Ticket = { id: number; subject: string; body: string; requester: { email: string; name?: string } };

export default defineChannel({
  name: 'helpdesk',
  label: 'Help desk',
  channel: 'email',
  api: {
    host: 'api.helpdesk.example.com',
    calls: [{ call: 'GET /api/tickets', query: ['since', 'limit'] }, 'POST /api/tickets/{id:digits}/close']
  },
  store: true,
  inbound: {
    webhook: {
      verify: { scheme: 'secret_token_header', header: 'x-helpdesk-token' },
      events: [{ kind: 'ticket', id: { from: 'json', path: 'ticket.id' }, lane: 'ticket.id' }],
      ack: { type: 'fixed', status: 200, contentType: 'text/plain', body: 'ok' }
    }
  },
  sends: {
    'reply.in_window': {
      method: 'POST',
      path: '/api/tickets/{{replyTo}}/replies',
      body: { kind: 'json', template: { body: '{{text}}' } },
      recipients: ['path'],
      address: 'answered',
      messageId: '$.id'
    }
  },
  actions: {
    sendInternalNote: sendAction({
      forAgent: true,
      describe: 'Add a private note to the ticket the person wrote about',
      send: {
        method: 'POST',
        path: '/api/tickets/{{replyTo}}/notes',
        body: { kind: 'json', template: { body: '{{text}}', private: true } },
        recipients: ['path'],
        address: 'answered',
        messageId: '$.id'
      }
    }),
    closeTicket: codeAction({
      forAgent: true,
      describe: 'Close a ticket by its number',
      input: { ticketId: 'number' },
      run: async ({ ticketId }, ctx) => {
        await ctx.fetch(`/api/tickets/${ticketId}/close`, { method: 'POST', json: {} });
        return { closed: ticketId };
      }
    })
  },
  schedules: [{ name: 'catch_up', everySeconds: 300 }],
  async onSchedule(_name, ctx) {
    const since = (await ctx.store.get('cursor')) as number | undefined;
    const page = (await ctx.fetch('/api/tickets', { query: { since: since ?? 0, limit: 25 } })) as { tickets?: Ticket[] };
    let last = since ?? 0;
    for (const t of page.tickets ?? []) {
      ctx.deliver({ id: String(t.id), conversation: String(t.id), from: ctx.peer('email', t.requester.email, t.requester.name), text: `${t.subject}\n\n${t.body}` });
      last = Math.max(last, t.id);
    }
    if (last !== since) await ctx.store.put('cursor', last);
  },
  onEvent(raw, ctx) {
    const { ticket } = ctx.json(raw) as { ticket?: Ticket & { status?: string } };
    if (!ticket || ticket.status === 'closed') return ctx.ignore('closed or empty ticket');
    return ctx.deliver({
      id: String(ticket.id),
      conversation: String(ticket.id),
      from: ctx.peer('email', ticket.requester.email, ticket.requester.name),
      text: `${ticket.subject}\n\n${ticket.body}`,
      context: 'This message came from the help desk. Keep replies under 500 characters.'
    });
  }
});
```

In this example the reply goes to a ticket, so the send uses `address: 'answered'`: the path holds `{{replyTo}}`, which is the `id` you gave `ctx.deliver` for the message being answered (here the ticket number). `{{target}}`, the person's address (the email from `ctx.peer`), is for a provider that addresses the reply to the person. Do not put an email address in a path. If the answered message has no `replyTo`, for example when the agent writes first, the send fails with `slot_missing` and nothing is sent. Use `send.text` with `{{target}}` for that case.

Run `npx voicelayer channel manifest ./custom-channel.ts`; it prints `manifest ok` with the counts. The provider's hosts, paths and fields here are made up: replace them with your provider's.

Not available yet, and refused with a sentence when you set them: `settings`, `controls`, `setup`, and `auth` (connect the provider's credentials in the dashboard instead). A per-event `agent` on `ctx.deliver` is not offered either.

## Test it

1. `npx voicelayer channel manifest ./channel.ts` ends with `manifest ok`. `testChannel` runs your `onEvent`, actions and schedules.
2. After deploy, the connector shows a published version and a registered room.
3. Send a test event to your provider, or POST one from the provider's console. The conversation appears under **Conversations**. If `onEvent` ignored it, the connection's record shows the reason.

`testChannel` cannot send headers or a signature: it passes only a body to `onEvent`. VoiceLayer verifies the signature before your code runs, so signature checking is not testable offline. To test it, send a real delivery from the provider, or POST one to the connection's address with the right header and secret, then look at the connection's record for a rejected delivery.

## Common errors

| Problem | Fix |
|---|---|
| `“settings” is not available yet` | Remove the field. It is refused, not ignored. |
| `a bare {x} is refused` | Type the placeholder: `{id:digits}`. |
| `a channel that declares sends names the provider host(s)` | Add `hosts`, or `api.host`. |
| `slot_invalid` | `prepare` must return only the declared slots, each an id of its declared kind. |
| `ctx.store needs store: true` | Add `store: true` to `defineChannel`. |
| The provider says the webhook failed | Check the secret you entered matches the one you gave the provider, and that the address was sent URL-encoded. |
| The message is delivered but nobody answers | Assign an agent to the connection. |

## Next steps

- [Testing agents and channels](https://docs.vlayers.ai/developers/sdks/testing)
- [Run your agent on VoiceLayer](https://docs.vlayers.ai/developers/sdks/hosting): the same room and image model, for agents.
- [Command line reference](https://docs.vlayers.ai/developers/sdks/cli)
- [Channel reference](https://docs.vlayers.ai/developers/sdks/reference/channels): `defineChannel`, actions and the store, with types.
