Skip to content

From Scratch (raw protocol) ​

Your mobile app, game engine, or server process needs to talk to Perfox — but there's no JavaScript runtime to drop a script tag into. This page walks you through the REST and WebSocket wire protocol directly, so you can build a working chat in any environment.

If you're on a JavaScript platform, the headless library implements everything on this page for you — including the conversation token and the device proof. Reach for this guide only when you genuinely can't run it.

What you'll build ​

By the end of this page you'll be able to send a message, receive the reply over a WebSocket, handle missed pushes with a fallback poll, attach a file, and optionally start a voice session — all from scratch, speaking the wire protocol directly. You'll need:

  • your API host (<slug>-api.perfox.ai);
  • a Site key (sa_site_live_…) from the Install tab of your agent's Web Chat trigger;
  • a device key — a P-256 signing key your client creates once and cannot export (see The device proof). In a browser this means the page must be served over https://;
  • and, if you want verified identity, a server-side HMAC signing step.

The shape of a conversation ​

Open the socket first, send with delivery: "async", and match the pushed reply frame back to the 202 by its reply_id.

The handshake — every REST request ​

Every call to /api/public/widget/* (all 15 routes — including tasks, file links, voice stop, upload status and transcription) carries:

http
POST /api/public/widget/send HTTP/1.1
Host: example-api.perfox.ai
X-Perfox-Site: sa_site_live_xxxxxxxxxxxxxxxx
X-Perfox-Device-Proof: eyJ0eXAiOiJwZXJmb3gtZGV2aWNlLXByb29mK2p3dCIs…
X-Perfox-Conversation-Token: <the newest token for this conversation>
Origin: https://example.com
Content-Type: application/json
  • X-Perfox-Site: <site_id> — your public Site key. Missing → 400 missing_site_id; unknown → 404 unknown_site; suspended → 403 site_suspended.
  • Origin — must be in the Site's allowed origins, or the request is rejected 403 origin_not_allowed. Browsers set this automatically; a server-to-server caller sets it explicitly.
  • X-Perfox-Device-Proof — a fresh proof signed with your device key, on every request, /init included. See The device proof.
  • X-Perfox-Conversation-Token — on every call that names a conversation (/init resume, /send, /history, /tasks, /tasks/cancel, /file_url, /upload, /upload/<id>, /voice/start, /voice/inject_text, /voice/stop, /call).

The Host is your own API host (example-api.perfox.ai). The host you call is what reaches your workspace, so there's no workspace id to put in the body. Your data stays private to your workspace.

The conversation token ​

Every response that hands back a conversation_id — /init, /send, /history, /voice/start, each row of /conversations, and /conversations/new — also carries a conversation_token. Keep it next to the id and send the newest one on every call that names that conversation. Tokens last 30 days and are re-issued on every response.

The conversation id on its own is not a key: a call that names a conversation without its token is refused 401 conversation_token_required; a wrong or expired token is 403 conversation_token_invalid. Recover from either by re-running /init.

The device proof ​

A conversation continues only from the same browser on the same device. Knowing a conversation id, or even copying its token, is useless anywhere else — because every request must also be signed by the key the conversation was started with.

The key. Create one ECDSA P-256 key pair per browser (or app install) as non-extractable, and keep it — in a browser, IndexedDB keeps a CryptoKeyPair without ever exposing its private half. Browsers offer this signing API only on secure (https://) pages, so a chat on an http:// page can't prove a device and every request is refused.

The proof is a compact JWS (three base64url parts joined by dots), signed ES256 with the raw r‖s signature WebCrypto produces:

PartContent
Header{ "typ": "perfox-device-proof+jwt", "alg": "ES256", "jwk": { "kty": "EC", "crv": "P-256", "x": "…", "y": "…" } } — your public key
htmThe HTTP method (GET, POST)
htuThe absolute URL you're calling. Only its path is compared, so proxies and custom domains are fine
iatNow, in Unix seconds. Proofs more than 120 seconds off the server's clock are refused
jtiA unique id for this proof (8–128 characters). Each proof is accepted once — sign a new one per request
cidThe conversation the request names (omit when it names none, for example a first /init)
athbase64url SHA-256 of the conversation token the request carries (omit when it carries none)
js
// Once per browser. Store `key` in IndexedDB so a reload keeps the SAME key (and the same conversation).
const key = await crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-256' }, false, ['sign', 'verify']);
const pub = await crypto.subtle.exportKey('jwk', key.publicKey);          // the PUBLIC half only
const jwk = { kty: pub.kty, crv: pub.crv, x: pub.x, y: pub.y };

const b64url = (buf) => btoa(String.fromCharCode(...new Uint8Array(buf)))
  .replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
const b64url_json = (obj) => b64url(new TextEncoder().encode(JSON.stringify(obj)));
let clock_offset_s = 0;   // learned from a `stale` refusal, see below

async function device_proof(method, url, conversation_id, token) {
  const header = { typ: 'perfox-device-proof+jwt', alg: 'ES256', jwk };
  const payload = {
    htm: method,
    htu: new URL(url, location.href).toString(),
    iat: Math.floor(Date.now() / 1000) + clock_offset_s,
    jti: crypto.randomUUID(),
    ...(conversation_id ? { cid: conversation_id } : {}),
    ...(token ? { ath: b64url(await crypto.subtle.digest('SHA-256', new TextEncoder().encode(token))) } : {}),
  };
  const input = `${b64url_json(header)}.${b64url_json(payload)}`;
  const sig = await crypto.subtle.sign({ name: 'ECDSA', hash: 'SHA-256' }, key.privateKey, new TextEncoder().encode(input));
  return `${input}.${b64url(sig)}`;
}

A native app does the same with its platform's key store (a P-256 key that can sign but not be exported).

Refusals. A missing or bad proof is 401 with this body:

json
{ "error": "device_proof_invalid", "reason": "stale", "server_time_ms": 1793000000000,
  "message": "This request must be signed by the browser that started the conversation. Reload the widget to start a new one." }

reason is one of missing, malformed, bad_signature, stale, wrong_request, wrong_conversation, token_mismatch or replayed; a temporary inability to check is 503 with reason: "unavailable". A token presented with a different key's proof is 403 conversation_token_invalid.

  • stale means the device's clock is off. Set clock_offset_s from server_time_ms and retry once.
  • Anything else: re-run /init. With the same key you resume the same conversation; with a different key you start a fresh one.

Put together, one helper makes every call:

js
const API  = 'https://example-api.perfox.ai';        // your API host
const SITE = 'sa_site_live_xxxxxxxxxxxxxxxx';      // your Site key
const tokens = {};                                   // conversation_id → newest conversation_token

async function widget(method, path, { conversation_id, body } = {}, retried = false) {
  const url = `${API}/api/public/widget${path}`;
  const token = conversation_id ? tokens[conversation_id] : undefined;
  const headers = { 'X-Perfox-Site': SITE, 'X-Perfox-Device-Proof': await device_proof(method, url, conversation_id, token) };
  if (token) headers['X-Perfox-Conversation-Token'] = token;
  if (body) headers['Content-Type'] = 'application/json';
  const res = await fetch(url, { method, headers, ...(body ? { body: JSON.stringify(body) } : {}) });
  const data = await res.json().catch(() => ({}));
  if (res.status === 401 && data.error === 'device_proof_invalid' && data.reason === 'stale' && !retried) {
    clock_offset_s = Math.round(data.server_time_ms / 1000 - Date.now() / 1000);
    return widget(method, path, { conversation_id, body }, true);   // once
  }
  if (data.conversation_id && data.conversation_token) tokens[data.conversation_id] = data.conversation_token;
  return { status: res.status, data };
}

Identity (optional) — sign user_hash on your server ​

Every conversation starts anonymous. Anonymous chat needs none of this. When your visitor is signed in to your app and you want Perfox to trust who they are — so they can list their past chats, and so nobody else can claim their identity once you require verification — the identity must be verified with an HMAC your server computes:

js
// On YOUR server — never in the browser (the secret would leak).
import { createHmac } from 'node:crypto';

function sign_identity(site_id, external_id, raw_site_secret) {
  return createHmac('sha256', raw_site_secret)
    .update(`${site_id}.${external_id}`)   // canonical string: "<site_id>.<external_id>"
    .digest('hex');
}

The canonical string is exactly <site_id>.<external_id>; the key is the raw site secret (sa_secret_live_…). Hand the resulting hex to the client, which passes it as the identity's user_hash field on /init, /send, and the voice, dial-out and upload calls.

The identity itself is a user-context object — all fields optional: name (display only), phone, email, external_id (the stable customer anchor and the field HMAC signs), attributes (a free-form string→string map), user_hash, and tenant_session_token. Perfox resolves the trust level from what you send: no identity at all (no external_id, email or phone) → anonymous; external_id + valid user_hash → verified; any other identity (an external_id without user_hash, or just an email or phone) → self_asserted, unless the site's Require HMAC identity verification toggle is on (then rejected 403 identity_verification_required). A hash that matches no secret is rejected 403 identity_verification_failed. The full multi-language signing spec and secret rotation are on Identity Verification (HMAC); the field set and its forwarding to your MCP tools are on User Context & Identity.

Step 1 — POST /init ​

Resolve the agent and the conversation, and learn what capabilities it offers.

js
const saved = JSON.parse(localStorage.getItem('perfox_conversation') ?? 'null');   // resume after a reload (optional)
if (saved) tokens[saved.id] = saved.token;

const { data: init } = await widget('POST', '/init', {
  conversation_id: saved?.id,                       // the proof's `cid` + the token header come with it
  body: {
    ...(saved ? { conversation_id: saved.id } : {}),
    locale: navigator.language,                     // lets the agent answer in the visitor's language
    user_context: { name: 'Priya Sharma', external_id: 'cust_abc123' /*, user_hash */ },
  },
});

