# Your own agent desk

> Take and place calls inside your own app: your server signs agents in with agent sessions (no second login), and the softphone engine connects with createTokenAuth. The token, ticket and socket sequence, refresh, errors and origin rules.

When your app already signs its agents in (a CRM, a helpdesk, a messaging inbox), they shouldn't need a second login to answer calls. Your **server** signs them in to MoreVoice with an **agent session**, and the softphone engine of `@morevoice/softphone` takes and places calls with it inside your page: offers from your [queues](https://docs.morevoice.ai/guides/human-agents/), outbound calls, hold and transfer controls, the copilot.

| Object | ID | What it is |
| --- | --- | --- |
| Managed user | `usr_…` | An agent or supervisor your app manages, keyed by your own `external_id`. No password, invitation or email of ours: they never sign in to the dashboard. |
| Agent session | `ags_…` | One sign-in of that person to the agent desk, minted by your server. Its bearer token (`mvas_…`) is returned once. |
| Socket ticket | | A one-use, 60-second pass for one socket (`/ws/agent`, `/ws/call`), made from the session. |

> **Before you start**
>
> Managed users and agent sessions are switched on per organisation: ask the MoreVoice team (until then the API answers `403 feature_unavailable`). Sessions sign people in to your **live** agent desk, so they take a live key (`mv_live_…`; test keys answer `403 live_only`), with the scopes `users:write` and `agent_sessions:write`. Keep the key on your server.

## 1. Sign the agent in from your server

When a signed-in person opens your agent desk, your server creates or updates them as a managed user (the same `external_id` always updates the same user), then creates their session:

**cURL**

```sh
# Your server, when a signed-in agent opens your app's agent desk. A live secret or restricted key with
# users:write and agent_sessions:write; never in a browser.
# 1. Create the agent the first time, update them after that: external_id is your own id for the person.
curl https://api.morevoice.ai/v1/users \
  -H "Authorization: Bearer $MOREVOICE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "external_id": "agent-1042",
    "name": "Dana Levi",
    "email": "dana@example.com",
    "role": "agent"
  }'

# 2. Sign them in for one shift, from your website only. Hand the response (token, expires_at) to their browser.
curl https://api.morevoice.ai/v1/agent_sessions \
  -H "Authorization: Bearer $MOREVOICE_API_KEY" \
  -H "Content-Type: application/json" \
  -d '{
    "external_id": "agent-1042",
    "ttl_s": 28800,
    "origin": "https://app.example.com"
  }'
```

**Node.js**

```ts title="sign-in-agent.ts"
import MoreVoice from "@morevoice/sdk";

const mv = new MoreVoice(); // reads MOREVOICE_API_KEY: a live key, on your server only

// Your server, when a signed-in agent opens your app's agent desk.
// 1. Create the agent the first time, update them after that: external_id is your own id for the person.
const user = await mv.users.upsert({ external_id: "agent-1042", name: "Dana Levi", email: "dana@example.com", role: "agent" });

// 2. Sign them in for one shift, from your website only.
const session = await mv.agentSessions.create({ external_id: "agent-1042", ttl_s: 28800, origin: "https://app.example.com" });

// Hand the browser the token and its expiry (createTokenAuth refreshes before it); never log the token.
console.log(user.id, session.id, session.expires_at);
const forBrowser = { token: session.token, expires_at: session.expires_at, ws_ticket: session.ws_ticket, ws_ticket_expires_at: session.ws_ticket_expires_at };
void forBrowser;
```

**Python**

