# Custom channels

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

Source: https://docs.vlayers.ai/developers/sdks/reference/channels

Kind: Reference

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

Import from `@voicelayer/sdk/channel`. For a walk-through, see [Build your own channel](https://docs.vlayers.ai/developers/sdks/custom-channels).

### defineChannel

function · `import { defineChannel } from '@voicelayer/sdk/channel'`

```ts
defineChannel(config: ChannelConfig): ChannelHandle
```

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

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `config` | `ChannelConfig` | yes | The channel's name, inbound webhook, sends, optional actions and schedules, and `onEvent`. |

##### Returns

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

##### Throws

- ChannelDefinitionError when the name is invalid, `onEvent` is missing, an action is malformed or a field that is not available yet is set.

##### Example

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

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

### ChannelConfig

interface · `import { ChannelConfig } from '@voicelayer/sdk/channel'`

```ts
interface ChannelConfig
```

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

#### Fields

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

### ChannelHandle

interface · `import { ChannelHandle } from '@voicelayer/sdk/channel'`

```ts
interface ChannelHandle
```

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

#### Fields

| Name | Type | Required | Description |
|---|---|---|---|
| `name` | `string` | yes | The connector's name. |
| `config` | `ChannelConfig` | yes | The config you passed to `defineChannel`. |

#### manifest

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

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

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `connectorId` | `string` | yes | The connector's id, `ws/<workspace>/<name>`. |

##### Returns

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

#### parse

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

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

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `events` | `readonly ChannelRawEvent[]` | yes | The raw events, as stored by the platform. |

##### Returns

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

#### runAction

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

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

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `request` | `ChannelActionRequest` | yes | Which action and phase, with its input and settings. |
| `io` | `ChannelActionIo` | yes | The provider call and the connection's store. |

##### Returns

`Promise<unknown>`: The action's result.

##### Throws

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

### ChannelEventContext

interface · `import { ChannelEventContext } from '@voicelayer/sdk/channel'`

```ts
interface ChannelEventContext
```

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

#### json

```ts
json(raw: ChannelRawEvent): any
```

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

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `raw` | `ChannelRawEvent` | yes | The raw event. |

##### Returns

`any`: The parsed body.

#### peer

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

Name a person on the channel.

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `kind` | `string` | yes | An identifier kind of the platform vocabulary, such as `telegram_user` or `phone`. |
| `address` | `string \| number` | yes | The person's address on the channel. |
| `displayName` | `string` | no | The person's name, when the provider gives it. |

##### Returns

`ChannelPeer`

##### Throws

- ChannelDefinitionError when `kind` is not an identifier kind.

#### deliver

```ts
deliver(message: DeliverInput): ChannelOutcome
```

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

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `message` | `DeliverInput` | yes | The message. |

##### Returns

`ChannelOutcome`

#### ignore

```ts
ignore(reason: string): ChannelOutcome
```

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

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `reason` | `string` | yes | Why nothing was done. |

##### Returns

`ChannelOutcome`

### ChannelPeer

interface · `import { ChannelPeer } from '@voicelayer/sdk/channel'`

```ts
interface ChannelPeer
```

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

#### Fields

| Name | Type | Required | Description |
|---|---|---|---|
| `kind` | `string` | yes | The identifier kind, from the platform's vocabulary: `telegram_user`, `phone` and so on. |
| `address` | `string` | yes | The person's address on the channel, such as a chat id or phone number. |
| `displayName` | `string` | no | The person's name, when the provider gives it. |

### DeliverInput

interface · `import { DeliverInput } from '@voicelayer/sdk/channel'`

```ts
interface DeliverInput
```

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

#### Fields

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | `string` | yes | The provider's id of this message; the building prefixes it and dedupes on it. |
| `conversation` | `string` | yes | Which conversation it belongs to (a chat id, a thread id): messages with one key are one conversation. |
| `from` | `ChannelPeer` | yes | Who wrote it: `ctx.peer(kind, address)`. |
| `text` | `string` | no | The message text. |
| `media` | `object[]` | no | Attachments, each a locator the platform can fetch and an optional format. |
| `media.locator` | `string` | yes | Where the attachment can be fetched. |
| `media.format` | `string` | no | The attachment's format, such as `image/png`. |
| `replyTo` | `string` | no | The provider's id of the message this answers. |
| `thread` | `string` | no | The provider's thread id, when the message belongs to a thread. |
| `at` | `number` | no | When the provider says it was written, epoch ms. |
| `context` | `string` | no | The owner's note for this event: stored with the message and shown to the agent as labelled input (never in the sealed prompt). At most 2000 characters. |

### ChannelOutcome

type · `import { ChannelOutcome } from '@voicelayer/sdk/channel'`

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

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

### ChannelIssue

interface · `import { ChannelIssue } from '@voicelayer/sdk/channel'`

```ts
interface ChannelIssue
```

A problem found in a channel's declaration.

#### Fields

| Name | Type | Required | Description |
|---|---|---|---|
| `path` | `string` | yes | Where in the declaration. |
| `message` | `string` | yes | What is wrong. |

### sendAction

function · `import { sendAction } from '@voicelayer/sdk/channel'`

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

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

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `a` | `SendAction<I, S>` | yes | The action. |

##### Returns

`SendAction<I, S>`: The same action.

##### Example

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

### SendAction

interface · `import { SendAction } from '@voicelayer/sdk/channel'`

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

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

#### Fields

| Name | Type | Required | Default | Description |
|---|---|---|---|---|
| `forAgent` | `boolean` | no | `false` | Offer the action to the agent as a tool. |
| `describe` | `string` | yes |  | What the action does. It becomes the tool's description for an agent action. |
| `sends` | `number` | no | `1` | How many messages one run sends, for metering. |
| `input` | `I` | no |  | The inputs the caller passes, by name and type (`text`, `string`, `url`, `number` or `boolean`). |
| `slots` | `S` | no |  | Typed identifiers `prepare` fills, such as `{ mediaId: 'digits' }`. Each sits as the whole value of a body field or path segment in `send`. |
| `send` | `import('@voicelayer/contracts').SendRequestTemplate` | yes |  | The request template, as for `sends`. It must hold `{{text}}`. |
| `address` | `'peer' \| 'answered'` | no |  | Shorthand for `send.address`: `peer` addresses the person, `answered` addresses the message being answered. |

#### prepare

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

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

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `input` | `InputValues<I>` | yes | The action's validated input. |
| `ctx` | `ChannelActionContext<I>` | yes | The action context. |

##### Returns

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

### codeAction

function · `import { codeAction } from '@voicelayer/sdk/channel'`

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

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

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `a` | `CodeAction<I>` | yes | The action. |

##### Returns

`CodeAction<I>`: The same action.

##### Example

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

### CodeAction

interface · `import { CodeAction } from '@voicelayer/sdk/channel'`

```ts
interface CodeAction<I extends InputShape = InputShape>
```

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

#### Fields

| Name | Type | Required | Default | Description |
|---|---|---|---|---|
| `forAgent` | `boolean` | no | `false` | Offer the action to the agent as a tool. |
| `describe` | `string` | no |  | What the action does. Required for an agent action: it becomes the tool's description. |
| `input` | `I` | no |  | The inputs the caller passes, by name and type (`text`, `string`, `url`, `number` or `boolean`). |
| `access` | `'read' \| 'write'` | no | `'write' for an agent action, otherwise 'read'` | Whether the action only reads or may change things at the provider. |

#### run

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

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

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `input` | `InputValues<I>` | yes | The action's validated input. |
| `ctx` | `ChannelActionContext<I>` | yes | The action context. |

##### Returns

`unknown`

### ChannelActionContext

interface · `import { ChannelActionContext } from '@voicelayer/sdk/channel'`

```ts
interface ChannelActionContext<I extends InputShape = InputShape>
```

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

#### Fields

| Name | Type | Required | Description |
|---|---|---|---|
| `input` | `InputValues<I>` | yes | The values of the action's declared inputs. |
| `settings` | `Readonly<Record<string, any>>` | yes | The connection's saved settings. |
| `store` | `ChannelStore` | yes | The connection's store. |

#### fetch

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

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

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `path` | `string` | yes | The call's path. |
| `init` | `ChannelFetchInit` | no | Method, JSON body and query. |

##### Returns

`Promise<any>`

##### Throws

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

#### deliver

```ts
deliver(message: DeliverInput): ChannelOutcome
```

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

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `message` | `DeliverInput` | yes | The message. |

##### Returns

`ChannelOutcome`

#### peer

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

Name a person on the channel.

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `kind` | `string` | yes | An identifier kind of the platform vocabulary. |
| `address` | `string \| number` | yes | The person's address on the channel. |
| `displayName` | `string` | no | The person's name, when the provider gives it. |

##### Returns

`ChannelPeer`

#### ignore

```ts
ignore(reason: string): ChannelOutcome
```

Say there is nothing to do.

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `reason` | `string` | yes | Why nothing was done. |

##### Returns

`ChannelOutcome`

### ChannelActionRequest

interface · `import { ChannelActionRequest } from '@voicelayer/sdk/channel'`

```ts
interface ChannelActionRequest
```

One action invocation as the room receives it.

#### Fields

| Name | Type | Required | Description |
|---|---|---|---|
| `phase` | `ChannelActionPhase` | yes | Which step is running. One of `schedule`, `prepare`, `run`, `control`. |
| `action` | `string` | yes | The action's name. |
| `input` | `Readonly<Record<string, unknown>>` | no | The input the caller passed. |
| `settings` | `Readonly<Record<string, unknown>>` | no | The connection's saved settings. |

### ChannelActionIo

interface · `import { ChannelActionIo } from '@voicelayer/sdk/channel'`

```ts
interface ChannelActionIo
```

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

#### Fields

| Name | Type | Required | Description |
|---|---|---|---|
| `fetch` | `(path: string, init?: ChannelFetchInit) => Promise<any>` | yes | Call the provider's declared API. |
| `store` | `ChannelStore` | yes | The connection's store. Used only when the channel declares `store: true`. |

### ChannelFetchInit

interface · `import { ChannelFetchInit } from '@voicelayer/sdk/channel'`

```ts
interface ChannelFetchInit
```

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

#### Fields

| Name | Type | Required | Default | Description |
|---|---|---|---|---|
| `method` | `'GET' \| 'HEAD' \| 'POST' \| 'PUT' \| 'PATCH' \| 'DELETE'` | no | `'POST' when 'json' is given, else 'GET'` | The HTTP method. The call must be one the declaration's `api.calls` lists. |
| `json` | `unknown` | no |  | A JSON request body. |
| `query` | `Readonly<Record<string, string \| number \| boolean \| undefined>>` | no |  | Query parameters. Keys must be declared on the call; `undefined` values are dropped. |

### ChannelStore

interface · `import { ChannelStore } from '@voicelayer/sdk/channel'`

```ts
interface ChannelStore
```

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

#### get

```ts
get(key: string): Promise<unknown>
```

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

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `key` | `string` | yes | The key to read. |

##### Returns

`Promise<unknown>`

#### put

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

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

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `key` | `string` | yes | The key to write. |
| `value` | `unknown` | yes | Any JSON value. |

##### Returns

`Promise<void>`

#### delete

```ts
delete(key: string): Promise<void>
```

Remove the value under `key`.

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `key` | `string` | yes | The key to remove. |

##### Returns

`Promise<void>`

#### list

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

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

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `prefix` | `string` | no | Only keys that start with this. |

##### Returns

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

### memoryStore

function · `import { memoryStore } from '@voicelayer/sdk/channel'`

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

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

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `initial` | `Readonly<Record<string, unknown>>` | no | Entries to start with. |

##### Returns

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

### serveChannel

function · `import { serveChannel } from '@voicelayer/sdk/channel'`

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

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

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `handle` | `ChannelHandle` | yes | The channel from `defineChannel`. |
| `opts` | `ServeChannelOptions` | no | Port, logging and shutdown behaviour. |

##### Returns

`Promise<ChannelServer>`: The running server.

##### Example

```ts
await serveChannel(channel);
```

### ServeChannelOptions

interface · `import { ServeChannelOptions } from '@voicelayer/sdk/channel'`

```ts
interface ServeChannelOptions
```

Options for serving a channel in its room.

#### Fields

| Name | Type | Required | Default | Description |
|---|---|---|---|---|
| `port` | `number` | no | `'$PORT'` | The port to listen on. |
| `host` | `string` | no |  | The address to listen on. |
| `log` | `RunnerLogger` | no |  | Where the server writes its log lines: an object with `debug`, `info`, `warn` and `error` functions. |
| `signals` | `boolean` | no | `true` | Install SIGTERM and SIGINT handlers and exit when stopped by one. |
| `env` | `Readonly<Record<string, string \| undefined>>` | no | `process.env` | The environment to read ports and the key proxy address from. |
| `transport` | `ActionTransport` | no | `the key proxy at '$VL_KEYS_URL' ('http://api.keys.vl')` | How `ctx.fetch` reaches the provider and `ctx.store` the platform's store. |

### ChannelServer

interface · `import { ChannelServer } from '@voicelayer/sdk/channel'`

```ts
interface ChannelServer
```

A running channel server.

#### Fields

| Name | Type | Required | Description |
|---|---|---|---|
| `port` | `number` | yes | The port it listens on. |
| `done` | `Promise<void>` | yes | Resolves when the server has stopped. |

#### stop

```ts
stop(): Promise<void>
```

Stop accepting requests and finish those running.

##### Returns

`Promise<void>`

### ChannelDefinitionError

class · `import { ChannelDefinitionError } from '@voicelayer/sdk/channel'`

```ts
class ChannelDefinitionError extends Error
```

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

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

### ChannelActionError

class · `import { ChannelActionError } from '@voicelayer/sdk/channel'`

```ts
class ChannelActionError extends Error
```

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

```ts
new ChannelActionError(code: ChannelActionErrorCode, message: string)
```

#### Fields

| Name | Type | Required | Description |
|---|---|---|---|
| `code` | `ChannelActionErrorCode` | yes | Why the action was refused. One of `unknown_action`, `wrong_phase`, `bad_input`, `slot_invalid`, `not_available`, `bad_result`, `handler_error`. |

### ChannelFetchError

class · `import { ChannelFetchError } from '@voicelayer/sdk/channel'`

```ts
class ChannelFetchError extends Error
```

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

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

#### Fields

| Name | Type | Required | Description |
|---|---|---|---|
| `status` | `number` | yes | The HTTP status. |
| `body` | `unknown` | yes | The provider's parsed answer. |