// → { conversation_id, conversation_token, customer_id, workflow_id, auth_level,
//     capabilities: { voice_chat, dial_out, file_upload, show_history, allow_new_chat, allow_export },
//     capability_warnings, ui, starters?, input_placeholder?, next_actions_enabled }
const conversation_id = init.conversation_id;
localStorage.setItem('perfox_conversation', JSON.stringify({ id: conversation_id, token: tokens[conversation_id] }));

Optional body fields: conversation_id (resume a conversation you were given earlier — an anonymous visitor resumes only an anonymous conversation, an identified one only their own), workflow_id (pin a specific published agent; otherwise the agent the Site is bound to answers), locale, and user_context. An identified visitor with no conversation_id resumes their open web conversation if they have one.

The conversation itself is created on the first /send, so opening the chat never leaves an empty conversation behind. Gate any voice, call, or attach UI on init.capabilities, and render ui (display name, avatar, colour, greeting, starters) however you like.

Step 2 — open the reply WebSocket ​

Open this before the first async send, so the reply has somewhere to land.

js
const ws_url = `${API.replace(/^http/, 'ws')}/api/chat/connect?site_id=${SITE}&conversation_id=${conversation_id}`;
const proof = await device_proof('GET', ws_url, conversation_id, tokens[conversation_id]);
const ws = new WebSocket(ws_url, ['perfox-widget.v1', `pct.${tokens[conversation_id]}`, `ppf.${proof}`]);