```python title="sign_in_agent.py"
import os

import requests

API = "https://api.morevoice.ai/v1"
HEADERS = {"Authorization": f"Bearer {os.environ['MOREVOICE_API_KEY']}"}  # a live key, on your server only

# Your server, when a signed-in agent opens your app's agent desk.
# 1. Create the agent the first time, update them after that: external_id is your own id for the person.
response = requests.post(
    f"{API}/users",
    headers=HEADERS,
    json={"external_id": "agent-1042", "name": "Dana Levi", "email": "dana@example.com", "role": "agent"},
    timeout=30,
)
response.raise_for_status()
user = response.json()

# 2. Sign them in for one shift, from your website only.
response = requests.post(
    f"{API}/agent_sessions",
    headers=HEADERS,
    json={"external_id": "agent-1042", "ttl_s": 28800, "origin": "https://app.example.com"},
    timeout=30,
)
response.raise_for_status()
session = response.json()

# Hand the browser the token and its expiry (createTokenAuth refreshes before it); never log the token.
print(user["id"], session["id"], session["expires_at"])
for_browser = {"token": session["token"], "expires_at": session["expires_at"], "ws_ticket": session["ws_ticket"], "ws_ticket_expires_at": session["ws_ticket_expires_at"]}
```

- **Who.** Agents and supervisors only, and only active ones (`409 resource_conflict` with `member_deactivated` otherwise). Each managed user takes a seat (`402 plan_limit` when none is free). Pass `user_id` instead of `external_id` for a member who joined by invitation.
- **How long.** `ttl_s` from 300 (5 minutes) to 86400 (24 hours), default eight hours, a shift. It never slides: the softphone gets a new session before it ends (step 2).
- **From where.** `origin` binds the session to your website: its token and tickets then work only from that exact origin (scheme, host and port). In a browser, always bind it: the agent desk's REST routes allow cross-origin calls only from the origins of live sessions.
- **The response** carries the `token` (once: never log it or store it), `expires_at`, a first `ws_ticket` and the `ws_url` of the agent socket. Give the browser the token, its expiry and the first ticket; the softphone's `server` is the host in `ws_url`.
- **Signing out.** When the person signs out of your app, `DELETE /v1/agent_sessions/{id}`: the token and its tickets stop at once, and open sockets close. Deactivating the user (`DELETE /v1/users/{id}`) ends all of their sessions.
- `GET /v1/agent_sessions` lists the live ones (filter by `user_id` or `external_id`), and `POST /v1/agent_sessions/{id}/ticket` makes a socket ticket from your server, for clients that cannot call MoreVoice with the token themselves.

A minimal endpoint, behind your own sign-in: it upserts the person and returns their session (`mv.users.upsert` in Node.js, `client.users.upsert` in Python):

**cURL**

```sh title="agent-session.sh"
# What your endpoint sends, for the signed-in person (your own id for them: $ME_ID).
curl https://api.morevoice.ai/v1/users \
  -H "Authorization: Bearer $MOREVOICE_API_KEY" -H "Content-Type: application/json" \
  -d '{"external_id": "'"$ME_ID"'", "name": "Dana Levi", "role": "agent"}'
curl https://api.morevoice.ai/v1/agent_sessions \
  -H "Authorization: Bearer $MOREVOICE_API_KEY" -H "Content-Type: application/json" \
  -d '{"external_id": "'"$ME_ID"'", "ttl_s": 3600, "origin": "https://app.example.com"}'
```

**Node.js**

```ts title="agent-session.ts"
import MoreVoice from "@morevoice/sdk";

const mv = new MoreVoice(); // MOREVOICE_API_KEY: a live key with users:write and agent_sessions:write
const APP_ORIGIN = "https://app.example.com"; // your website, exactly as the browser sends Origin

/** POST /voice/agent-session in your app: the signed-in person's agent session, for their browser only. */
export async function agentSession(me: { id: string; name: string; email: string }) {
	await mv.users.upsert({ external_id: me.id, name: me.name, email: me.email, role: "agent" });
	const s = await mv.agentSessions.create({ external_id: me.id, ttl_s: 3600, origin: APP_ORIGIN });
	return { token: s.token, expires_at: s.expires_at, ws_ticket: s.ws_ticket, ws_ticket_expires_at: s.ws_ticket_expires_at };
}
```

**Python**

```python title="agent_session.py"
from morevoice import MoreVoice

client = MoreVoice()  # MOREVOICE_API_KEY: a live key with users:write and agent_sessions:write
APP_ORIGIN = "https://app.example.com"  # your website, exactly as the browser sends Origin


def agent_session(me_id: str, name: str, email: str) -> dict[str, str]:
    """POST /voice/agent-session in your app: the signed-in person's agent session, for their browser only."""
    client.users.upsert(me_id, name=name, email=email, role="agent")
    s = client.agent_sessions.create({"external_id": me_id, "ttl_s": 3600, "origin": APP_ORIGIN})
    return {"token": s.token, "expires_at": s.expires_at.isoformat(), "ws_ticket": s.ws_ticket, "ws_ticket_expires_at": s.ws_ticket_expires_at.isoformat()}
```

## 2. Connect the softphone in the browser

`createTokenAuth` signs the softphone engine in with the sessions your endpoint returns. It asks for one when the engine first connects, again shortly before it expires, and once more if MoreVoice refuses it:

```ts title="agent-desk.ts"
import { createTokenAuth, SoftphoneEngine, type SoftphoneSessionErrorCode, type SoftphoneState } from "@morevoice/softphone";

declare function render(state: SoftphoneState): void; // your UI
declare function showSignedOut(code: SoftphoneSessionErrorCode): void;

const session = createTokenAuth({
	// Your endpoint from step 1 (your own cookie or header authenticates it).
	fetchToken: async () => {
		const res = await fetch("/voice/agent-session", { method: "POST" });
		if (res.status === 401) return null; // signed out of your app: final, "signed_out"
		if (!res.ok) throw new Error(`agent session: HTTP ${res.status}`); // transient: the engine retries
		return res.json();
	},
	onError: (error) => showSignedOut(error.code),
});

const engine = new SoftphoneEngine({ auth: session.auth, api: session.api });
engine.subscribe(render); // conn, presence, ringing offers, the call
engine.configure({ server: "https://api.morevoice.ai" }); // the host in the session's ws_url

// A ringing offer: answer it (the microphone opens), or decline.
engine.subscribe((state) => {
	const offer = state.offers[0];
	if (offer && confirm(`Answer ${offer.from}?`)) void engine.answer(offer.offerId);
});
```

- The token lives in memory only: never in `localStorage`, `sessionStorage`, a cookie or a URL. Reloading the page asks your endpoint again.
- `engine.status("available")`, `engine.dial({ number, mode: "me", via: "panel" })`, `engine.hangup()`, `engine.mute(on)` and `engine.dtmf(digits)` work as in MoreVoice's own agent workspace.
- When `onError` fires the engine is signed out (`state.conn` is `"unauthorized"`). Once the person can work again, `engine.reconnectNow()` asks your endpoint for a new session. `engine.configure(null)` signs out and forgets the token.

> **Not on npm yet**
>
> `@morevoice/softphone` is published to npm with the API beta. Until then, ask the MoreVoice team for the package file.

## How it works

The sequence, from sign-in to sign-out:

```text
your backend                      MoreVoice                              the agent's browser
────────────                      ─────────                              ───────────────────
                                                                         fetchToken() → POST /voice/agent-session
POST /v1/users {external_id, …}       →  the managed user (upsert)
POST /v1/agent_sessions               →  {token mvas_…, expires_at,
     {external_id, ttl_s, origin}         ws_ticket, ws_url}
{token, expires_at, ws_ticket}   ─────────────────────────────────────→  kept in memory
                                      ←  GET  wss://…/ws/agent?ticket=<ws_ticket>     Origin: your site
                                      →  presence, offers (the socket stays open; 15 s pings)
                                      ←  POST /api/auth/ticket                         Authorization: Bearer mvas_…
                                      →  {ticket}: one use, 60 s (each reconnect, each outbound call's /ws/call)
                                      ←  POST /api/sip/calls/{id}/hangup, /api/telephony/…   Bearer mvas_…
                                                                         expires_at − 60 s: fetchToken() again
POST /v1/agent_sessions (a new one)   →  …the next requests use it; open sockets stay up
person signs out of your app:
DELETE /v1/agent_sessions/{id}        →  token and tickets refused, sockets closed (4001)
```

### Credentials

| | Agent session token | Socket ticket |
| --- | --- | --- |
| Looks like | `mvas_…` | an opaque string |
| Lifetime | `ttl_s`: 5 minutes to 24 hours, fixed | 60 seconds, one use |
| Where it goes | `Authorization: Bearer` on the agent desk's REST routes | `?ticket=` on one socket URL |
| Made by | `POST /v1/agent_sessions` (your server) | `POST /api/auth/ticket` with the token (the softphone), or `POST /v1/agent_sessions/{id}/ticket` (your server); the create response carries the first one |
| Ends | at `expires_at`, on `DELETE /v1/agent_sessions/{id}`, or when the user is deactivated | when used or after 60 s; on revocation |

The token reaches only the agent desk: the sockets `/ws/agent` (offers, presence, answer and decline), `/ws/call` (calls placed from the softphone), `/ws/meeting` and `/ws/join`, and the REST routes `/api/telephony/*`, `/api/callbacks/*`, `/api/agent/*`, `/api/me/settings`, `/api/me/extension`, `/api/me/directory`, `/api/kb/search`, `/api/copilot/*`, `/api/notifications*`, `/api/queues`, `GET /api/users`, `POST /api/sip/calls/{id}/hangup` and `POST /api/auth/ticket`. Every other route answers `403 embedded_route_forbidden`, and the person's role (agent or supervisor) applies as everywhere.

### Refresh

`createTokenAuth` asks `fetchToken` for a new session at `expires_at` minus one minute (`refreshBeforeMs`; half the lifetime when that is shorter). The new token is used from the next request on; sockets that are open stay open, and the older session simply runs out (revoke it from your server if you prefer: the softphone then reconnects on the new one). A refresh that fails is retried every 15 seconds while the old token still works. If `fetchToken` returns only a token string, with no `expires_at`, there is no early refresh: a refused token is refreshed on demand.

### Errors

| What happens | What MoreVoice answers | What `createTokenAuth` does |
| --- | --- | --- |
| The token is refused: revoked, expired, or the user deactivated | `401 agent_session_invalid` | Calls `fetchToken` once and retries. Refused again: final `session_expired` (it was past `expires_at`) or `session_revoked` |
| The session is bound to another website | `401 origin_not_allowed` | Final `origin_not_allowed` at once (a new session would be bound the same way) |
| The agent socket closes as signed out (the session was revoked) | close code `4001` | Calls `fetchToken` once and reconnects. A second one within 30 seconds: final |
| `fetchToken` resolves `null` | | Final `signed_out` |
| `fetchToken` resolves something other than an `mvas_…` token, such as an API key | | Final `invalid_token` |
| `fetchToken` throws (your backend is down) | | Not final: the engine shows offline and retries with backoff |
| A route outside the agent desk | `403 embedded_route_forbidden` | Passed to the caller (a bug in the calling code) |

Final errors are `SoftphoneSessionError`s with a typed `code`: `onError` gets each one once, `session.error` keeps the last, and the engine stops (`state.conn` is `"unauthorized"`) until `engine.reconnectNow()`.

### Origin rules

- A session created with `origin` works only from that origin: each REST call's `Origin` header must equal it exactly, and a ticket made from it opens sockets only from it (`401 origin_not_allowed` otherwise). Without `origin` it works from anywhere, but browsers can't use it across origins (no CORS).
- Browsers send `Origin` themselves on cross-origin requests and on every socket. Outside a browser (a Node.js or Electron process), pass `origin` to `createTokenAuth` for the REST calls, and give the engine a `WebSocket` that sends the same `Origin` header.
- The agent desk's REST routes answer CORS for the origins of live sessions only: `Authorization` and `Content-Type` headers, never cookies (`credentials: "omit"`).
- The API key never leaves your server; the browser only ever holds the session token, in memory.
