> For the complete documentation index, see [llms.txt](https://docs.concurrence.com/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.concurrence.com/developer-guide/guides/build-an-operator-console.md).

# Build Your Own Operator Console

Build an operator console on the Platform API and SDK: sign operators in, find live runs, take over text and phone conversations, and hand back.

Build an operator screen that lets a person watch live conversations, step in, and hand them back to the agent. This guide uses the Platform API and the Platform SDK for TypeScript (`@amigo-ai/platform-sdk`). Every call also works over HTTP with the same credentials, and the main calls include a curl version.

It is written for the engineers who build an operator experience on the Platform API, such as solutions engineers who put together a working screen for a customer deployment and developers who add operator controls to their own tools. With the sign-in used in this guide, operators use the Developer Console twice: to accept their workspace invitation and to approve the sign-in that authorizes your app. Every other step uses the API.

{% hint style="warning" %}
**Operators is a beta feature.** A workspace must be enabled for it before it can call the operator operations or the run takeover operations. Any other workspace gets `403` with the message `Operators is a beta feature that is not enabled for this workspace`. Ask your Concurrence representative to enable it. Because the feature is in beta, its contract can change. Check the API reference and the SDK release history when you upgrade the SDK.
{% endhint %}

## What You Build

* A sign-in on your server that gives each operator their own identity token.
* A list of live runs, where a run is one conversation on any channel, that shows which ones an operator can take over.
* A text panel with the conversation, a hold that stays renewed while the operator is present, a composer that stages one reply at a time, and a handback button.
* A phone panel that joins in listen mode, asks for explicit confirmation before the operator speaks to the caller, sends guidance, and hands back.
* Error messages, a record of what operators did, and exit paths that hand the run back.

## Before You Start

You need:

* **A workspace enabled for operators.** [Check access](#check-access) with one call.
* **An operator user.** A person who signs in to the workspace with the `operator`, `admin`, or `owner` role. Those roles hold `Operator:Update`, which every control call needs. The `member` and `viewer` roles do not. [Invite the person](https://docs.concurrence.com/developer-guide/platform-api/workspaces.md#invitations) with the role you want. They accept the invitation in the Developer Console.
* **An operator profile for that person.** Register it with the email address the person signs in with and, for phone calls, a phone number in E.164 format. Registering needs `Operator:Create`, which the `member`, `admin`, and `owner` roles hold.
* **For phone calls, a line that allows the number.** The operator's phone number must be in the line's `allowed_forwarding_numbers`, in the same E.164 form. Whoever provisions the line sets the list. See [Control Voice Calls](https://docs.concurrence.com/developer-guide/platform-api/conversations/channel-manager.md#control-voice-calls).
* **A platform-managed voice service for phone takeover.** A service whose `session_provider` is `gpt_realtime` does not support takeover or guidance. See [Session Provider](https://docs.concurrence.com/developer-guide/platform-api/workspaces/services.md#session-provider) and [Check the Runtime](#check-the-runtime).
* **Your workspace ID and region hosts.** The examples use the US production hosts. Use the hosts for your region from [Regions & Endpoints](https://docs.concurrence.com/developer-guide/getting-started/regions-and-endpoints.md).
* **The SDK, on your server.** Node.js 20 or later and `npm install @amigo-ai/platform-sdk`. Staging a text reply with `runs.authorTurn` needs version 0.116.0 or later. Renewing a hold with `runs.renewTakeover` and reading a staged reply with `runs.getAuthoredTurn` need 0.127.0 or later. Every SDK call in this guide runs on your server (see [How the Pieces Fit](#how-the-pieces-fit)). For setup, see [Installation](https://docs.concurrence.com/developer-guide/platform-api/platform-sdk/installation.md) and [Configuration](https://docs.concurrence.com/developer-guide/platform-api/platform-sdk/configuration.md).

Text conversations need no phone number and no line setup.

### Check Access <a href="#check-access" id="check-access"></a>

Call a read operation with the credential you plan to use. A workspace that is not enabled returns the beta `403`.

```typescript
import { AmigoClient, PermissionError } from '@amigo-ai/platform-sdk'

// True when the workspace is enabled for the operators beta.
export async function operatorsEnabled(client: AmigoClient): Promise<boolean> {
  try {
    await client.operators.list({ limit: 1 })
    return true
  } catch (error) {
    if (error instanceof PermissionError && /beta feature/i.test(error.detail ?? '')) {
      return false
    }
    throw error
  }
}
```

`operators.list` needs only `Operator:View`, so any role can run it. Any other error, including a different `403` such as a credential that belongs to another workspace, propagates so you can handle it.

## How the Pieces Fit

Your console has two parts: the operator's browser and a small server you run. A browser page on your own domain cannot call the Platform API or the Identity API directly, so the browser talks only to your server. Your server signs the operator in, keeps their tokens in that operator's session, and calls the Platform API with the operator's identity token. Every SDK call on this page runs on your server.

<figure><img src="https://1651797362-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YwM0LHtEGLt9S21OyC3%2Fuploads%2Fgit-blob-056076cb328ae2291818f0855a842a6815508a42%2Foperator-console-architecture.svg?alt=media" alt="Your operator console has two parts: the operator&#x27;s browser and a server you run. The server receives the operator&#x27;s token from the Identity API and calls the Platform API over REST for runs, operators, and real-time events. The Platform API enforces permission, eligibility, and audit and controls the agent runtime. On voice, the platform dials the operator&#x27;s phone into the call."><figcaption><p>You build the operator console: a browser screen and the server behind it. The platform enforces permission, eligibility, and audit, runs the conversation, and dials the operator's phone on voice calls. Your console carries no audio.</p></figcaption></figure>

| You build and run                                                                               | Concurrence provides                                                                                          |
| ----------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------- |
| Sign-in, sessions, and token handling on your server                                            | Identity, tokens, roles, and permissions                                                                      |
| The queue and its staffing rules: who sees which runs, in what order                            | Runs, each run's takeover eligibility, the operator roster, and a priority-ranked queue for phone calls       |
| Transcript views                                                                                | Conversation and call data                                                                                    |
| The reply composer for text conversations, and renewal of the hold while an operator is present | The hold on a text run, which keeps the agent silent, and one staged reply at a time, sent as its own message |
| The confirmation before an operator speaks, and the LIVE banner                                 | Pausing and resuming the agent, and the phone connection: dialing the operator, muting, and removing them     |
| A handback on every exit path                                                                   | The handback that resumes the agent                                                                           |
| Staffing, monitoring disclosures, and your own action log                                       | Operator-attributed audit records                                                                             |

### Two Ways to Address a Control

The same takeover can be requested by run or by operator.

|            | Run-addressed                                                                                         | Operator-addressed                                                                                              |
| ---------- | ----------------------------------------------------------------------------------------------------- | --------------------------------------------------------------------------------------------------------------- |
| Path       | `/v1/{workspace_id}/runs/{run_id}/...`                                                                | `/v1/{workspace_id}/operators/{operator_id}/...`                                                                |
| Channels   | Phone, SMS, WhatsApp, email, web, and iMessage, with one call shape                                   | Phone calls, keyed by `call_sid`                                                                                |
| Operations | `takeover`, `takeover/renew`, `switch-mode`, `handback`, `authored-turn` (stage and read), `guidance` | `join-call`, `leave-call`, `switch-mode`, `send-guidance`, `wrap-up`, `briefing`, plus the roster and the queue |
| SDK        | `client.runs`                                                                                         | `client.operators`                                                                                              |

Use the run-addressed operations for control: every run carries a server-computed `takeover` object, and one call shape covers every channel. Use the operator-addressed operations for the roster, the queue, briefings, and wrap-ups. Their contracts are on [Runs](https://docs.concurrence.com/developer-guide/platform-api/conversations/runs.md#operator-takeover) and [Operators](https://docs.concurrence.com/developer-guide/platform-api/conversations/operators.md#operator-api).

## Sign the Operator In <a href="#credentials" id="credentials"></a>

Every control call acts as one operator, and that operator is the signed-in user. The platform enforces three things on the run-addressed operations and on `join-call`, `leave-call`, `switch-mode`, `send-guidance`, and `wrap-up`:

1. **An identity token.** Send the operator's own Bearer token from sign-in. A workspace API key is refused with `403` and the message `Identity JWT required for this operation`.
2. **Permission.** The token's workspace role must include `Operator:Update`: `operator`, `admin`, or `owner`.
3. **The right operator.** The `operator_id` in the request must be the signed-in user's own operator, the one you registered for that person. Any other id gets `403`, whatever the caller's role. There is no impersonation and no admin override, so your console has no operator picker.

{% hint style="warning" %}
**A console built on one shared workspace API key cannot act as its operators.** Each operator signs in and uses their own token.
{% endhint %}

An API key still makes the calls your server needs for itself:

| Credential                    | Keep it                                                                                     | What it can call                                                                                                                                                                                                                |
| ----------------------------- | ------------------------------------------------------------------------------------------- | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| The operator's identity token | On your server, in that operator's session. The browser holds only your own session cookie. | Every control call for that operator, and the reads in the next row                                                                                                                                                             |
| A workspace API key           | On your server only                                                                         | Reads: list runs, get a run, the run summary, the state of a staged reply, list and get operators, the queue, and briefings. It can also register and update operators when the key's role allows it, and open the event stream |

<figure><img src="https://1651797362-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YwM0LHtEGLt9S21OyC3%2Fuploads%2Fgit-blob-cb38731d1663c5c54fedefb00448bb9a50859dfd%2Foperator-credentials-map.svg?alt=media" alt="A workspace API key can read runs, operators, and the queue but gets 403 on every operator action. The operator&#x27;s identity token can read and can also take over, renew the hold, hand back, switch mode, stage a reply, send guidance, join and leave a call, and record a wrap-up. The operator in the request must be the signed-in caller."><figcaption><p>A workspace API key cannot act on a live conversation. Only the signed-in operator's identity token can act, and only as that operator.</p></figcaption></figure>

Your server forwards the operator's token on every control call. Use the API key only for the reads and roster work the server does on its own behalf. See [Choose Credentials](https://docs.concurrence.com/developer-guide/getting-started/credentials.md).

### Get the Operator's Token

The device authorization flow signs an operator in through your server. Your server asks the Identity API for a code, and your page shows the code and link to the operator. The operator approves the sign-in on the Developer Console's device page, and the SDK returns an access token and a refresh token for the workspace. Your server keeps both in that operator's session. If your operators sign in through your organization's identity provider, exchange the provider's authorization code at the token endpoint instead; see [SSO Login](https://docs.concurrence.com/developer-guide/platform-api/platform-api/authentication.md#sso-login).

```typescript
import {
  AmigoClient,
  MemoryTokenStorage,
  TokenManager,
  loginWithDeviceCode,
  type DeviceCodeIssuance,
} from '@amigo-ai/platform-sdk'

// US production hosts. Use the hosts for your region from Regions & Endpoints.
const platformUrl = 'https://platform.api-us.concurrence.com'
const identityUrl = 'https://identity.api-us.concurrence.com'

// Runs on your server for one operator's sign-in. showCode sends the code and link to that
// operator's browser through your own endpoint. The operator approves the sign-in there,
// then the SDK returns their tokens.
export async function signInOperator(
  workspaceId: string,
  showCode: (issuance: DeviceCodeIssuance) => void,
): Promise<TokenManager> {
  const result = await loginWithDeviceCode({
    identityBaseUrl: identityUrl,
    workspaceId,
    clientDescription: 'operator-console',
    onCode: showCode,
  })

  const tokens = new TokenManager({
    storage: new MemoryTokenStorage(),
    identityBaseUrl: identityUrl,
  })
  await tokens.store(result)
  return tokens
}

// Build a client that carries the operator's current identity token.
// getAccessToken() refreshes the token before it expires.
export async function operatorClient(tokens: TokenManager): Promise<AmigoClient> {
  const credentials = await tokens.getAccessToken()
  if (!credentials) throw new Error('The operator is signed out')

  return new AmigoClient({
    apiKey: credentials.token, // the option is named apiKey; it also takes an identity token
    workspaceId: credentials.workspaceId,
    baseUrl: platformUrl,
    identityBaseUrl: identityUrl,
  })
}
```

* Each operator needs a user in the workspace with a role that holds `Operator:Update`.
* `TokenManager` refreshes the access token before it expires. Call `operatorClient` for each batch of requests so the client carries the current token.
* Show the operator `issuance.user_code` and `issuance.verification_uri_complete`.
* Keep tokens on your server, in that operator's session, and out of URLs and logs.
* For the flow's details, other sign-in options, and multi-workspace users, see [Authentication & API Keys](https://docs.concurrence.com/developer-guide/platform-api/platform-api/authentication.md#device-code-flow-cli-and-desktop-apps).

### Register the Operator Profile

The profile ties the signed-in user to the phone number the platform dials. A person with `Operator:Create` registers it once per operator, and registration returns the operator's `id`.

```typescript
import type { AmigoClient } from '@amigo-ai/platform-sdk'

// Run this with a credential that holds Operator:Create (member, admin, or owner).
// It returns the operator id. Keep it in your own record for the person.
export async function registerOperator(
  client: AmigoClient,
  person: { name: string; email: string; phoneNumber: string },
): Promise<string> {
  const created = await client.operators.create({
    name: person.name,
    email: person.email, // the address the person signs in with
    phone_number: person.phoneNumber, // E.164, for example +14155550100
    connection_method: 'phone',
    role: 'operator',
  })
  return created.id
}
```

* Register the email address the person signs in with. The platform ties the operator to the signed-in user through it. An email is unique in the workspace and fixed once registered, so a wrong address needs a new operator.
* The phone number is required for phone calls and ignored for text. Leave `connection_method` at `phone`. Operators hear phone calls on their phone, and no other audio connection exists.
* The profile `role` (`operator`, `supervisor`, or `admin`) describes the person. Permissions come from the workspace role, not from this field.
* Keep the returned `id` in your own record for the person. Every control call names it as `operator_id`, and the platform accepts it only from that person's own token.

## Find Runs That Need a Human

A run is one conversation on any channel, identified by a stable `run_id`. The platform does not decide which runs need a person. Your staffing rules do. The platform gives you the inventory, each run's eligibility, and for phone calls a priority-ranked queue.

```typescript
import type { AmigoClient, components } from '@amigo-ai/platform-sdk'

type Run = components['schemas']['Run']

// While an operator holds a text run, its takeover object also carries held_by. The SDK's Run type does not list it.
type HeldBy = { operator_id: string; since: string; expires_at: string }

// Every live conversation run: running, plus paused while an operator holds it.
export async function listLiveRuns(client: AmigoClient): Promise<Run[]> {
  const runs: Run[] = []
  let continuationToken: unknown
  do {
    const page = await client.runs.list({
      kind: ['conversation'],
      status: ['live'],
      limit: 100,
      continuationToken,
    })
    runs.push(...page.items)
    continuationToken = page.has_more ? page.continuation_token : undefined
  } while (continuationToken !== undefined && continuationToken !== null)
  return runs
}

// Offer takeover controls only when this returns true. operatorId is the signed-in operator's id.
export function canTakeOver(run: Run, operatorId: string): boolean {
  if (!run.takeover.eligible) return false
  // Phone takeover and guidance work on platform-managed voice calls only.
  // A null session_provider means no runtime was recorded for the run, so offer no phone controls.
  if (run.channel === 'voice' && run.session_provider !== 'concurrence') return false
  // A paused text run is held, and another operator's takeover on it is refused.
  // Offer takeover only to the operator who holds it, to resume their panel.
  // For everyone else, show who holds it instead (takeover.held_by).
  if (run.channel !== 'voice' && run.status === 'paused') {
    const heldBy = (run.takeover as { held_by?: HeldBy | null }).held_by
    return heldBy?.operator_id === operatorId
  }
  return true
}
```

Read these fields on each run:

| Field                    | Use                                                                                                                                                                                                                                                                                                                                                                                                                                   |
| ------------------------ | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `status`                 | `running` is live. `paused` is a text run that an operator holds, for as long as the hold lasts. Both match the `live` filter. A phone call with an operator on it stays `running`. A `dormant` run is idle and cannot be taken over.                                                                                                                                                                                                 |
| `channel`                | `voice`, `sms`, `whatsapp`, `email`, `web`, or `imessage`.                                                                                                                                                                                                                                                                                                                                                                            |
| `takeover`               | `eligible`, `mode_options`, and `reason`, plus `held_by` while an operator holds a text run. Voice offers `listen` and `takeover`. Every other channel offers `takeover` only. When `eligible` is false, `reason` is short text you can show as the disabled-state explanation. `held_by` gives the holder's `operator_id`, `since`, and `expires_at`, the end of the hold unless it is renewed. `eligible` stays true on a held run. |
| `session_provider`       | The voice runtime. `concurrence` is platform-managed, and `gpt_realtime` is the realtime provider. It is `null` when no runtime was recorded for the run, so offer phone controls only when it is `concurrence`.                                                                                                                                                                                                                      |
| `source_call_sid`        | The call's handle for phone runs. Use it for the operator-addressed operations and the observer stream.                                                                                                                                                                                                                                                                                                                               |
| `source_conversation_id` | The conversation to read for text runs.                                                                                                                                                                                                                                                                                                                                                                                               |

### Check the Runtime <a href="#check-the-runtime" id="check-the-runtime"></a>

Phone takeover and guidance work on platform-managed voice calls, so check `session_provider` in addition to `takeover`: offer them only when it is `concurrence`. For a `gpt_realtime` call, show the run for monitoring and offer neither control. `canTakeOver` in the snippet above applies both checks.

### Rank Phone Calls

`client.operators.getQueue()` returns active phone calls ranked by `priority_score`, each with `priority_reasons` (`high_risk`, `long_wait`, `safety_concern`, or `looping`) and context such as `wait_seconds`. Match an item to its run on `call_sid`, which is the run's `source_call_sid`.

### Watch for Changes

The workspace event stream tells you when to refresh. It is best-effort, so treat events as hints and read state from the Runs API. Open one stream on your server and push refresh hints to each operator's browser. A workspace allows a limited number of simultaneous streams, so do not open one per tab.

```typescript
import type { AmigoClient } from '@amigo-ai/platform-sdk'

const refreshHints = new Set([
  'call.started',
  'call.ended',
  'call.escalated',
  'text.started',
  'text.completed',
])

// Runs once on your server, with a client built from your workspace API key.
// Refresh the run list when the stream hints that something changed.
// The Runs API stays the source of truth; events are hints.
export function watchForChanges(client: AmigoClient, refresh: () => void): () => void {
  let timer: ReturnType<typeof setTimeout> | undefined
  const scheduleRefresh = () => {
    clearTimeout(timer)
    timer = setTimeout(refresh, 2000) // coalesce bursts and stay inside the read limit
  }

  // The stream is best-effort, so also refresh on a slow timer.
  const safetyNet = setInterval(refresh, 45_000)

  const subscription = client.events.subscribeToWorkspace({
    onEvent: (event) => {
      if (refreshHints.has(event.event_type)) scheduleRefresh()
    },
    onError: (error) => console.error('The event stream stopped', error),
  })

  return () => {
    clearTimeout(timer)
    clearInterval(safetyNet)
    subscription.unsubscribe()
  }
}
```

| Event                            | Meaning                                                                                                  |
| -------------------------------- | -------------------------------------------------------------------------------------------------------- |
| `call.started`, `call.ended`     | A phone call began or ended. `call.ended` carries `escalated`.                                           |
| `call.escalated`                 | An operator joined a call that had no open escalation, which opened one. `trigger` and `reason` say why. |
| `text.started`, `text.completed` | A text session began or ended.                                                                           |

Events carry identifiers and metadata, not message text. The SDK reconnects on its own and sends the last event ID it received, so the stream replays recent events you missed, on a best-effort basis. Ignore event types you do not handle. Open the stream with your workspace API key: a client built from an operator's token cannot reconnect after that token expires. When `onError` fires, the SDK has stopped retrying, so open the stream again with a new client. A `too_many_streams` error means the workspace has too many streams open. Close the ones you do not need. The [SSE Events](https://docs.concurrence.com/developer-guide/platform-api/conversations/sse-events.md) page describes the stream and its connection frames.

## Take Over a Text Conversation

Text takeover uses the same calls on SMS, WhatsApp, email, web, and iMessage runs, and `takeover.eligible` says which runs accept them. There is no listen mode, because there is no live audio. Watching a text run is a read of its conversation and changes nothing. Takeover is what holds the run: the run is `paused`, and the agent does not reply while the hold lasts, apart from the emergency reply and the case where the platform cannot confirm the hold, both described in [While an Operator Holds a Run](#while-an-operator-holds-a-run). A hold lasts 90 seconds and ends by itself unless your console renews it, so a closed tab or a lost connection hands the conversation back to the agent about 90 seconds after the last renewal.

<figure><img src="https://1651797362-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YwM0LHtEGLt9S21OyC3%2Fuploads%2Fgit-blob-dd1ea0f77455b505f8ae232dd3480d30656b7b0a%2Foperator-text-takeover-flow.svg?alt=media" alt="To take over a text run, list live runs and read each run&#x27;s takeover object, then take over, which holds the run for 90 seconds and pauses it. Renew the hold at least every 30 seconds while the operator is present. Stage one reply at a time and read its state: pending, consumed, or expired. A handback ends the hold and discards a pending reply. A hold that nobody renews ends by itself, and the agent answers the person&#x27;s next message."><figcaption><p>On a text run, taking over holds the run for 90 seconds. Renew the hold, stage one reply at a time, and read its state. A handback discards a pending reply.</p></figcaption></figure>

1. **Check eligibility.** `takeover.eligible` is true and `mode_options` includes `takeover`. A `paused` run is held: `takeover.held_by` names the operator, when they took the run, and when the hold ends unless it is renewed. Offer takeover on a `running` run, and on a `paused` run whose `held_by.operator_id` is the signed-in operator's, to resume their panel. A different operator's takeover on a held run is refused with `409`.
2. **Take over.** The run becomes `paused`. The response carries `held_by`, `hold_token`, and `lease_seconds`, which is 90. Keep the `hold_token` in the operator's session on your server and send it back exactly as received: it is opaque, so do not parse or reformat it. If the conversation ended before the takeover took hold, the call returns `409`. If another operator holds the run, the call returns `409` with `detail.code` `run_held`: `detail.held_by` gives who holds it, since when, and until when, and `detail.operator_name` names them. Show the holder to the operator.
3. **Renew the hold.** While the operator is present, renew at least every 30 seconds with the `hold_token`. Each renewal moves the end of the hold to 90 seconds from the renewal, so one failed renewal does not end the hold. A renewal does not take a run. If the hold is gone because it was handed back, ran out, or another operator took the run, the renewal returns `409` with `detail.code` `hold_lost`: stop renewing, tell the operator that the agent may have replied, and let them take over again on purpose. The holder can also call takeover again, which keeps the hold and returns the same `hold_token`, so it recovers a token you lost. Renew with the token rather than by taking over again, because a takeover that reaches the platform after a handback holds the run again.
4. **Show the conversation.** Read it with `source_conversation_id` while the panel is open. The person's messages appear in it while the run is held, and the agent does not answer them (see [While an Operator Holds a Run](#while-an-operator-holds-a-run) for the exceptions). Reads are limited to 60 per minute per credential, so poll at a measured pace.
5. **Stage a reply.** The operator writes a reply of 1 to 4,000 characters. Staging needs a hold that the operator owns: without one, the call returns `409` with `detail.code` `no_hold`. The platform hands the reply to the agent, which sends it as its own message in the conversation.
6. **Read what became of the reply.** Read its state until it is `consumed` or `expired`, then stage the next reply. A run has one reply waiting at a time. See [How a Staged Reply Behaves](#how-a-staged-reply-behaves).
7. **Hand back.** The hold ends, the run returns to `running`, and the agent answers the person's next message. A handback discards a reply that is still waiting, so show the operator when one is before they hand back. Only the operator who holds the run, or an admin or owner acting as their own operator, can hand back a held run. Anyone else gets `403` and the hold stays. Handing back a run that nobody holds succeeds and changes nothing.

{% tabs %}
{% tab title="TypeScript" %}

```typescript
import { isAmigoError } from '@amigo-ai/platform-sdk'
import type { AmigoClient, components } from '@amigo-ai/platform-sdk'

type Run = components['schemas']['Run']

// Take over a live text run. Text runs offer takeover only. A run that another operator holds is refused with 409.
// Keep hold_token and send it back exactly as received.
export async function takeOverTextRun(client: AmigoClient, run: Run, operatorId: string) {
  if (!run.takeover.eligible || !(run.takeover.mode_options ?? []).includes('takeover')) {
    throw new Error(run.takeover.reason ?? 'This run cannot be taken over')
  }
  const { hold_token, held_by, lease_seconds } = await client.runs.takeOver(run.run_id, { operator_id: operatorId, mode: 'takeover' })
  if (!hold_token || !held_by) throw new Error('The platform returned no hold for this run')
  return { hold_token, held_by, lease_seconds }
}

// Renew the hold every 30 seconds while the operator is present. Runs on your server. Pass
// () => operatorClient(tokens) as getClient, so each renewal carries the current token. Call the returned
// function when the operator hands back, signs out, or goes idle. onStopped fires when the platform refuses a
// renewal that a retry cannot fix: 409 hold_lost means the hold was handed back, ran out, or another operator
// took the run.
export function keepHold(
  getClient: () => Promise<AmigoClient>,
  runId: string,
  operatorId: string,
  holdToken: string,
  onStopped: (status: number) => void,
): () => void {
  const timer = setInterval(async () => {
    try {
      const client = await getClient()
      await client.runs.renewTakeover(runId, { operator_id: operatorId, hold_token: holdToken })
    } catch (error) {
      const status = isAmigoError(error) ? error.statusCode : undefined
      // Any other 4xx will fail again on a retry, so stop renewing.
      if (status !== undefined && status < 500 && status !== 401 && status !== 429) {
        clearInterval(timer)
        onStopped(status)
      }
      // A 401 (the token refreshes), a 429, a 5xx or a network error: the next renewal tries again. One failed renewal does not end the hold.
    }
  }, 30_000)
  return () => clearInterval(timer)
}

// Read the conversation so the operator sees what the person wrote.
export async function readTranscript(client: AmigoClient, run: Run) {
  if (!run.source_conversation_id) throw new Error('This run has no conversation to read')
  const conversation = await client.conversations.get(run.source_conversation_id)
  return conversation.turns ?? []
}

// Stage the operator's reply. The platform hands it to the agent, which sends it as its own message.
// Staging needs a hold the operator owns (409 no_hold), and one reply waits at a time (409 reply_pending).
export async function stageReply(client: AmigoClient, run: Run, operatorId: string, text: string) {
  const staged = await client.runs.authorTurn(run.run_id, { operator_id: operatorId, text })
  return staged.staged // true: the reply was handed over, not sent. Read its state next.
}

// What became of the last reply staged on this run. state is none, pending, consumed or expired. Poll it while a reply is pending.
export async function readReplyState(client: AmigoClient, run: Run) {
  return client.runs.getAuthoredTurn(run.run_id)
}

// Release the run. The agent answers again, and a reply that is still waiting is discarded.
export async function handBackTextRun(client: AmigoClient, run: Run, operatorId: string) {
  const result = await client.runs.handBack(run.run_id, { operator_id: operatorId })
  return result.success
}
```

{% endtab %}

{% tab title="curl" %}

```bash
# Set WORKSPACE_ID, RUN_ID, OPERATOR_ID (your operator's id), and OPERATOR_TOKEN (the operator's access token).
BASE=https://platform.api-us.concurrence.com
RUN="$BASE/v1/$WORKSPACE_ID/runs/$RUN_ID"

# Take over. The response carries held_by, hold_token, and lease_seconds.
# Set HOLD_TOKEN to the hold_token, exactly as returned.
curl -X POST "$RUN/takeover" \
  -H "Authorization: Bearer $OPERATOR_TOKEN" -H "Content-Type: application/json" \
  -d "{\"operator_id\": \"$OPERATOR_ID\", \"mode\": \"takeover\"}"

# Renew the hold, at least every 30 seconds
curl -X POST "$RUN/takeover/renew" \
  -H "Authorization: Bearer $OPERATOR_TOKEN" -H "Content-Type: application/json" \
  -d "{\"operator_id\": \"$OPERATOR_ID\", \"hold_token\": \"$HOLD_TOKEN\"}"

# Stage one reply
curl -X POST "$RUN/authored-turn" \
  -H "Authorization: Bearer $OPERATOR_TOKEN" -H "Content-Type: application/json" \
  -d "{\"operator_id\": \"$OPERATOR_ID\", \"text\": \"Hi, this is Sam from the clinic.\"}"

# Read what became of the last reply: none, pending, consumed, or expired
curl "$RUN/authored-turn" -H "Authorization: Bearer $OPERATOR_TOKEN"

# Hand back
curl -X POST "$RUN/handback" \
  -H "Authorization: Bearer $OPERATOR_TOKEN" -H "Content-Type: application/json" \
  -d "{\"operator_id\": \"$OPERATOR_ID\"}"
```

{% endtab %}
{% endtabs %}

The contracts are in [Take Over a Run](https://docs.concurrence.com/developer-guide/platform-api/conversations/runs.md#take-over-a-run), [Renew a Hold](https://docs.concurrence.com/developer-guide/platform-api/conversations/runs.md#renew-a-hold), [Author a Non-Voice Turn](https://docs.concurrence.com/developer-guide/platform-api/conversations/runs.md#author-a-non-voice-turn), [Read a Staged Reply](https://docs.concurrence.com/developer-guide/platform-api/conversations/runs.md#read-a-staged-reply), and [Hand a Run Back](https://docs.concurrence.com/developer-guide/platform-api/conversations/runs.md#hand-a-run-back).

### While an Operator Holds a Run

* A message from the person is recorded and shown in the conversation. The agent does not reply to it and does not run tools for it.
* The hold is best effort. When the platform cannot confirm it as a message arrives, the agent answers that message as it would without a hold, so the person is not left in silence. Read the conversation to see what was sent.
* While the platform can confirm the hold, a message that it recognizes as describing a medical emergency or self-harm gets an authored emergency reply. Recognition covers a limited set of phrasings in English and Spanish and can miss others, and a message it does not recognize gets no reply from the agent. Show the operator each new message as it arrives, because the operator who holds a run is the one answering it.
* When the hold ends, whether by a handback or because nobody renewed it, the agent does not go back over what the person wrote in the meantime. It answers the person's next message, with the held messages in context. Have the operator answer the person before they hand back.
* A conversation that your own application drives through the conversation API takes a turn or a poll while an operator holds it. The turn is recorded, `conversation.status` is `paused`, and `output` is empty, or holds the emergency reply when the platform sends one. The operator's replies are not in a turn or poll response: read them with [List Conversation Turns](https://docs.concurrence.com/developer-guide/platform-api/conversations.md#list-conversation-turns). A close returns `409` until the hold ends. See [Concurrency](https://docs.concurrence.com/developer-guide/platform-api/conversations.md#concurrency).

### How a Staged Reply Behaves

* The platform hands the reply to the agent before the call returns, and the agent sends it as its own message. `staged: true` means the reply was handed over, not that it was sent. The response carries `reply_id` and `expires_at`.
* A run has one reply waiting at a time. Staging another while one waits returns `409` with `detail.code` `reply_pending` and the waiting `reply_id`. A reply waits up to 2 minutes and is sent only while the operator who staged it still holds the run. A reply that is not sent in that time expires, and a handback discards it.
* `GET .../authored-turn` reads what became of the last reply on the run. `state` is `none` (no reply is on record), `pending` (it waits to be sent), `consumed` (it was taken to be sent), or `expired` (it ran out of time, or a handback discarded it). The response also carries `reply_id`, `operator_id`, `staged_at`, and `expires_at`. Poll it while a reply is `pending`, at a pace inside the read limit, and keep the composer locked until the state is `consumed` or `expired`.
* `consumed` means the platform took the reply to send it, and it sends it at most once. It does not confirm that the channel delivered it: if the send fails after the reply was taken, the platform does not send it again, and the state still reads `consumed`. Look for the reply as an agent message in the conversation before you stage the same text again.
* A reply that cannot be handed to the agent is discarded, so its state reads `expired` and the operator can stage another. The call returns an error, and `detail.code` says why. See [Handle Errors](#handle-errors).
* On a web conversation that an external user session owns, no agent runs for the person. The response has `waits_for_person` set to true, and the reply is sent when the person next sends a message or polls, before it expires. It then appears in the conversation's turns. The response to that message or poll does not carry it.

## Take Over a Phone Call

On a phone call the operator joins by phone. The platform dials the number on the operator's profile and adds that leg to the call. Your console controls the call and can show a live transcript. It does not carry audio.

{% hint style="info" %}
**Operator audio is phone-only.** The platform has no browser audio path for operators. The operator hears and speaks on their phone, and a browser microphone or headset does not connect them to the call.
{% endhint %}

<figure><img src="https://1651797362-files.gitbook.io/~/files/v0/b/gitbook-x-prod.appspot.com/o/spaces%2F2YwM0LHtEGLt9S21OyC3%2Fuploads%2Fgit-blob-b0ae0b52fb84942af5bc18484186da162ccd488f%2Foperator-voice-takeover-flow.svg?alt=media" alt="On a voice call the platform dials the operator&#x27;s phone. In listen mode the operator is muted, the agent stays active, and guidance goes to the agent as text the caller does not hear. After your console confirms going live, switching to takeover unmutes the operator and pauses the agent. Leaving, hanging up, or handing back resumes the agent."><figcaption><p>In listen mode the operator is muted, and the caller hears them only in takeover mode. Guidance goes to the agent as text, and your console owns the go-live confirmation.</p></figcaption></figure>

1. **Check eligibility and runtime.** The run is `voice`, `takeover.mode_options` includes `listen` and `takeover`, and `session_provider` is `concurrence`.
2. **Brief the operator.** `client.operators.createBriefing(operatorId, { call_sid })` returns a structured briefing built from call intelligence and entity context.
3. **Join in listen mode.** Pass `mode: 'listen'` explicitly. The default is `takeover`, which suspends the agent from the moment of the join. In listen mode the operator's phone rings, and they hear the call while muted. The agent continues. Joining is idempotent for the same operator. A second operator on the same call gets `409`.
4. **Follow along.** The operator hears the call on their phone. To show a live transcript, subscribe from your server to the call's [observer stream](https://docs.concurrence.com/developer-guide/platform-api/conversations/voice-agent.md#observer-websocket), which accepts the operator's identity token or a workspace API key, and send the lines to the browser. See [Observer Events](https://docs.concurrence.com/developer-guide/platform-api/conversations/observer-events.md). Keep **Go live** disabled until the operator has answered: the stream reports a `participant_joined` event with `participant_role` `operator` when they do.
5. **Send guidance when needed.** Guidance can interrupt the agent's current speech and steer its next reply without adding operator audio. Check the returned `status`. `delivered` means a live session received it. `deduplicated` means an identical guidance was just sent. `queued_no_subscriber` means no session was listening, and `failed` and `unknown` mean delivery was not confirmed.
6. **Confirm, then go live.** Switch to `takeover` only after the operator confirms. The agent's speech and turn processing stop while the operator drives.
7. **Hand back.** The operator leaves, the agent resumes in the same call, with what was said during the takeover as context when the platform captured it, and your console records a wrap-up.

{% tabs %}
{% tab title="TypeScript" %}
Join in listen mode and send guidance:

```typescript
import type { AmigoClient, components } from '@amigo-ai/platform-sdk'

type Run = components['schemas']['Run']

// Join a live phone call in listen mode. The operator's phone rings.
// Pass mode explicitly: the default is takeover.
export async function joinListening(client: AmigoClient, run: Run, operatorId: string) {
  const joined = await client.runs.takeOver(run.run_id, { operator_id: operatorId, mode: 'listen' })
  if (!joined.participant_call_sid) throw new Error('The join returned no operator leg')
  // Keep this value: switching mode needs it.
  return { participantCallSid: joined.participant_call_sid }
}

// Send guidance without taking over. True when a live session received it.
export async function sendGuidance(
  client: AmigoClient,
  run: Run,
  operatorId: string,
  message: string,
) {
  const result = await client.runs.sendGuidance(run.run_id, {
    operator_id: operatorId,
    message,
  })
  return result.status === 'delivered'
}
```

Go live after confirmation, and return to listening:

```typescript
import type { AmigoClient, components } from '@amigo-ai/platform-sdk'

type Run = components['schemas']['Run']

// Call this only after the operator confirmed they are about to speak to the caller.
export async function goLive(
  client: AmigoClient,
  run: Run,
  operatorId: string,
  participantCallSid: string,
) {
  return client.runs.switchMode(run.run_id, {
    operator_id: operatorId,
    participant_call_sid: participantCallSid,
    mode: 'takeover',
  })
}

// Mute the operator again; the agent resumes.
export async function backToListening(
  client: AmigoClient,
  run: Run,
  operatorId: string,
  participantCallSid: string,
) {
  return client.runs.switchMode(run.run_id, {
    operator_id: operatorId,
    participant_call_sid: participantCallSid,
    mode: 'listen',
  })
}
```

Hand back and record the outcome:

```typescript
import type { AmigoClient, components } from '@amigo-ai/platform-sdk'

type Run = components['schemas']['Run']

// Remove the operator from the call. The agent resumes in the same call.
export async function handBackCall(client: AmigoClient, run: Run, operatorId: string) {
  const result = await client.runs.handBack(run.run_id, { operator_id: operatorId })
  return result.success
}

// Record how the intervention ended.
export async function wrapUp(
  client: AmigoClient,
  run: Run,
  operatorId: string,
  outcome: 'resolved' | 'escalated' | 'transferred',
  notes: string,
) {
  if (!run.source_call_sid) throw new Error('This run has no call to wrap up')
  return client.operators.wrapUp(operatorId, {
    call_sid: run.source_call_sid,
    outcome,
    notes,
  })
}
```

{% endtab %}

{% tab title="curl" %}

```bash
# Set WORKSPACE_ID, RUN_ID, OPERATOR_ID, OPERATOR_TOKEN, and, after the join, PARTICIPANT_CALL_SID.
BASE=https://platform.api-us.concurrence.com
RUN="$BASE/v1/$WORKSPACE_ID/runs/$RUN_ID"

# Join in listen mode. Keep participant_call_sid from the response.
curl -X POST "$RUN/takeover" \
  -H "Authorization: Bearer $OPERATOR_TOKEN" -H "Content-Type: application/json" \
  -d "{\"operator_id\": \"$OPERATOR_ID\", \"mode\": \"listen\"}"

# Go live, after the operator confirms
curl -X POST "$RUN/switch-mode" \
  -H "Authorization: Bearer $OPERATOR_TOKEN" -H "Content-Type: application/json" \
  -d "{\"operator_id\": \"$OPERATOR_ID\", \"participant_call_sid\": \"$PARTICIPANT_CALL_SID\", \"mode\": \"takeover\"}"

# Hand back
curl -X POST "$RUN/handback" \
  -H "Authorization: Bearer $OPERATOR_TOKEN" -H "Content-Type: application/json" \
  -d "{\"operator_id\": \"$OPERATOR_ID\"}"
```

{% endtab %}
{% endtabs %}

The contracts are in [Take Over a Run](https://docs.concurrence.com/developer-guide/platform-api/conversations/runs.md#take-over-a-run), [Switch Mode](https://docs.concurrence.com/developer-guide/platform-api/conversations/runs.md#switch-mode), [Send Guidance](https://docs.concurrence.com/developer-guide/platform-api/conversations/runs.md#send-guidance), and [Record Operator Wrap-Up](https://docs.concurrence.com/developer-guide/platform-api/conversations/operators.md#record-operator-wrap-up).

### Go-Live Confirmation

The API does not supply a confirmation flow. Your console provides one, because going live puts a person's voice on a call with a caller. Make it explicit:

* Name the caller and the service, and say that the operator will speak to the caller and the agent will stop.
* Require a deliberate action. Do not trigger it from a keyboard shortcut or a default-focused button.
* Show a persistent **LIVE** banner while the operator is in takeover, with a **Stop talking** control that returns to listen mode.
* Tell the operator when to speak. Mode changes take a moment to reach the call, so show a switching state until the response returns.

### What the Phone Connection Does

* The join response means the platform placed the call to the operator's phone. The operator answers on their phone. Carrier conditions can delay the leg.
* A mode switch needs the `participant_call_sid` from the join response. Keep it, and the current mode, in your own session record. After a page reload, repeating the join with `mode: 'listen'` returns the same `participant_call_sid` for the same operator, but its `mode` echoes the request rather than the call's current mode.
* If the operator hangs up, the agent resumes. Hand back removes the operator's leg and resumes the agent.
* Recorded turns can carry `speaker_id` and `speaker_role` to attribute caller, agent, and operator speech. Tolerate missing or ambiguous speaker metadata.

## Verify the Flow

Run each flow once on a test workspace before you show it to anyone.

**Text**

* Run these steps on a test conversation of each channel you plan to staff.
* After takeover, `GET /runs/{run_id}` shows `status` `paused`, and `takeover.held_by` names your operator.
* While the run is held, send a message as the person. It appears in the conversation, and the agent does not reply. A conversation your application drives through the conversation API accepts the turn, reads `paused`, and returns an empty `output`.
* Stage a reply. It appears in the conversation as an agent message, and `GET /runs/{run_id}/authored-turn` reads `consumed`.
* Stop renewing and wait 90 seconds. The run reads `running` again, and a renewal returns `409` with `hold_lost`.
* Take over again, then hand back. The status is `running`. Send a message as the person: the agent answers it.
* Clean up: hand back, then close the test conversation.

**Phone**

* After a listen join, the operator's phone rings and the operator hears the call. Once they answer, the call's observer stream reports `participant_joined` with `participant_role` `operator`.
* After go-live, the agent stops speaking.
* After handback, the operator's leg ends and the agent keeps the call.
* Clean up: hand back, end the test call, and record a wrap-up.

Test phone takeover on a real phone call to a test line whose allowlist includes your test operator's number. A browser test call or a simulation is not a phone call: its run reports `takeover.eligible` as false, and a join on it is refused. In production, real callers and real operators replace the test line and the test numbers.

## Handle Errors

Branch on the status, then show your own text. Log the `detail` in the body with the `request_id` for support, except on `422`, where `detail` can echo what the operator typed. On `409`, `detail` names the reason the request was refused. A hold or reply conflict on a text run carries an object with a `code`, listed after the table. Any other `409` carries text your console can show.

| Status | Typical cause                                                                                                                                                                                                                                                                                                                                                                                               | What your console shows                                                                                                       |
| ------ | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- | ----------------------------------------------------------------------------------------------------------------------------- |
| `401`  | The token is missing, invalid, or expired.                                                                                                                                                                                                                                                                                                                                                                  | Refresh the token, or send the operator back to sign-in.                                                                      |
| `403`  | The workspace is not enabled: `Operators is a beta feature that is not enabled for this workspace`.                                                                                                                                                                                                                                                                                                         | "Operators is not enabled for this workspace." Hide the operator screens and point to your Concurrence representative.        |
| `403`  | A workspace API key was used: `Identity JWT required for this operation`.                                                                                                                                                                                                                                                                                                                                   | A developer error. Send the operator's token.                                                                                 |
| `403`  | The request names another operator: `You may only perform operator actions as your own operator identity.`                                                                                                                                                                                                                                                                                                  | "You can only act as yourself." Remove any operator picker.                                                                   |
| `403`  | The role lacks `Operator:Update`, the token belongs to another workspace, or the call belongs to another workspace.                                                                                                                                                                                                                                                                                         | "Your role cannot do this."                                                                                                   |
| `403`  | A handback of a held text run by an operator who does not hold it and is not an admin or owner: `Only the operator who holds this run, or an admin or owner, can hand it back`.                                                                                                                                                                                                                             | "Another operator holds this conversation."                                                                                   |
| `404`  | The run is not live in this workspace, no operator profile exists for the id, or the call or the operator's leg was not found. A handback after the operator already left a call also returns `404`.                                                                                                                                                                                                        | "This conversation is not live." Refresh the list. If the profile is missing, ask an admin to register one.                   |
| `409`  | The channel does not support the action, the conversation ended before takeover, the operator has no phone number, another operator is on the call, the call or the operator's leg already ended, or a text run's hold or staged reply conflicts with the request. Only the hold and reply conflicts carry a `detail.code`. The other causes carry text. A close on a held conversation also returns `409`. | Show the reason from `detail`, or your own text for its `code`, then refresh the run.                                         |
| `422`  | The phone number is not in the line's `allowed_forwarding_numbers`, a mode other than `listen` or `takeover` was sent, or the text is empty or longer than 4,000 characters (guidance: 5,000).                                                                                                                                                                                                              | Show fixed text, and do not show or log `detail`. For a number problem, tell the operator to ask whoever provisions the line. |
| `429`  | The credential exceeded a rate limit.                                                                                                                                                                                                                                                                                                                                                                       | Wait for `Retry-After`, then retry.                                                                                           |
| `502`  | A telephony or voice runtime failure, or the platform could not take, renew, or release the hold, stage or send the reply, or look the run up. On a staged reply, `detail.code` says whether sending it again is safe.                                                                                                                                                                                      | "That did not go through." Check the run, then retry.                                                                         |
| `503`  | The voice runtime, the identity service, or the platform is unavailable, or the run is busy. A busy run answers with `Retry-After`.                                                                                                                                                                                                                                                                         | Retry shortly.                                                                                                                |
| `504`  | Telephony or the voice runtime did not respond in time. The outcome can be unclear, and the operator's phone may still ring.                                                                                                                                                                                                                                                                                | Check the run before you retry.                                                                                               |

On a text run, these errors carry an object in `detail`, and `detail.code` says what happened:

| `detail.code`                                                                                      | Status         | Call          | What it means                                                                                                                                                                                   |
| -------------------------------------------------------------------------------------------------- | -------------- | ------------- | ----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
| `run_held`                                                                                         | `409`          | Take over     | Another operator holds the run. `detail.held_by` gives who, since when, and until when, and `detail.operator_name` names them. Either can be null. Show the holder and offer no takeover.       |
| `hold_lost`                                                                                        | `409`          | Renew         | The hold was handed back, ran out, or another operator took the run. Stop renewing and tell the operator.                                                                                       |
| `no_hold`                                                                                          | `409`          | Stage a reply | The operator has no live hold on the run. Take over first.                                                                                                                                      |
| `reply_pending`                                                                                    | `409`          | Stage a reply | A reply is already waiting, and `detail.reply_id` names it. Stage again once its state is not `pending`.                                                                                        |
| `conversation_not_active`, `reply_expired`, `channel_routing_unavailable`, `reply_not_deliverable` | `409`          | Stage a reply | The reply could not be handed to the agent, and it was not sent. `channel_routing_unavailable` means the person has not written recently enough for the platform to reach them on this channel. |
| `agent_unreachable`                                                                                | `502` or `503` | Stage a reply | The reply was not sent. Sending it again is safe.                                                                                                                                               |
| `agent_rejected_request`                                                                           | `502`          | Stage a reply | The platform's request to send the reply was refused. The reply was not sent, and sending it again will not help.                                                                               |
| `conversation_read_failed`                                                                         | `502`          | Stage a reply | Nothing was staged or sent. Sending the reply again is safe.                                                                                                                                    |
| `delivery_unconfirmed`                                                                             | `502`          | Stage a reply | The reply may have been sent. Read the conversation before you send it again.                                                                                                                   |

A busy run answers takeover, renew, handback, and stage with `503` and no code. Retry after the seconds in `Retry-After`.

Correct the request before you retry a `409` or `422`. A join on a call that is not a phone call is refused with `409`, and a mode switch or handback with `422`, so check `takeover.eligible` first. The [Platform SDK error classes](https://docs.concurrence.com/developer-guide/platform-api/platform-sdk/error-handling.md) carry `statusCode`, `detail`, and `requestId`.

```typescript
import { isAmigoError, isHttpException } from '@amigo-ai/platform-sdk'

// The code in the detail object of a text-run error, such as run_held or hold_lost.
function detailCode(error: unknown): string | undefined {
  if (!isHttpException(error)) return undefined
  const detail = error.errorBody.detail
  if (typeof detail !== 'object' || detail === null || Array.isArray(detail)) return undefined
  return typeof detail.code === 'string' ? detail.code : undefined
}

// Map an API error to the text your console shows. Branch on the status first.
export function operatorErrorMessage(error: unknown): string {
  if (!isAmigoError(error)) return 'Something went wrong. Try again.'
  const detail = error.detail ?? ''

  switch (error.statusCode) {
    case 401:
      return 'Your session ended. Sign in again.'
    case 403:
      if (/beta feature/i.test(detail)) return 'Operators is not enabled for this workspace.'
      if (/identity jwt/i.test(detail)) return 'Sign in as an operator. An API key cannot act as one.'
      if (/own operator identity/i.test(detail)) return 'You can only act as yourself.'
      if (/holds this run/i.test(detail)) return 'Another operator holds this conversation.'
      return 'Your role cannot perform operator actions.'
    case 404:
      return 'The conversation is not live, or no operator profile matches you.'
    case 409:
      switch (detailCode(error)) {
        case 'run_held':
          return 'Another operator holds this conversation.'
        case 'hold_lost':
          return 'Your hold ended and the agent may have replied. Take over again to continue.'
        case 'no_hold':
          return 'Take over the conversation before you reply.'
        case 'reply_pending':
          return 'Your last reply is still waiting to be sent.'
        case 'conversation_not_active':
        case 'reply_expired':
        case 'channel_routing_unavailable':
        case 'reply_not_deliverable':
          return 'Your reply was not sent.'
        default:
          return 'The conversation changed. Refresh the list.'
      }
    case 422:
      return 'The request was refused. Check the text, or ask whoever provisions the line to allow your phone number.'
    case 429:
      return 'Too many requests. Wait a moment, then try again.'
    case 502:
    case 503:
    case 504:
      if (detailCode(error) === 'delivery_unconfirmed') {
        return 'Your reply may have been sent. Check the conversation before you send it again.'
      }
      return 'The platform could not finish that. Check the run before you try again.'
    default:
      return 'Something went wrong. Try again.'
  }
}
```

## What Is Recorded

Operator actions are recorded against the operator who took them, when the record can be written. The operator audit log lists a takeover, a handback, a staged reply, guidance, and a mode switch. A record holds identifiers and the outcome, and the channel and mode where they apply. A staged reply and guidance are recorded with their length and a content fingerprint, not their text.

* A renewal that succeeds, and a takeover that the holder repeats, are not recorded: the end of the hold is on the run, in `takeover.held_by`. A renewal that the platform refused because the hold had ended is recorded.
* The log is refreshed about every 15 minutes, so an action appears in it after that delay. To confirm an action the operator just took, read the run or the reply's state, not the log. See [Query the Operator Audit Log](https://docs.concurrence.com/developer-guide/platform-api/conversations/operators.md#query-the-operator-audit-log).
* A wrap-up records an `outcome` of `resolved`, `escalated`, or `transferred` and up to 2,000 characters of notes.

Records are best-effort: one that cannot be written does not fail the action. Keep your own record of what your console sent, including text takeovers, handbacks, and staged replies, in your system of record.

## Production Checklist

* **Confirm before an operator speaks.** Build the [go-live confirmation](#go-live-confirmation) and the LIVE banner. Pass `mode: 'listen'` on every phone join.
* **One operator per run.** A second join on a call returns `409`. A second takeover on a held text run returns `409` with `detail.code` `run_held`, and the platform names the holder, so your console does not need to claim a run first.
* **Track who is on which call.** Your console decides how many calls an operator can be on. Joining a call does not change the operator's profile `status`, and a takeover by run does not check it, so keep your own record of who is on which call.
* **Renew only while an operator is present.** A hold that is renewed does not end, so a console that keeps renewing from an unattended screen keeps the agent silent on that conversation. Renew from your server on a timer tied to the operator's session, and stop when the session shows no input for the idle limit you set.
* **Hand back on every exit.** Hand back on sign-out, an idle timeout, an error boundary, and page close, so the agent answers again at once instead of after the hold runs out. A hold ends when it is handed back or not renewed. A closing tab cannot make a normal request, so have the page send a beacon to your server (below) and let the server hand the run back.
* **Give supervisors a way to find held runs.** List `status=paused` runs on a supervisor screen to find held text runs: `takeover.held_by` names the operator, since when, and until when. A phone call with an operator on it stays `running`, so track those from the joins your console makes, and flag the ones held longer than your policy allows. A hold ends when its holder hands it back or stops renewing it. To release one sooner, a supervisor with the `admin` or `owner` role hands the run back as their own operator, which needs an operator profile of their own.
* **Design for repeats.** A takeover repeated by the holder keeps the hold, and one from another operator returns `409`. A repeated handback succeeds, and so does a handback on a run nobody holds. On a phone call a second operator's join returns `409`, and a handback returns `404` once the operator has left. A staged reply is sent at most once, as described in [How a Staged Reply Behaves](#how-a-staged-reply-behaves). Identical guidance sent twice in a short window is reported as `deduplicated`.
* **Stay inside the rate limits.** Control calls (takeover, renew, handback, switch mode, authored turn, guidance, join, leave, wrap-up) allow 10 requests per minute. Reads allow 60. A run-addressed call is counted per credential, run, and operation, and an operator-addressed call per credential and operation. Renewing every 30 seconds uses 2 of the 10 requests a minute that the renew operation allows. Back off on `429` and honor `Retry-After`. Poll rarely and use the event stream as a hint. See [Rate Limits](https://docs.concurrence.com/developer-guide/platform-api/conversations/runs.md#rate-limits).
* **Handle PHI in your UI.** Transcripts, caller numbers, entity names, and staged text can contain protected health information. Keep them out of URLs, analytics, error trackers, and logs. Apply your own access controls and retention to anything your console stores.
* **Disclose monitoring where required.** Do not rely on the platform to tell the caller that an operator has joined or is listening. Your organization decides what disclosure policy or law requires.
* **Plan for no operator.** Takeover needs a person who is available. Define what happens when none is: a configured transfer, a callback task, or a bounded agent response. See [Operators and Escalation](https://docs.concurrence.com/operations-and-safety/operators).
* **Check the runtime.** Offer phone takeover and guidance only for `session_provider` `concurrence`.

The handback on page close has two halves. In the operator's browser, send a beacon to your own server when the page is hidden. The beacon carries your session cookie, so treat the route like any other state-changing route in your app:

```typescript
// Runs in the operator's browser. Asks your server to hand the run back when the tab closes.
export function handBackOnPageHide(runId: string): () => void {
  const onPageHide = () => {
    navigator.sendBeacon('/operator/handback', JSON.stringify({ runId }))
  }
  window.addEventListener('pagehide', onPageHide)
  return () => window.removeEventListener('pagehide', onPageHide)
}
```

On your server, the route behind `/operator/handback` finds that operator's session, builds the client with `operatorClient`, and hands the run back with `client.runs.handBack(runId, { operator_id })`, as in the snippets above, and stops that run's renewal timer. The platform refuses a handback from an operator who does not hold the run, so a stale session cannot release another operator's hold.

## Operations Used

| Task                     | Operation                                                  | SDK method                    | Contract                                                                                                                                            |
| ------------------------ | ---------------------------------------------------------- | ----------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |
| Check access             | `GET /v1/{workspace_id}/operators`                         | `operators.list`              | [List Operators](https://docs.concurrence.com/developer-guide/platform-api/conversations/operators.md#list-operators)                               |
| Register an operator     | `POST /v1/{workspace_id}/operators`                        | `operators.create`            | [Register an Operator](https://docs.concurrence.com/developer-guide/platform-api/conversations/operators.md#register-an-operator)                   |
| List live runs           | `GET /v1/{workspace_id}/runs`                              | `runs.list`                   | [List Runs](https://docs.concurrence.com/developer-guide/platform-api/conversations/runs.md#list-runs)                                              |
| Rank phone calls         | `GET /v1/{workspace_id}/operators/queue`                   | `operators.getQueue`          | [Get the Operator Queue](https://docs.concurrence.com/developer-guide/platform-api/conversations/operators.md#get-the-operator-queue)               |
| Watch for changes        | `GET /v1/{workspace_id}/events/stream`                     | `events.subscribeToWorkspace` | [SSE Events](https://docs.concurrence.com/developer-guide/platform-api/conversations/sse-events.md)                                                 |
| Read a text conversation | `GET /v1/{workspace_id}/conversations/{conversation_id}`   | `conversations.get`           | [Get Conversation Detail](https://docs.concurrence.com/developer-guide/platform-api/conversations.md#get-conversation-detail)                       |
| Brief the operator       | `POST /v1/{workspace_id}/operators/{operator_id}/briefing` | `operators.createBriefing`    | [Generate an Operator Briefing](https://docs.concurrence.com/developer-guide/platform-api/conversations/operators.md#generate-an-operator-briefing) |
| Take over or join        | `POST /v1/{workspace_id}/runs/{run_id}/takeover`           | `runs.takeOver`               | [Take Over a Run](https://docs.concurrence.com/developer-guide/platform-api/conversations/runs.md#take-over-a-run)                                  |
| Renew the hold           | `POST /v1/{workspace_id}/runs/{run_id}/takeover/renew`     | `runs.renewTakeover`          | [Renew a Hold](https://docs.concurrence.com/developer-guide/platform-api/conversations/runs.md#renew-a-hold)                                        |
| Stage a reply            | `POST /v1/{workspace_id}/runs/{run_id}/authored-turn`      | `runs.authorTurn`             | [Author a Non-Voice Turn](https://docs.concurrence.com/developer-guide/platform-api/conversations/runs.md#author-a-non-voice-turn)                  |
| Read a staged reply      | `GET /v1/{workspace_id}/runs/{run_id}/authored-turn`       | `runs.getAuthoredTurn`        | [Read a Staged Reply](https://docs.concurrence.com/developer-guide/platform-api/conversations/runs.md#read-a-staged-reply)                          |
| Send guidance            | `POST /v1/{workspace_id}/runs/{run_id}/guidance`           | `runs.sendGuidance`           | [Send Guidance](https://docs.concurrence.com/developer-guide/platform-api/conversations/runs.md#send-guidance)                                      |
| Switch mode              | `POST /v1/{workspace_id}/runs/{run_id}/switch-mode`        | `runs.switchMode`             | [Switch Mode](https://docs.concurrence.com/developer-guide/platform-api/conversations/runs.md#switch-mode)                                          |
| Hand back                | `POST /v1/{workspace_id}/runs/{run_id}/handback`           | `runs.handBack`               | [Hand a Run Back](https://docs.concurrence.com/developer-guide/platform-api/conversations/runs.md#hand-a-run-back)                                  |
| Record a wrap-up         | `POST /v1/{workspace_id}/operators/{operator_id}/wrap-up`  | `operators.wrapUp`            | [Record Operator Wrap-Up](https://docs.concurrence.com/developer-guide/platform-api/conversations/operators.md#record-operator-wrap-up)             |

## Reference

* [Runs](https://docs.concurrence.com/developer-guide/platform-api/conversations/runs.md#operator-takeover): the run-addressed operations, takeover eligibility, and rate limits.
* [Operators](https://docs.concurrence.com/developer-guide/platform-api/conversations/operators.md): the operator-addressed operations.
* [SSE Events](https://docs.concurrence.com/developer-guide/platform-api/conversations/sse-events.md) and [Observer Events](https://docs.concurrence.com/developer-guide/platform-api/conversations/observer-events.md): the event catalogs.
* [Voice Agent](https://docs.concurrence.com/developer-guide/platform-api/conversations/voice-agent.md#observer-websocket): the observer stream and session event injection.
* [Authentication & API Keys](https://docs.concurrence.com/developer-guide/platform-api/platform-api/authentication.md) and [Choose Credentials](https://docs.concurrence.com/developer-guide/getting-started/credentials.md): sign-in, tokens, and roles.
* [Platform SDK](https://docs.concurrence.com/developer-guide/platform-api/platform-sdk.md): installation, configuration, and error handling.
* [Operate and Improve a Workflow](https://docs.concurrence.com/developer-guide/guides/operate-and-improve.md): where operator work fits in a run investigation.


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

## Querying This Documentation
If you need additional information that is not directly available in this page, you can query the documentation by asking a question.

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.concurrence.com/developer-guide/guides/build-an-operator-console.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