Why the token and proof are subprotocols. A browser can't set custom headers on a WebSocket upgrade. site_id and conversation_id ride in the URL; the conversation token (pct.<token>) and a device proof signed for this URL and conversation (ppf.<proof>) ride as subprotocols, so neither ever lands in a URL. The upgrade runs the same Origin + Site verification: a missing param is 400; a bad origin or unknown site is 403; a missing or invalid token is 401 / 403, and a missing or invalid proof is 401. The conversation id alone opens nothing.

The socket is receive-only — bound to the one conversation from the handshake; anything you send on it is ignored. The server sends a keep-alive { "type": "ping" } frame every 30 seconds or so. If you hear nothing at all for about 75 seconds, treat the socket as dead, reconnect (with a fresh proof), and use the fallback poll.

Step 3 — POST /send with delivery: "async" ​

js
async function send(text) {
  render_user_bubble(text);                       // optimistic echo

  const { status, data: ack } = await widget('POST', '/send', {
    conversation_id,
    body: { conversation_id, customer_id: init.customer_id, text, delivery: 'async' },
  });

  // → 202 { accepted: true, message_id, reply_id, server_time, conversation_id, conversation_token }
  // → or 202 { accepted: true, held_by_operator: true, message_id, server_time } (no reply_id)
  // → or 409 { error: 'conversation_closed' } — see "When a conversation closes" below
  if (ack.reply_id) pending.add(ack.reply_id);     // remember it to match the WS frame
}

The reply is pushed over the WebSocket and correlated by reply_id. If the ack carries held_by_operator: true instead, a person on your team has taken over the conversation: no AI turn runs, and their answer arrives later as an unsolicited reply frame. Delivery is cross-node safe — the turn may run on a different backend than the one holding your socket, and the reply still finds its way to the right open socket.

Other /send body fields: user_context (send the identity on every call), workflow_id, locale, file_refs (see Upload), and structured_data (the machine-readable values from an interactive input, alongside the human-readable text).

Use delivery: "async" only while the socket is open. Omit delivery (or send "sync") for a server-to-server caller with no socket: the request then blocks and returns { text, message_id } in the 200 body (plus attachments, charts, cards, rich or suggested_actions when present). It can also fail with 503 workflow_provisioning or 500 workflow_execution_failed.

Step 4 — render the pushed frames ​

The socket carries several frame types. Handle the ones you need and ignore any type you don't recognise:

js
let streaming = '';
ws.onmessage = (ev) => {
  let frame;
  try { frame = JSON.parse(ev.data); } catch { return; }
  switch (frame.type) {
    case 'reply_delta':                        // text so far, while the agent is still writing
      streaming += frame.text;
      render_streaming_bubble(streaming);
      break;
    case 'reply':
      if (frame.unsolicited) { render_agent_bubble(frame); break; }   // a message nobody asked for
      if (!pending.has(frame.reply_id)) break;
      pending.delete(frame.reply_id);
      streaming = '';
      render_agent_bubble(frame);              // the final text REPLACES the streamed preview
      break;
    case 'error':
      if (!pending.has(frame.reply_id)) break;
      pending.delete(frame.reply_id);
      streaming = '';
      render_error(frame.text);                // frame.code: workflow_provisioning | workflow_execution_failed
      break;
    case 'suggested_actions':                  // follow-up chips for the reply you just rendered
      attach_chips(frame.reply_id, frame.suggested_actions);
      break;
    // 'task_status', 'ui:command' and 'ping' — see below
  }
};

The frame shapes are:

jsonc
// streamed preview — zero or more per turn; append in order
{ "type": "reply_delta", "text": "…" }

// the finished turn — ONE per assistant turn; authoritative
{ "type": "reply", "reply_id": "…", "text": "…",
  "attachments": [ /* files */ ],             // each key present only when non-empty
  "charts": [ … ], "cards": [ … ],
  "rich": [ /* ordered blocks: cards | table | compare | detail | chart */ ],
  "suggested_actions": [ "…" ] }

// a server-initiated message (for example a follow-up after login) — no reply_id to match
{ "type": "reply", "unsolicited": true, "text": "…" }

// failure
{ "type": "error", "reply_id": "…", "code": "workflow_execution_failed", "text": "…" }

// follow-up chips, sent after the reply they belong to
{ "type": "suggested_actions", "reply_id": "…", "suggested_actions": [ "…" ] }

Streaming is a preview: the final reply frame always carries the complete text, so if you'd rather not stream, ignore reply_delta. When rich is present, render it instead of charts and cards.

Two more frame types exist for richer clients. task_status reports a background job the agent started (for example "Reading your document") with task_key, status and label — show a status chip, and disable input while a blocking task is open. ui:command carries a command for the host page; see UI-command bus.

Step 5 — the fallback poll ​

A push can be missed. Make delivery self-healing by polling /history while a reply_id is still pending:

js
async function poll_history() {
  const { data: page } = await widget('GET', `/history?conversation_id=${conversation_id}&limit=20`, { conversation_id });
  // page → { messages, has_more, next_before, conversation_id, conversation_token }
  reconcile(page.messages);   // upsert by id — the awaited assistant turn appears here too
}

limit defaults to 20 (maximum 200). Page backwards for scroll-up by passing the previous next_before as before. The same endpoint replays the whole transcript when you resume a conversation after a reload.

When a conversation closes ​

A person closed it. If someone on your team closes the conversation (a wrap-up, or resolving it on Cases) while your client still holds it, /send, /voice/start and /upload answer 409 { "error": "conversation_closed" }. Re-run /init with the closed conversation_id: Perfox decides where to continue — an identified visitor's own open conversation, or a fresh one — and returns the new id and token. Send the message again there; files you uploaded for the closed conversation don't carry over, so ask the visitor to attach them again.

It went quiet. A web-only chat that has been quiet for 5 minutes — no live call, no waiting for a person, no step waiting for a reply, no background task still running — is closed quietly; nothing is sent to the visitor. If the same visitor comes back within 24 hours, /init with that conversation_id (and its token, from the same browser) resumes it with its history, and their next /send reopens it: same thread, same agent memory. Nothing to build — just keep the id and token as above. A conversation closed by a person is never reopened this way.

Rate limits ​

Per client IP and minute, the widget routes accept 240 requests together; /upload and /transcribe (which accept up to 25 MB each) are additionally limited to 30. Over a limit you get 429 with an X-RateLimit-Reset header (Unix seconds). If the limiter is briefly unavailable, /upload and /transcribe answer 503 while chat keeps working — retry shortly.

Worked example — Priya asks about her test results ​

Setup. Asha, an admin at Acme Diagnostics, has configured a Web Chat trigger with file upload enabled. The agent can look up lab reports through Acme's own MCP tools.

Action. Priya opens the Acme Diagnostics chat — a custom native iOS app built on this protocol. On first launch the app created its device key in the iOS key store. Behind the scenes it calls /init with external_id: "cust_abc123" and a user_hash signed on Acme's server, keeps the returned conversation token, opens the WebSocket, and then she types: "Can you tell me about my last blood panel?"

Result. The /send call returns a 202 within milliseconds. The answer streams in over the socket, then a reply frame delivers the final text and an attachments array containing a signed link to her PDF report. The app renders the bubble and the download button without polling.

What just happened. Because Acme's server signed Priya's identity, Perfox accepted cust_abc123 as genuine and forwarded it to Acme's tools, which returned her report. Every request was signed with the app's device key, so even if someone copied the conversation id and token off her phone, they couldn't continue the chat from another device. The agent composed its reply and the socket delivered it — first as a live preview, then as one complete frame.

Upload ​

Attaching a file is two steps: upload it, then send it with a message.

POST /api/public/widget/upload (multipart, with the same X-Perfox-Site, Origin, device proof and conversation token headers) accepts one file field (up to 25 MB) plus conversation_id, and optionally customer_id, workflow_id and user_context (as a JSON string). It's gated by the Web Chat trigger's Enable file upload switch plus a prerequisite check — off → 403 file_upload_not_enabled (and 503 no_workflow_configured / file_upload_prereq_failed / missing_credential when uploads aren't ready); an unsupported type → 400 unsupported_type. The file is stored privately and its content extracted by type: images → vision, PDF/Word/Excel → vision/OCR/structured extraction, audio → transcription, video → frames + audio, text formats → read as-is. The response is { upload_id, file_id, file_name, file_url, file_key, mime_type, status: "ready" }.

Then send it: POST /send { conversation_id, text, file_refs: ["<upload_id>"], … } — up to 5 files per message, and text may be empty. A file that isn't ready yet makes /send return 409 attachments_not_ready; check it with GET /api/public/widget/upload/<upload_id>?conversation_id=<id>. See File Upload.

Voice ​

Voice is not on this WebSocket. Both voice capabilities are opt-in, gated by a Web Chat trigger switch plus a prerequisite check, and reported in /init capabilities (with capability_warnings when a switch is on but something it needs is missing).

  • Browser voice (Enable voice chat): POST /api/public/widget/voice/start { conversation_id, user_context } returns { livekit_url, livekit_token, room_name, voice_session_id, voice_mode, voice_animation_style } plus the conversation token. Get microphone permission before you call it. /voice/inject_text { voice_session_id, text } (up to 8,000 characters) pushes a typed turn into the call; /voice/stop { voice_session_id } ends it. Both must carry the conversation token of the conversation the call runs in — a caller that doesn't hold it is refused, and a session id from somewhere else is 404 voice_session_not_found. Disabled → 403 voice_chat_not_enabled.
  • Outbound dial-out (Enable dial-out (Call Me)): POST /api/public/widget/call { phone_number, conversation_id, customer_id, user_context } places an outbound phone call using the same persona and tools and returns { call_id, status: "calling", phone }. An undialable number → 400 invalid_phone_number; disabled → 403 dial_out_not_enabled.

You join the real-time voice session with the URL and token from /voice/start using a LiveKit client SDK for your platform, publish the microphone, and read captions off the session's data channel (topic transcript). The raw caption frame is:

jsonc
{ "type": "transcript",
  "speaker": "user" | "assistant",   // raw wire field is `speaker` (the library renames it `role`)
  "text": "…",
  "partial": true }                  // true = live delta (append); false = consolidated turn-end (replace)

The same channel also carries session_event frames — for example agent_ready when the greeting has finished (unmute the mic then), agent_busy / agent_idle while the agent looks something up, and conversation_ended when the agent ends the call.

Note the field is speaker here, where the headless library's transcript event uses role. Same values (user / assistant); the library normalizes the name. See Voice & Dial-Out.

You can now build a full custom conversation experience ​

You know how to open a conversation, prove the device and the identity, send messages, receive replies, handle missed pushes and closed conversations, attach files, and start a voice session — all without any Perfox JavaScript dependency.

Where to go next:

  • Overview (3 tiers) — see where this tier fits relative to the drop-in widget and the headless library, and decide whether you still need the raw protocol.
  • Headless Library (@perfox/widget-core) — if you're on a JavaScript platform, this implements everything above for you and saves the wiring.
  • Public Widget API — the full endpoint and frame schemas, for when you need every field documented precisely.
  • Identity Verification (HMAC) — multi-language signing examples and secret rotation, so you can implement the user_hash step in any backend language.
  • User Context & Identity — the full user-context field set and how trust levels work.
  • File Upload — upload limits, extraction details, and what the agent sees.
  • Voice & Dial-Out — voice modes and the complete voice lifecycle.