# Defining and starting an agent

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

Source: https://docs.vlayers.ai/developers/sdks/reference/define-agent

Kind: Reference

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

Import from `@voicelayer/sdk`. For a walk-through, see [Voice agents in code](https://docs.vlayers.ai/developers/sdks/voice-agents).

### defineAgent

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

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

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

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `config` | `AgentConfig<TProcess>` | yes | The agent: prompt, tools, models, process and the rest of `AgentConfig`. |

##### Returns

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

##### Example

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

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

await agent.start();
```

### AgentConfig

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

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

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

#### Fields

| Name | Type | Required | Default | Description |
|---|---|---|---|---|
| `name` | `string` | yes |  | The agent's name: lowercase letters, digits, `-` and `_`. With the deploy's environment it picks the agent's row in the dashboard. |
| `prompt` | `string` | yes |  | The system prompt the model follows. Calls use the version you deployed; editing it later applies to the next call only. |
| `greeting` | `string` | no |  | A fixed opening line, spoken straight away with no model call, so the caller does not wait. Absent: the model writes the greeting from the prompt. |
| `routingInstructions` | `string` | no |  | Plain-language guidance on when the agent should act, added below the prompt under a "Routing" heading. |
| `capabilities` | `readonly string[]` | no |  | Capability tags shown for the agent in the dashboard. |
| `version` | `string` | no |  | Your own version string, shown in the dashboard. It is a label, not what the platform pins a call to. |
| `process` | `ProcessDefinition<TProcess>` | no |  | The values the agent collects from the caller, and what happens when it has them. Build it with `defineProcess` to get typed `data` in `onComplete`. |
| `process.collect` | `T` | yes |  | The fields to capture, by name. |
| `process.completeWhen` | `CompletionStrategy` | no |  | The rule that decides when the process is complete. |
| `process.backendAck` | `ProcessBackendAck` | no |  | An endpoint the platform tells when the process completes. |
| `process.onComplete` | `(data: InferProcessData<T>, ctx: HandlerContext) => Promise<void> \| void` | no |  | Runs when the process completes, with the captured data. It has 5 seconds; it is awaited, errors are logged, and the process stays complete. |
| `process.onField` | `<K extends keyof T>(field: K, value: InferFieldValue<T[K]>, ctx: HandlerContext) => Promise<void> \| void` | no |  | Runs each time a field is captured, with the field name and value. It has 2 seconds; it is awaited, errors are logged, and the field stays captured. |
| `triggers` | `Readonly<Record<string, TriggerDefinition>>` | no |  | Rules that watch the conversation and act when a condition is met, by name. |
| `handoff` | `HandoffConfig` | no |  | Where and how the agent hands a call to a person. |
| `handoff.fallback` | `string` | yes |  | The destination used when no route matches. |
| `handoff.routes` | `Readonly<Record<string, string>>` | no |  | Named destinations the agent or a trigger can hand off to, by name, for example `{ billing: '+15551230000' }`. |
| `handoff.briefing` | `\| string \| ((args: { readonly data: Record<string, unknown>; readonly transcript: TranscriptHandle; readonly call: CallInfo }) => string \| Promise<string>)` | no |  | What the receiving person is told: fixed text, or a function of the captured data, the transcript and the call. A function has 2 seconds; when it is late the platform's own briefing is used. |
| `handoff.mode` | `'warm' \| 'cold'` | no |  | `warm` briefs the receiver before connecting the caller; `cold` connects straight away. |
| `handoff.headers` | `{ readonly context?: boolean; readonly reason?: boolean }` | no |  | SIP headers a contact centre reads on the transfer. `context` sends `User-to-User` with a reference (128 characters at most) to a read-only summary of the call; `reason` sends `X-VL-Reason` with the reason the platform's output guard let through. The names and shapes are fixed by the platform. Off unless you switch them on. |
| `memory` | `MemoryConfig` | no |  | How far the agent's memory reaches and how long it is kept. |
| `memory.scope` | `MemoryScope` | no |  | How far remembered values reach. One of `call`, `caller`, `participant`, `account`, `platform`. |
| `memory.retentionDays` | `number` | no |  | How many days remembered values are kept before they are deleted. |
| `memory.piiFields` | `readonly string[]` | no |  | Names of fields that hold personal details, kept tokenised. |
| `memory.platformOptIn` | `boolean` | no | `false` | Whether the agent takes part in platform-wide memory. |
| `participants` | `ParticipantsConfig` | no |  | Handlers for people joining and leaving the call, and a cap on how many may. |
| `participants.onJoin` | `(participant: Participant, ctx: HandlerContext) => Promise<void> \| void` | no |  | Runs when someone joins. A notification: delivered in call order, never waited on. |
| `participants.onLeave` | `(participant: Participant, ctx: HandlerContext) => Promise<void> \| void` | no |  | Runs when someone leaves. A notification: delivered in call order, never waited on. |
| `participants.attributes` | `(participant: Participant) => Readonly<Record<string, string>> \| Promise<Readonly<Record<string, string>>>` | no |  | Adds attributes to a participant as they join. It has 1 second; when it is late no attributes are added. |
| `participants.max` | `number` | no |  | The most participants the call allows. |
| `connectors` | `Readonly<Record<string, ConnectorInstance>>` | no |  | Connector objects for your own integration code, by key. They stay in your process. With `expose: true` each function becomes a tool the model can call. |
| `compliance` | `readonly ComplianceTag[]` | no |  | The compliance regimes the agent operates under. |
| `models` | `ModelsConfig` | no |  | Which models the agent uses for the language model, speech to text and text to speech. |
| `model` | `ModelDescriptor \| string \| ModelConfig` | no |  | The agent's language model in the AI SDK's words: shorthand for `models.llm`. Setting both is a build error. |
| `outbound` | `OutboundCallConfig` | no |  | How the agent behaves on calls it places, such as answering-machine detection. |
| `outbound.amd` | `'off' \| 'detect' \| 'detectMessageEnd'` | no | `'off'` | Answering-machine detection, judged from the words the callee says. `off` treats every answer as a person, `detect` acts the moment a machine greeting is recognised, `detectMessageEnd` waits for the greeting to finish first. Inbound calls never run it. |
| `outbound.voicemailScript` | `string` | no |  | What to say when a machine answers. Without it the agent hangs up when a machine is detected. |
| `speech` | `SpeechConfig` | no |  | How the agent sounds: pronunciations, background audio, interruptions and when a caller's turn ends. |
| `speech.pronunciations` | `Readonly<Record<string, string>>` | no |  | How to say particular words: a map from the written word to how it should be pronounced. |
| `speech.backgroundAudio` | `string \| { readonly url?: string; readonly volume?: number }` | no |  | A sound under the conversation: a URL, or `{ url, volume }`. |
| `speech.interruption` | `{ readonly enabled?: boolean; readonly minWords?: number; readonly minDuration?: number }` | no |  | How easily the caller can interrupt the agent: `enabled` (default true; false makes the agent uninterruptible), `minWords` the caller must say first (0 to 10, default 0) and `minDuration`, the milliseconds of speech that count (0 to 5000, default 500). |
| `speech.endpointing` | `{ readonly minDelay?: number; readonly maxDelay?: number }` | no |  | When the caller's turn is over: `minDelay`, the silence in milliseconds before it counts as done (0 to 5000, default 500), and `maxDelay`, the ceiling after which it ends regardless (0 to 15000, default 3000). |
| `endCall` | `EndCallPolicy` | no |  | When and how a call ends: teardown, silence and length limits and a hook that can take over. |
| `endCall.teardown` | `'room' \| 'agent'` | no | `'room'` | What to close when the call ends. `room` ends the whole call, including the phone leg, so the carrier sees a hangup; `agent` only removes the agent and leaves the other side connected, for when something else owns the call. |
| `endCall.guaranteeMs` | `number \| false` | no | `4000` | How long, in milliseconds, the platform keeps retrying teardown until the room is really gone, so a hangup that did not land is repeated. `false` tries once. |
| `endCall.idleHangupMs` | `number \| false` | no | `20000` | Hang up when the agent is waiting on the caller and the line has been silent this many milliseconds, so a stuck call does not run on. Never fires while the agent is speaking or a tool runs. `false` turns it off. |
| `endCall.maxCallDurationMs` | `number \| false` | no | `3600000` | Hang up once the call has run this many milliseconds, whatever else is happening. `false` turns off this default. The agent's own limit in the dashboard wins over it, and the workspace's plan ceiling caps every call either way. |
| `endCall.onEnd` | `(ctx: HandlerContext, info: EndCallInfo) => boolean \| { veto?: boolean } \| void \| Promise<boolean \| { veto?: boolean } \| void>` | no |  | Runs just before the call ends, for every cause. It has 2 seconds. Return `false` (or `{ veto: true }`) to take over teardown yourself; anything else, a throw or a late answer runs the default teardown. A hangup by the host cannot be vetoed. |
| `tools` | `Readonly<Record<string, ToolEntry>>` | no |  | Tools the model can call, by name. Each is a `defineTool` or `httpTool` result, an AI SDK tool, or a `ToolDefinition`. Spread several in with `...defineTool({...})`. |
| `toolBindings` | `readonly string[]` | no |  | Tools you created in the dashboard (HTTP tools) that this agent may use, by name. Absent or empty means none. |
| `actions` | `readonly (string \| ActionDeclaration)[]` | no |  | Catalog actions the agent offers, by tool name: VoiceLayer's own (`vl_book_meeting`, `vl_check_availability`, `vl_send_text`, `vl_send_email`) or a connected app's (`int_hubspot_contacts_create`). The list is sealed at publish like `tools`. What an action may do (the connection it uses, argument rules, limits, whether it sees real values) is set by an Admin in the dashboard, and each call runs through VoiceLayer's action door under the call's own credential, so your process never holds a provider credential. Absent: none. |
| `store` | `object` | no |  | The workspace store a hosted agent reads and writes: collections of JSON documents. Mark the fields you query by `indexed` and those that hold people's details `personal`; an indexed personal field is also `hashed`, so only a keyed hash of it is kept in the clear. The person sees the indexed and personal fields when they confirm a publish. Absent: no store. |
| `store.collections` | `readonly { /** The collection's name. */ readonly name: string; /** The fields the agent queries or flags; documents may hold other fields too. */ readonly fields?: readonly { /** The field's name. */ readonly name: string; /** The kind of value it holds. */ readonly type: 'string' \| 'number' \| 'boolean'; /** Whether the agent queries by this field. @default false */ readonly indexed?: boolean; /** Whether the field holds a person's details, which are protected in storage. @default false */ readonly personal?: boolean; /** Keep only a keyed hash of the value in the clear, so it can be matched but not read. Implied for an indexed personal field. */ readonly hashed?: boolean; }[]; }[]` | yes |  | The collections the agent may use. |
| `schedules` | `object[]` | no |  | Cron schedules for a hosted agent, in UTC and at most once a minute. Each calls the published endpoint of kind `schedule` named in `endpoint`, which must be declared in `endpoints`. Absent: none. |
| `schedules.name` | `string` | yes |  | The schedule's name. |
| `schedules.cron` | `string` | yes |  | A cron expression, in UTC, firing at most once a minute. |
| `schedules.endpoint` | `string` | yes |  | The name of the `schedule` endpoint in `endpoints` that each run calls. |
| `schedules.missed` | `'skip' \| 'run_once'` | no | `'skip'` | What to do with a run that fell due while the platform could not run it: `skip` drops it, `run_once` runs it once when it can. |
| `endpoints` | `object[]` | no |  | The addresses a hosted agent publishes at run.vlayers.ai (`api`, `hook`, `mcp` or `schedule`), who may call each (`auth`: a key, a signature or anyone) and what the handler may ask the platform for. Absent: none. |
| `endpoints.name` | `string` | yes |  | The endpoint's name, used in its address and by `schedules`. |
| `endpoints.kind` | `'api' \| 'hook' \| 'mcp' \| 'schedule'` | yes |  | What the endpoint is: an `api`, a `hook` (webhook receiver), an `mcp` server or a `schedule` target. |
| `endpoints.auth` | `Record<string, unknown>` | yes |  | Who may call it: a key, a signature or anyone. |
| `endpoints.capabilities` | `readonly string[]` | no |  | What the handler may ask the platform to do, such as `store.put` or `messages.send`. |
| `endpoints.realValues` | `readonly string[]` | no |  | The subset of `capabilities` that may return people's real details instead of placeholders; each release is recorded. |
| `endpoints.idleTimeoutMs` | `number` | no |  | For a streaming response, how long it may sit idle before it is closed, in milliseconds (1000 to 3600000). Absent: the platform default. |
| `publishedEndpoints` | `AgentConfig['endpoints']` | no |  | The manifest's own name for `endpoints`, accepted as an alias. Setting both is a build error. |
| `declaredEndpoints` | `object[]` | no |  | The hosts a hosted agent's process may call out to: `{ host: 'api.github.com' }`, or `{ name, host, connection, methods }` to call a host through a vault connection. Everything else the process tries to reach is refused by name. Absent: no outbound access. |
| `declaredEndpoints.name` | `string` | no |  | A name for the host, used by the connection. |
| `declaredEndpoints.host` | `string` | yes |  | The host the process may call, for example `api.github.com`. |
| `declaredEndpoints.connection` | `string` | no |  | A vault connection whose credential is added to calls to this host. |
| `declaredEndpoints.methods` | `readonly ('GET' \| 'POST' \| 'PUT' \| 'PATCH' \| 'DELETE')[]` | no |  | The HTTP methods allowed. |
| `guard` | `GuardConfig` | no |  | Flags replies that look wrong, such as too long or containing banned text. |
| `guard.maxLength` | `number` | no | `8000` | Flag a reply longer than this many characters. |
| `guard.bannedSubstrings` | `readonly string[]` | no | `none` | Substrings that flag a reply (case-insensitive). |
| `consultation` | `ConsultationPolicy` | no |  | Limits and wording for when the agent asks a connected assistant for help mid-call: the hold phrase, the timeouts and the cumulative cap. |
| `onUtterance` | `(text: string, ctx: HandlerContext) => Promise<void> \| void` | no |  | Runs after each thing the caller says, with the text. A notification: delivered at least once and in call order, and the call never waits for it. |
| `onFieldCaptured` | `(field: string, value: unknown, ctx: HandlerContext) => Promise<void> \| void` | no |  | Runs each time a process field is captured, with the field and value. A notification: the call never waits for it. |
| `onCallEnd` | `(outcome: OnCallEndOutcome, ctx: HandlerContext) => Promise<void> \| void` | no |  | Runs when the call ends, with how it went. A notification: the call never waits for it. |
| `onDtmf` | `(event: DtmfEvent, ctx: HandlerContext) => Promise<void> \| void` | no |  | Runs when the caller presses a phone key. A notification: the call never waits for it. This replaces `ctx.onDtmf(handler)`, because a closure cannot outlive a stateless invocation. |
| `onQuery` | `OnQuery` | no |  | Make your own function the model. It is handed the latest utterance and the text history with the turn's abort signal, and returns a string or an async iterable of strings that is spoken. Text only: a brain that needs VoiceLayer's tools uses `brain` with a framework adapter. Excludes `brain` and a bound brain connector. |
| `brain` | `BrainTurnHandler \| { readonly handler: BrainTurnHandler; readonly firstTokenDeadlineMs?: number }` | no |  | A framework brain: the handler an adapter builds (`openaiAgentsBrain`, `claudeAgentBrain` or `langgraphBrain` from `@voicelayer/sdk/brain`), or `{ handler, firstTokenDeadlineMs }` to set how long the first token may take. Excludes `onQuery`. |
| `puppetMode` | `boolean` | no |  | Run the agent as a remote-controlled puppet: no autonomous model loop, and a connected assistant says what is spoken. |
| `hostControlled` | `boolean` | no |  | Let a connected assistant interject during an autonomous agent's calls and answer its questions. |
| `mcpExposed` | `boolean` | no | `true` | Make the agent visible to connected assistants (MCP) and the API, so they can list it and drive its live calls. |

### defineProcess

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

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

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

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `def` | `ProcessDefinition<T>` | yes | The fields to collect (`collect`) and what to do when they are in. |
| `def.collect` | `T` | yes | The fields to capture, by name. |
| `def.completeWhen` | `CompletionStrategy` | no | The rule that decides when the process is complete. |
| `def.backendAck` | `ProcessBackendAck` | no | An endpoint the platform tells when the process completes. |
| `def.onComplete` | `(data: InferProcessData<T>, ctx: HandlerContext) => Promise<void> \| void` | no | Runs when the process completes, with the captured data. It has 5 seconds; it is awaited, errors are logged, and the process stays complete. |
| `def.onField` | `<K extends keyof T>(field: K, value: InferFieldValue<T[K]>, ctx: HandlerContext) => Promise<void> \| void` | no | Runs each time a field is captured, with the field name and value. It has 2 seconds; it is awaited, errors are logged, and the field stays captured. |

##### Returns

`ProcessDefinition<T>`: The same definition, typed.

##### Example

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

### ProcessField

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

```ts
interface ProcessField
```

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

#### Fields

| Name | Type | Required | Default | Description |
|---|---|---|---|---|
| `type` | `ProcessFieldType` | yes |  | What kind of value to capture. `datetime`, `email` and `phone` are captured as strings. One of `string`, `number`, `boolean`, `string[]`, `datetime`, `email`, `phone`. |
| `required` | `boolean` | no | `false` | Whether the process needs this field before it counts as complete (with `completeWhen: 'all-required-captured'`). |
| `pattern` | `RegExp` | no |  | A pattern a captured `string` (or each `string[]` item) must match. Its flags are kept, so case sensitivity carries over. |
| `min` | `number` | no |  | The lower bound: the smallest value for a `number`, the shortest length for a `string`. |
| `max` | `number` | no |  | The upper bound: the largest value for a `number`, the longest length for a `string`. |
| `enum` | `readonly string[]` | no |  | The only values the field may take. |
| `ask` | `string` | no |  | What the agent says to ask for this field. |
| `extract` | `string` | no |  | A hint to the model for pulling this field out of what the caller said. |
| `fromCaller` | `boolean` | no | `true` | Set to `false` when the agent writes the field itself; it is then never extracted from the caller's words. |

### TriggerDefinition

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

```ts
interface TriggerDefinition
```

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

#### Fields

| Name | Type | Required | Description |
|---|---|---|---|
| `on` | `TriggerCondition` | yes | The condition that fires the trigger. |
| `then` | `TriggerAction` | yes | What to do when it fires. |
| `onlyWhile` | `string` | no | Restrict the trigger to one step of the flow, by step name. |

### ActionDeclaration

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

```ts
interface ActionDeclaration
```

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

#### Fields

| Name | Type | Required | Default | Description |
|---|---|---|---|---|
| `name` | `string` | yes |  | The action's tool name, for example `vl_send_text` or `int_hubspot_contacts_create`. |
| `confirm` | `boolean` | no | `false` | Ask the person before running. |
| `sendRealValues` | `boolean` | no | `false` | Let real caller values reach the connected app; each use is recorded. |
| `connection` | `string` | no |  | The connection a connected app's action uses, by id or name. Resolved when the agent is published. |

### OnCallEndOutcome

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

```ts
interface OnCallEndOutcome
```

How the call went, handed to `onCallEnd`.

#### Fields

| Name | Type | Required | Description |
|---|---|---|---|
| `reason` | `string` | yes | Why the call ended. |
| `durationMs` | `number` | yes | How long the call lasted, in milliseconds. |
| `processCompleted` | `boolean` | yes | Whether the process completed. |
| `fieldsCaptured` | `number` | yes | How many process fields were captured. |
| `handoffOccurred` | `boolean` | yes | Whether the call was handed to a person. |

### EndCallInfo

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

```ts
interface EndCallInfo
```

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

#### Fields

| Name | Type | Required | Description |
|---|---|---|---|
| `reason` | `string` | no | Why the call is ending, for example the reason the agent gave when it ended the call. |
| `trigger` | `EndCallTrigger` | yes | What caused the end: see `EndCallTrigger`. One of `tool`, `host`, `idle`, `max_duration`, `participant-left`, `flow`, `engine-closed`, `user`, `admission`, `agent-disconnected`. |
| `teardown` | `'room' \| 'agent'` | yes | What the platform is about to close: the whole `room` or only the `agent`. |

### DtmfEvent

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

```ts
interface DtmfEvent
```

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

#### Fields

| Name | Type | Required | Description |
|---|---|---|---|
| `participantId` | `string` | yes | The participant who pressed the key. |
| `code` | `number` | yes | The key's DTMF code number. |
| `digit` | `string` | yes | The key as a character: `0` to `9`, `*` or `#`. |
| `at` | `Date` | yes | When the key was pressed. |

### Participant

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

```ts
interface Participant
```

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

#### Fields

| Name | Type | Required | Description |
|---|---|---|---|
| `id` | `string` | yes | The participant's id within the call. |
| `kind` | `string` | yes | What kind of participant this is, for example a caller, a person you transferred to, or the agent. |
| `isAgent` | `boolean` | yes | Whether this participant is the agent itself. |
| `phone` | `string \| null` | yes | The participant's phone number, or `null` when they do not have one. |
| `displayName` | `string \| null` | yes | The participant's name when the platform knows it, otherwise `null`. |
| `attributes` | `Readonly<Record<string, string>>` | yes | Extra attributes attached to the participant, including any `participants.attributes` returned. |
| `joinedAt` | `Date` | yes | When the participant joined. |
| `leftAt` | `Date \| null` | yes | When the participant left, or `null` while they are still on the call. |

### TranscriptHandle

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

```ts
interface TranscriptHandle
```

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

#### tail

```ts
tail(n: number): string
```

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

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `n` | `number` | yes | How many turns to include. |

##### Returns

`string`

#### full

```ts
full(): string
```

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

##### Returns

`string`

### AgentHandle

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

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

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

#### Fields

| Name | Type | Required | Description |
|---|---|---|---|
| `name` | `string` | yes | The agent's name, from its config. |
| `config` | `AgentConfig<TProcess>` | yes | The config you passed to `defineAgent`. |
| `messageHandler` | `MessageHandler \| undefined` | yes | The direct-mode handler set by `onMessage`, if any. |

#### manifest

```ts
manifest(opts?: BuildOptions): BuildResult
```

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

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `opts` | `BuildOptions` | no | Build options such as the build identity. |

##### Returns

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

#### onMessage

```ts
onMessage(handler: MessageHandler): AgentHandle<TProcess>
```

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

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `handler` | `MessageHandler` | yes | Called with each inbound message and a context to answer through. |

##### Returns

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

##### Throws

- TypeError when `handler` is not a function.

##### Example

```ts
const agent = defineAgent({ name: 'text-bot', prompt: 'You answer questions.' }).onMessage(async (message, ctx) => {
  await ctx.send({ text: `You said: ${message.text}` });
});
await agent.start();
```

#### start

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

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

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `opts` | `StartOptions` | no | The lock file, signal handling, logger and the rest of `StartOptions`. |

##### Returns

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

##### Throws

- LockError when there is no lock file and the agent has no `onMessage`.
- BuildError when the agent's definition has errors.

##### Example

```ts
await agent.start({ log: consoleLogger('debug') });
```

### startAgents

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

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

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

##### Parameters

| Name | Type | Required | Description |
|---|---|---|---|
| `handles` | `readonly AgentHandle[]` | yes | The agents to serve. |
| `opts` | `StartOptions` | no | The lock file, signal handling, exit behaviour, logger and the rest of `StartOptions`. |

##### Returns

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

##### Throws

- BuildError when an agent's definition has errors.
- LockError when there is no lock file, or it has no build of the agent for the credential's environment.
- TypeError when more than one handle has `onMessage` in the same process.

##### Example

```ts
import { startAgents } from '@voicelayer/sdk';
import { sales, support } from './agents.js';

await startAgents([sales, support]);
```

### StartOptions

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

```ts
interface StartOptions extends Omit<RunnerOptions, 'builds'>
```

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

#### Fields

| Name | Type | Required | Default | Description |
|---|---|---|---|---|
| `lock` | `string \| LockFile` | no | `'VOICELAYER_LOCK_FILE', else './voicelayer.lock.json'` | The lock file `voicelayer deploy` wrote: a path, or the parsed lock. |
| `signals` | `boolean` | no | `true` | Install SIGTERM and SIGINT handlers: the first drains current calls, a second exits at once. |
| `exit` | `boolean` | no | `true` | Exit the process when the runner finishes (every build retired, or drained after SIGTERM). |
| `direct` | `Omit<ServeDirectOptions, 'signal' \| 'log'>` | no | `key from 'VOICELAYER_API_KEY'` | Direct-mode options for an agent with `onMessage`, such as the scoped API key. |
| `direct.apiKey` | `string` | no |  | A scoped REST key (`messages:send`, `messages:read`, `events:read`, `conversations:control`). Default `VOICELAYER_API_KEY`. A `vlw_` worker credential is refused. |
| `direct.baseUrl` | `string` | no |  | Default `VOICELAYER_API_URL`, else https://api.vlayers.ai. |
| `direct.channels` | `readonly string[]` | no |  | Only these channels' messages reach the handler (one channel also narrows the stream server-side). |
| `direct.cursorStore` | `CursorStore` | no |  | Where to keep the place in the event stream, so a restart continues where it stopped. |
| `direct.onHandlerError` | `(err: unknown, message: InboundMessage) => void` | no |  | Told about a handler that threw (after it is logged); the runner moves on to the next message. |
| `direct.fetch` | `typeof fetch` | no |  | Tests and proxies. |
| `direct.reconnect` | `{ /** The wait before the first reconnect, in milliseconds. @default 500 */ readonly initialDelayMs?: number; /** The longest wait between reconnects, in milliseconds. @default 30000 */ readonly maxDelayMs?: number; /** Reconnect when the stream is silent this long, in milliseconds. @default 45000 */ readonly idleTimeoutMs?: number; }` | no |  | Stream reconnect tuning (defaults: 500 ms first delay, 30 s cap, 45 s idle timeout). |
| `direct.env` | `NodeJS.ProcessEnv` | no |  | Read in tests: the process environment the defaults come from. |
| `room` | `Omit<ServeRoomOptions, 'log'>` | no |  | Options for a hosted agent: ports and `onRequest`, which answers requests to the agent's published endpoints. Used only when the process runs inside a hosted room. |
| `room.host` | `string` | no |  | The address to listen on. Default `0.0.0.0`: the shim reaches the process over the room's loopback, and `voicelayer image test` over a docker network. |
| `room.fetch` | `typeof fetch` | no |  | The `fetch` that reaches the shim. Default the global one. |
| `room.env` | `Readonly<Record<string, string \| undefined>>` | no |  | The environment to read `PORT`, `VL_SHIM_PORT`, `PUBLIC_PORT` and `VL_ROOM_ID` from. Default `process.env`. |
| `room.port` | `number` | no |  | The handlers' port (`$PORT`, 8080 by default). |
| `room.shimPort` | `number` | no |  | The shim's actions port (`$VL_SHIM_PORT`, 7070 by default). |
| `room.publicPort` | `number` | no |  | Where published requests arrive (`$PUBLIC_PORT`). Not listened on when unset (the controller sets it only for an agent with endpoints). |
| `room.onRequest` | `(req: RoomRequest) => RoomResponse \| unknown \| Promise<RoomResponse \| unknown>` | no |  | Answers published endpoint requests. Without it, they get a 404 that says the agent has no handler. |
| `room.signals` | `boolean` | no |  | Install SIGTERM/SIGINT handlers: stop accepting, finish what is running (up to `drainMs`), exit. Default true. |
| `room.exit` | `boolean` | no |  | Exit the process when the server stops after a signal. Default true. |
| `room.drainMs` | `number` | no |  | How long to let running requests finish after a stop signal, in milliseconds. |
| `workerKey` | `string` | no | `'VOICELAYER_WORKER_KEY'` | The worker credential (`vlw_…`). A project API key is refused before any connection opens. |
| `edgeUrl` | `string` | no | `'VOICELAYER_EDGE_URL', else 'wss://edge.vlayers.ai/worker'` | The platform's worker address. `ws://` is accepted only for localhost. |
| `capacity` | `number` | no | `20 (or 'VOICELAYER_WORKER_CAPACITY')` | How many invocations the process runs at once, shared by every agent in it. |
| `region` | `string` | no |  | A region label sent with the connection, shown in the dashboard. |
| `log` | `RunnerLogger` | no | `'consoleLogger()'` | Where the runner writes its log lines: an object with `debug`, `info`, `warn` and `error` functions that take a message and fields. `consoleLogger(level)` writes JSON lines to stderr, `silentLogger` writes nothing. |
| `onEvent` | `(event: RunnerEvent) => void` | no |  | Called with runner lifecycle events: connected, registered, register_rejected, draining, retired, fatal and the rest. |
