Skip to content

Public Widget API ​

You've built your own chat UI — or a mobile screen — and now you need to know exactly what to call. This page documents every HTTP and WebSocket endpoint the Perfox widget speaks, so you can drive the same AI conversation from any client.

The prebuilt widget calls all of these for you automatically. This reference is for the case where you replace the widget with your own chat UI and talk to Perfox directly.

Mount points ​

Every endpoint lives under /api/public/widget on your workspace's API host, https://<your-workspace>-api.perfox.ai:

Method + pathPurpose
POST /api/public/widget/initOpen a session, resolve the agent, return capabilities.
POST /api/public/widget/sendSend a visitor message and run the agent.
GET /api/public/widget/historyPage the transcript.
GET /api/public/widget/conversationsList a verified visitor's past conversations.
POST /api/public/widget/conversations/newStart a fresh conversation.
POST /api/public/widget/uploadUpload a file.
GET /api/public/widget/upload/{upload_id}Check an upload's processing status.
POST /api/public/widget/file_urlRe-sign a stale media URL.
POST /api/public/widget/transcribeTurn a recorded voice note into text.
GET /api/public/widget/tasksList a conversation's open background tasks.
POST /api/public/widget/tasks/cancelCancel one of them.
POST /api/public/widget/voice/startOpen a browser voice session.
POST /api/public/widget/voice/inject_textPush a text turn into a live voice session.
POST /api/public/widget/voice/stopEnd a voice session.
POST /api/public/widget/callAsk the agent to phone the visitor.

All of these accept cross-origin requests (any origin, no cookies). Replies can also be pushed to the browser over a WebSocket at /api/chat/connect — a separate mount, because it is the delivery channel rather than a resource.

Authentication ​

Every request carries these headers — every widget endpoint checks them:

  • X-Perfox-Site: sa_site_live_… — your public site ID.
  • Origin: https://your-allowed-origin — must match your site's allowed-origins list (case-insensitive exact match; a missing Origin is rejected).
  • X-Perfox-Device-Proof: <proof> — a short-lived proof signed by the visitor's browser (see Device proof). Required on every request, /init included.
  • X-Perfox-Conversation-Token: <token> — on every call that names a conversation (see below).

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 beside the id and send it as X-Perfox-Conversation-Token on every call that names the conversation: /init (when resuming), /send, /history, /tasks, /tasks/cancel, /file_url, /upload, /upload/{upload_id}, /voice/start, /voice/inject_text, /voice/stop and /call.

  • Missing → 401 conversation_token_required. Wrong, expired, or presented with another browser's proof → 403 conversation_token_invalid. Recover by running /init again.
  • A token lasts 30 days and is re-issued on every response — always keep the newest.
  • The conversation id alone is not a credential: without the token (and the matching proof) nobody can read or write the conversation.

Device proof ​

A conversation continues only from the browser that started it. Your client creates one ECDSA P-256 key per browser and site (with WebCrypto, non-extractable, so it can sign but never be copied), keeps it, and signs a fresh proof for every request. The proof is a compact JWS:

PartContent
Header{ "typ": "perfox-device-proof+jwt", "alg": "ES256", "jwk": <the public key> } — the signature is raw r‖s, as WebCrypto produces it
htmThe HTTP method
htuThe request URL — only its path is compared, so proxies and custom domains work
iatSeconds since the epoch; must be within ±120 seconds of server time
jtiA random id, 8–128 characters, used once
cidThe conversation the request names, when it names one
athbase64url SHA-256 of the conversation token the request sends, when it sends one

Each conversation token is bound to the key that first proved it, so a token copied to another browser or device is refused.

A bad proof answers 401:

json
{ "error": "device_proof_invalid", "reason": "stale", "server_time_ms": 1761900000000, "message": "…" }

reason is one of missing, malformed, bad_signature, stale, wrong_request, wrong_conversation, token_mismatch or replayed. On stale (the visitor's clock is off), re-base on server_time_ms and retry once. When the check itself is briefly unavailable the status is 503 with reason: "unavailable".

Use the headless library

Browsers only expose WebCrypto on https:// pages, so a page served over plain http:// cannot prove a device. The headless library creates the key, signs every request and keeps the newest token for you; From Scratch shows the same thing by hand.

Identity ​

The identity level Perfox assigns depends on the user_context you send:

Sent in user_contextResulting auth_level
no external_id, email or phoneanonymous
external_id + a valid user_hashverified
external_id without user_hash, or only an email / phoneself_asserted — accepted, but treated as a new visitor: it never resolves to or resumes an existing customer. If your site's Require HMAC identity verification setting is on, the request is rejected instead

Only a verified identity identifies anyone, whether or not the setting is on. The signed external_id is what picks the customer; an email or phone sent beside it — or typed by the visitor in chat — is kept for display but never picks or changes a customer.

The user_hash is an HMAC-SHA256 of the canonical string <site_id>.<external_id>, keyed with your site secret (sa_secret_live_…), and is checked against every active and expiring secret. See Identity Verification.

POST /send — sending a message ​

The body carries the message and the conversation it belongs to:

FieldWhat
conversation_idThe conversation from /init (or /conversations/new).
customer_idThe customer from /init.
textThe visitor's message. May be empty only when file_refs is present.
file_refsUp to 5 upload_ids from /upload to attach to this message.
user_contextThe visitor's identity (and user_hash), re-checked on every send.
deliveryasync to get 202 and the reply over the WebSocket; omit (or sync) to get the reply in the HTTP response.

Synchronous (the default): the response body is the reply — { "text", "message_id" } plus attachments, charts, cards, rich and suggested_actions when the reply has them.

Asynchronous ("delivery": "async"): the request returns 202 Accepted immediately, freeing the connection:

json
{ "accepted": true, "message_id": "…", "reply_id": "…", "server_time": "…" }

The reply is then pushed over the WebSocket, tagged with the same reply_id. Open the socket before you send. The message:received SDK event fires when the push lands.

While a background task in the conversation is still running and blocking input, /send returns 409 task_in_progress with the task's label.

If the conversation has been closed, /send (like /voice/start and /upload) returns 409 conversation_closed. The body never names another conversation — run /init again, and it decides where to continue (a conversation that closed only because it sat idle can be picked up again).

When a person on your team has taken over the chat, /send records the message for them and the AI doesn't answer. The response is 202 with "held_by_operator": true and no reply_id, because there's nothing to wait for. Their answer arrives later over the WebSocket as an unsolicited reply:

json
{ "accepted": true, "held_by_operator": true, "message_id": "…", "server_time": "…" }

GET /connect (WebSocket) — reply push ​

wss://<your-workspace>-api.perfox.ai/api/chat/connect?site_id=…&conversation_id=…

Why credentials ride where they do. Browsers can't set custom headers like X-Perfox-Site on a WebSocket upgrade, so site_id and conversation_id ride as query params, and the Origin is read from the upgrade headers. The conversation token and the device proof travel as subprotocols, never in the URL:

js
new WebSocket(url, ['perfox-widget.v1', `pct.${conversation_token}`, `ppf.${device_proof}`])

Sign the proof for GET and the socket URL's path, with cid set to the conversation. The server selects perfox-widget.v1. user_hash is deliberately never in the URL — identity was already proven at /init and /send; the socket only receives.

Upgrade gate (checked before the socket opens):

  • Missing site_id or conversation_id → rejected with 400.
  • Site or Origin check fails → rejected with 403.
  • A failed device proof → 401 (503 when the check is briefly unavailable).
  • A missing conversation token → 401; an invalid one → 403.

Receive-only. The socket is bound to the one conversation from the handshake; there is no join message and anything the client sends is ignored. If authorization is lost after connecting, the socket closes with code 1008. The server sends a { "type": "ping" } frame every 30 seconds to keep the connection alive — ignore it, but treat any frame as proof the socket is healthy, and reconnect if nothing at all arrives for about 75 seconds (a half-open connection can still report itself as open).

Frames the server pushes:

jsonc
// streamed text while the agent is still writing (see "Streaming" below)
{ "type": "reply_delta", "text": "<next chunk>" }

// the finished turn — authoritative
{ "type": "reply",
  "reply_id": "<the id from the 202>",
  "text": "<assistant text>",
  "attachments":       [ /* … */ ],  // optional arrays, present ONLY when non-empty
  "charts":            [ /* … */ ],
  "cards":             [ /* … */ ],
  "rich":              [ /* … */ ],
  "suggested_actions": [ /* … */ ] }

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

// the turn failed
{ "type": "error",
  "reply_id": "<same reply_id>",
  "code": "workflow_provisioning" | "workflow_execution_failed",
  "text": "<human-readable message>" }

A reply with "unsolicited": true was started by the platform rather than by a /send — for example a follow-up after the visitor signs in, a human agent taking over, or that person's typed answer on a chat they've taken over. It has no pending request to match; render it as a new assistant message. task_status frames report background-task progress, and ui:command frames carry page commands for sites that have enabled them.

Failure code workflow_provisioning means the agent's dedicated capacity is still starting up; workflow_execution_failed means the turn failed to run.

GET /history — transcript pagination ​

GET /api/public/widget/history?conversation_id=…&limit=20&before=…
Query paramDefaultMeaning
conversation_id— (required; absent → 400)The conversation to page.
limit20Page size, capped at 200.
before—ISO-timestamp cursor: returns only messages strictly older than it. An invalid cursor is ignored (you get the newest page), not a 400.

Each call returns the most recent limit messages older than the cursor, in chronological order (oldest first within the page). Visitor messages, agent replies, human-agent messages and uploaded files are included; tool activity and internal status events are not. Each message has id, role (user or assistant), text and timestamp, plus attachments and any rich content it had.

json
{ "messages": [ … ], "has_more": true, "next_before": "2026-06-25T09:29:12.000Z" }

Page backwards by passing next_before as the next before, and stop when has_more is false. Media links are re-signed as they are read, so an old attachment still opens.

GET /conversations and POST /conversations/new ​

GET /api/public/widget/conversations lists a returning visitor's past conversations (newest first, limit default 30, max 100), each with conversation_id, title, preview and updated_at. Pass the visitor's external_id and user_hash as query parameters. Only a verified visitor gets a list, looked up by the signed external_id alone (an extra phone or email never widens it) — anyone else gets { "conversations": [] }, so one visitor can never list another's conversations.

POST /api/public/widget/conversations/new with { "user_context": … } closes the visitor's open conversation and returns a fresh { "conversation_id", "customer_id" }.

POST /file_url — re-sign a media URL ​

Media URLs expire; the durable file_key does not. Refresh a stale URL without an admin session:

POST /api/public/widget/file_url
{ "conversation_id": "…", "file_key": "…" }   →   { "url": "…" }

The key must belong to the named conversation (or be a downloadable Knowledge Base file), so a visitor can only refresh media they were shown. Anything else returns 403 forbidden.

POST /upload — file upload ​

POST /api/public/widget/upload is a multipart request with one file field of up to 25 MB, plus optional conversation_id, customer_id and workflow_id. Perfox decides the file type from its extension, never from the type the browser reports, and refuses active content — HTML, SVG, XML and JavaScript files. An unsupported file type returns 400 unsupported_type; more than 5 files still processing in one conversation returns 400 too_many_files.

The endpoint is gated by the Web Chat trigger's Enable file upload toggle. If it's off you get 403 file_upload_not_enabled; it fails with 503 no_workflow_configured, file_upload_prereq_failed or missing_credential when uploads are not ready to use.

The file is stored (nothing to configure on your side) and its content is extracted so the agent can read it — images are analysed, documents and spreadsheets are read, audio is transcribed, video is described. The response:

json
{ "upload_id": "…", "file_id": "…", "file_name": "…", "file_url": "…", "file_key": "…", "mime_type": "…", "status": "ready" }

Attach the file to a message by sending its upload_id in file_refs on /send (a file still processing gives 409 attachments_not_ready — wait and resend). GET /api/public/widget/upload/{upload_id}?conversation_id=… returns its status, parsed_chars, and — once written — a short summary (or an error_message if processing failed). Very long documents are also indexed, so the agent can search them instead of reading them whole. Full reference: File Upload.

POST /transcribe — voice notes ​

Send a recorded clip as a multipart file (an audio/* type, up to 25 MB) and get { "transcript": "…" } back, ready to put in the message box. A non-audio file returns 400 not_audio; silence returns 422 empty_transcript.

GET /tasks and POST /tasks/cancel ​

Some agent actions run in the background and show a progress card. GET /api/public/widget/tasks?conversation_id=… returns { "tasks": [...] } for the conversation's open tasks, and POST /api/public/widget/tasks/cancel with { "conversation_id", "task_key" } cancels one, returning { "cancelled": true | false }.

Voice — /voice/start, /voice/inject_text, /voice/stop, /call ​

The widget has two opt-in voice capabilities, each gated by a Web Chat trigger toggle plus a prerequisite check. Both surface in /init's capabilities — { voice_chat, dial_out, file_upload, show_history, allow_new_chat, allow_export } — and a capability whose prerequisite fails is switched off there and listed in capability_warnings.

Browser voice chat — the Enable voice chat toggle:

  • POST /api/public/widget/voice/start returns livekit_url, livekit_token, room_name and voice_session_id, plus voice_mode and voice_animation_style (how the widget should draw the session). The browser joins the room directly with the LiveKit client SDK.
  • POST /api/public/widget/voice/inject_text with { voice_session_id, text } pushes a text turn into the live session — for example the contents of a file uploaded mid-call. text is at most 8,000 characters (longer → 413).
  • POST /api/public/widget/voice/stop with { voice_session_id } ends the session and saves the recording.

Both must carry the call's conversation token; a voice_session_id that isn't from your workspace returns 404 voice_session_not_found.

voice/start can also return 403 voice_chat_not_enabled, 503 voice_chat_prereq_failed, 402 out_of_credits, or 429 concurrent_voice_limit_reached when too many voice sessions are already running. Recordings (caller, agent and a combined stereo mix) are stored for you — nothing to configure.

Dial-out — the Enable dial-out toggle:

  • POST /api/public/widget/call with { phone_number, conversation_id, customer_id, user_context } places a phone call to the visitor with the same persona and tools, and returns { call_id, status: "calling", phone }. The number is normalised for you (India is assumed when there's no country code). Disabled → 403 dial_out_not_enabled; a bad number → 400 invalid_phone_number.
  • There is no default caller number. The call is placed from the number on the agent's own Phone Call trigger, through the connected Plivo account that holds it. If the agent has no such number, or it isn't on any connected account, dial-out is switched off at /init and /call returns 503 dial_out_prereq_failed with a remediation; your workspace is also notified. 503 missing_credential means no Plivo connection was found when dialling.
  • Before anything is dialled: the number must be in a country Perfox may call (India by default) and must not be a premium-rate or special-rate number — otherwise 403 country_not_allowed or 403 premium_rate_destination. Calls are limited to 3 per hour per visitor IP, 3 per hour per destination number, 10 per hour per site and 50 per day for your workspace (429 rate_limited; 503 limiter_unavailable if the limit can't be checked). Your workspace must have credit (402 out_of_credits).

Full lifecycle: Voice & Dial-Out.

Streaming — text and voice ​

Text. How a text reply arrives is set on the Web Chat trigger's Response delivery option:

  • Stream as written (the default) — over the WebSocket, reply_delta frames carry the reply as the agent writes it. Append each text chunk to a live bubble. When the finished reply frame arrives, replace the bubble's text with the reply's text: the final frame is authoritative, and it can differ from what streamed (for example when personal details were masked at the end of the turn).
  • Send complete reply — no deltas; one reply frame per answer, with any table or chart validated first.

Streaming needs the WebSocket, so it only happens with "delivery": "async". A turn can also fall back to a single complete reply when the agent's settings require the whole answer to be checked before it is shown. Either way, a client that ignores reply_delta and renders only reply frames still works.

Voice. Voice transcripts never come over the chat WebSocket. After /voice/start, each transcript is sent on the voice room's data channel under the transcript topic:

jsonc
{ "type": "transcript",
  "speaker": "user" | "assistant",   // note: `speaker`, not `role`
  "text": "…",
  "timestamp": 1750000000000,
  "partial": true }                  // true = live delta (render, then replace); false = consolidated turn-end

Render partial: true deltas as a live caption and replace them when the consolidated partial: false frame for the turn arrives.

Worked example — a visitor sends a message ​

Acme Support has a custom chat UI built against this API. Here's what happens when Priya, a customer, types "What's the status of my return?" and presses send:

Setup. Asha, the Acme Support admin, left the Web Chat trigger's Response delivery on Stream as written. Priya's browser opened the WebSocket at /api/chat/connect when the chat panel opened.

Action. Priya's UI calls POST /api/public/widget/send with her message, conversation_id, "delivery": "async" and a user_hash proving she's a verified user. The server answers 202 Accepted with a reply_id.

Result. Within a couple of seconds reply_delta frames start arriving and the answer appears word by word. Then a reply frame lands with the same reply_id and the final text: "Your return is in transit and expected by Thursday." Priya's UI swaps in the final text.

What just happened. The 202 freed the HTTP connection immediately, the deltas let Priya see the answer begin before it was finished, and the reply_id on the final frame tied it to her message.

Rate limits ​

Per visitor IP, per minute: 240 requests across the widget endpoints, and separately 30 for /upload and 30 for /transcribe. Over a limit you get 429 with an X-RateLimit-Reset header. If the limiter is briefly unavailable, /upload and /transcribe answer 503; the other endpoints stay open.

Error codes ​

HTTPCodeMeaning
400missing_site_idX-Perfox-Site header absent.
404unknown_siteNo site with that ID.
403site_suspendedThe site is suspended.
403origin_not_allowedOrigin not in your allowed-origins list.
403identity_verification_requiredAn external_id, email or phone supplied without a valid signed external_id on a site that requires it.
403identity_verification_faileduser_hash didn't match any active or expiring secret.
401device_proof_invalidThe device proof is missing or invalid (reason says why; 503 when the check is unavailable).
401conversation_token_requiredA call that names a conversation sent no conversation token.
403conversation_token_invalidThe token is wrong, expired, or from another browser. Run /init again.
403voice_chat_not_enabled / dial_out_not_enabled / file_upload_not_enabledThe capability's toggle is off.
409task_in_progressA blocking background task is still running.
409conversation_closedThe conversation was closed. Run /init again.
429—Rate limit reached; see X-RateLimit-Reset.
503no_workflow_configuredThe site is not bound to a published agent.

See also ​

You can now drive a complete conversation — text, voice, and file sharing — from any client against these endpoints. To go further: