You are implementing a typed client for one Finesse Voice API endpoint: "Realtime (WebSocket)".
Everything you need is in this prompt. Do not invent anything that is not specified here.
WHAT TO BUILD
- A RealtimeSession client (name it per the project's conventions) for bidirectional, low-latency
synthesis over one WebSocket:
connect() open the socket
startContext(options) send task_start; returns a context handle
context.append(text, finalize?) send task_continue (finalize: true on the last text)
context.cancel() send task_cancel
end() send session_end and wait for session_ended
plus typed events per context (started, audio, sentence done, done, cancelled, failed, error)
via an async iterator or callbacks, whichever fits the stack.
- Use the stack's standard WebSocket client: the global WebSocket in browsers, the "ws" package in
Node (it can send the X-API-Key header: new WebSocket(url, { headers })), "websockets" >= 14 in
Python (additional_headers=...). Receive binary frames as ArrayBuffer/bytes.
- Detect the stack first: look for package.json, tsconfig.json, pyproject.toml,
requirements.txt, go.mod, Gemfile, composer.json and similar. Use the project's language, HTTP
client, module layout, error-handling conventions and test runner. If there is no project yet or
the stack is unclear, use TypeScript on Node 18+ with the built-in fetch and no new dependencies.
- If the project already has a Finesse API client module, add this to it (reuse its auth, base
URL, error type and retry helper) instead of creating a parallel one.
- Keep the base URL (https://fi.production.flamapis.com) in one constant or config value.
ENDPOINT AND AUTH
- URL: wss://fi.production.flamapis.com/flam-voice-svc/api/v1/public/stream (no key in the URL)
- Auth is a short-lived, single-use access token ("fin_tok_..."), NOT the API key:
1. Server-side, mint a token: POST https://fi.production.flamapis.com/flam-voice-svc/api/v1/public/tokens
with header X-API-Key: <workspace API key> (required scope: tts) and an optional JSON body
{ "ttl_seconds": 300, "voice_ids": ["<voice id>"] } (ttl 10-3600, default 300). The token is
in data.token. Read the key from FINESSE_API_KEY; never log, commit or ship it to a browser.
2. Open the socket with subprotocols ["finesse.v1", token], e.g.
new WebSocket(url, ["finesse.v1", token]). The server selects "finesse.v1".
3. Fallback only for clients that cannot send subprotocols: ...?access_token=<token>
(URL-encode it and redact it from any logged URL).
- The connect() API takes a token, or a getToken() callback that asks the app's server for one.
In a browser, getToken() calls the app's own authenticated route; never embed FINESSE_API_KEY in
client code.
- Server-side clients (Node, Python, Go) can skip tokens and send the API key as a handshake
header instead: X-API-Key: <key from FINESSE_API_KEY> (scope tts). This is not deprecated. If the
module runs in both environments, use the header on the server and tokens in the browser.
Auth precedence if several are sent: subprotocol token, ?access_token, X-API-Key header, ?api_key.
- Tokens are single use: consumed by the handshake. Mint a NEW token for every connect/reconnect;
never cache or reuse one. A token grants tts only and dies if its API key is revoked or expires.
- DEPRECATED: ?api_key=<key> in the URL still works (the handshake response carries
"Deprecation: true" and a Link header to the token docs), but do not implement it: it leaks the
long-lived key into URLs and logs.
- A valid token upgrades the connection (101 Switching Protocols). Handshake failures:
401 code "token_invalid" unknown, expired or already-used token: mint a new token, retry once
401 code "key_expired" the minting key has expired (from POST /tokens): do not retry
403 code "insufficient_scope" the key lacks the tts scope (from POST /tokens): do not retry
402 / 403 plan check (flat body with "error"): do not retry
400 not a WebSocket upgrade request: a client bug
429 code "concurrency_limited" every concurrent stream slot of the workspace is in use (an
open session holds one until it closes): wait Retry-After
seconds, then retry with backoff and a NEW token
429 code "rate_limited" over the plan's requests per second: wait Retry-After, retry
Handshake error bodies are the standard JSON envelope with code and request_id; every handshake
response also carries X-Request-Id, RateLimit-Policy and RateLimit headers.
503 code "upstream_busy": the service is at capacity; wait Retry-After seconds and retry
Browsers do not expose the handshake status; treat a close before "open" as a connect failure
and retry once with a fresh token.
- The service dials the synthesis engine only after the upgrade. If it cannot be reached, the first
frame is a fatal error frame with code "upstream_unavailable" and the socket closes with 1013:
a retryable connect failure (new token, backoff).
- The handshake also checks the plan BEFORE upgrading: 403 if streaming is not included in the
plan, 402 if the character quota is exhausted (when billing enforcement is active). The
handshake response carries X-Billing-Remaining (remaining characters). Surface these as distinct
connect errors; do not auto-reconnect on 401, 402 or 403.
VOICE IDS
- Always send your own Flam voice ids (the 24-character hex ids from
GET https://fi.production.flamapis.com/flam-voice-svc/api/v1/public/voices, whose voices are in data.voices). The service replaces voice_id with
the enrolled engine voice on the frames you send. Only JSON text frames of the four documented
types are forwarded; any other frame is dropped with a non-fatal "invalid_message" error frame.
Frames from the engine are forwarded verbatim.
- An unknown or unenrolled voice returns an error frame with code "voice_not_found" (not billed).
- If the token was minted with voice_ids, a task_start for any other voice gets a NON-FATAL error
frame with code "voice_not_allowed"; fail just that context, the session continues.
SESSION MODEL
- One connection is one session. A session can run up to 4 CONCURRENT contexts (independent
synthesis streams), each keyed by a client-chosen context_id that is unique within the session.
Enforce the limit of 4 open contexts client-side and generate unique ids (e.g. a counter or UUID).
- Start a context, optionally keep appending text (ideal for LLM output arriving in chunks), and
finalize it when the turn is done. Audio for each context streams back as it is synthesized.
- You send JSON text frames; the "type" field dispatches the message.
- You receive JSON text frames (status/control) interleaved with binary frames (raw audio).
MESSAGES YOU SEND
task_start (begin a context):
field required default notes
type yes - "task_start"
context_id yes - unique per session; a duplicate gives context_already_exists
voice_id yes - your Flam voice id; unknown/unenrolled gives voice_not_found
text no "" text to synthesize; 10,000 chars or more gives text_too_long;
empty text with finalize: true gives text_required
finalize no false true = no more text for this context; flush and finish
language no "en" invalid gives invalid_language
output_format no f32le one of the audio formats below; invalid is coerced to default
sample_rate no 24000 native rate is 24000; only upsampling above it
num_step no 32 1-32; quality vs latency
expressiveness no - 0-1; accepted, no effect today (use guidance_scale)
guidance_scale no 2.0 0-10
length_scale no 1.0 greater than 0, up to 5; speaking-rate control
idle_flush_ms no 800 clamped to 200-5000; auto-flush a pending sentence after this
much silence from you
{
"type": "task_start",
"context_id": "ctx-1",
"voice_id": "665f1a2b3c4d5e6f7a8b9c0d",
"text": "Hello from Finesse, streaming in realtime.",
"finalize": true,
"output_format": "s16le",
"sample_rate": 24000
}
task_continue (append text to an open context; send as many as you like, and set finalize: true
on the last one to flush and finish):
{ "type": "task_continue", "context_id": "ctx-1", "text": "And another sentence.", "finalize": false }
task_cancel (abort a context):
{ "type": "task_cancel", "context_id": "ctx-1" }
session_end (graceful close; the server replies with session_ended and closes the socket):
{ "type": "session_end" }
Validate locally before sending: required fields present, context_id unique and at most 4 open,
task_start text under 10,000 characters, numeric parameters sent as JSON numbers (not strings),
sample_rate 8000-48000, num_step 1-32, expressiveness 0-1, and keep guidance_scale within 0-10 and length_scale in
(0, 5], and every text frame well under 1 MiB.
MESSAGES YOU RECEIVE (JSON text frames, each with a "type")
- task_started: {context_id, sample_rate, audio_format}. The EFFECTIVE rate and format for the
context. Use these, not what you requested, to configure playback.
- audio_chunk: {context_id, sentence_index, chunk_index, audio_duration_s, byte_length},
IMMEDIATELY FOLLOWED BY ONE BINARY FRAME of raw PCM (or opus) bytes. Pair them in order: each
audio_chunk announces the binary frame that follows it. Route that binary frame to the announced
context_id, and check its length against byte_length (log a warning on mismatch).
- sentence_done: {context_id, sentence_index, text, audio_duration_s}. One sentence is fully
synthesized.
- task_done: {context_id, num_sentences, total_audio_duration_s, profile, trace_id}. The context
is complete; profile carries timing detail (ttfb_ms, generate_ms, overall_rtf, and more; type it
as an open record).
- task_cancelled: {context_id, sentences_completed, sentences_dropped, trace_id}. Reply to
task_cancel.
- task_failed: {context_id, sentences_completed, code, trace_id}. Terminal failure for one
context.
- error: {context_id?, code, message, fatal}. Validation or billing errors. When fatal is true the
session is closing; otherwise only the offending message was rejected (fail just that context
if context_id is set).
- session_ended: {reason}, where reason is "idle" or "client_request". The socket closes after it.
Documented error codes: context_already_exists, voice_not_found, voice_not_allowed, text_too_long,
text_required, rate_limited, invalid_language, invalid_request (non-fatal: a parameter out of range or not a JSON number),
insufficient_credits, stream_billing_error (fatal: the billing check failed; retry on a new
connection), upstream_closed (fatal: the engine connection dropped; retry on a new connection),
invalid_message (non-fatal: a frame you sent was dropped), upstream_unavailable (fatal: the engine
could not be reached; retry on a new connection). Keep code typed as string; unknown codes must
not crash.
Ignore unknown message types.
AUDIO FORMATS (binary frames carry raw PCM, no container, in the context's output_format)
format bytes/sample notes
f32le 4 default; float32 in [-1, 1)
s16le 2 best choice for web playback and WAV wrapping
s24le / s32le / f64le 3 / 4 / 8 niche pipelines
opus - 48 kHz, 20 ms frames; can stall under heavy chunking; prefer
PCM on WebSocket
Audio is MONO at the effective sample_rate from task_started (native 24000 Hz). Nothing on this
path returns WAV: provide a small helper that wraps mono s16le PCM in a WAV header when needed.
Default the client to output_format "s16le" unless the caller chooses otherwise, and state it.
LIMITS AND CLOSE CODES
- Text frames over 1 MiB close the socket with code 1009.
- A session idle for 600 s is closed by the server (session_ended with reason "idle"). Surface
that as a normal end, not an error.
- Close codes:
1009 text frame over 1 MiB: a client bug; do not reconnect with the same payload
1011 reason "upstream_error" (the synthesis service failed), "upstream_closed" (its
connection dropped, preceded by an upstream_closed error frame) or
"stream_billing_error" (the billing check failed, preceded by that frame): reconnect
with backoff
1013 reason "upstream_unavailable" (the engine could not be reached, preceded by that error
frame) or "upstream_busy" (the synthesis service is at capacity): back off before
reconnecting, and reuse one socket for many contexts instead of opening more
1008 out of credits (reason insufficient_credits, preceded by that error frame): do not
reconnect until the workspace is topped up
1000 the session ended normally
1006 no close frame: the network dropped (reconnect with backoff if the caller opted in)
Any other close code from the engine is passed through with its reason.
- Each open socket holds one of the workspace's concurrent stream slots, so reuse one socket for
many contexts instead of opening more connections.
- On any close, fail every still-open context with a typed error carrying the close code/reason.
- Reconnect policy: never reconnect automatically on 402/403/1008, or on 401 (except 401
token_invalid: at most one retry with a fresh token). For other abnormal closes, reconnect only
if the caller opted in, with exponential backoff and a NEW token each time, and never replay
contexts that already sent text (replaying bills the text again).
BILLING
- Billed per character of text on every task_start and task_continue frame, against the plan's
monthly character allowance, exactly like the /speak and SSE endpoints.
- If the workspace runs out of credits mid-session (strict enforcement), the frame that exceeded
the balance is not forwarded; you receive a fatal error frame and the session closes:
{ "type": "error", "code": "insufficient_credits", "message": "You're out of credits - top up to continue.", "fatal": true }
Map it to a distinct out-of-credits error. If the billing check itself fails, the same fatal
frame arrives with code "stream_billing_error" ("Billing check failed. Please retry.").
LATENCY
- The first connection after a long idle period may be slow while the synthesis engine warms up.
Allow a generous, configurable connect/first-audio timeout, and for latency-sensitive apps
connect ahead of the first turn and keep the socket alive (reuse it across turns).
ACCEPTANCE CRITERIA
- Connects with the API key in the X-API-Key header on a server, or with a freshly minted token in
the subprotocol list ["finesse.v1", token] in a browser (the API key never appears in a URL or in
browser code), and surfaces 401/402/403/429 handshake failures distinctly.
- Sends only the documented message types and fields; enforces at most 4 open contexts and unique
context ids.
- Pairs every audio_chunk with the next binary frame and delivers the bytes to the right context,
using the effective sample_rate/audio_format from task_started.
- Handles task_done, task_cancelled, task_failed, non-fatal and fatal error frames, session_ended,
and close codes 1000/1006/1008/1009/1011/1013 as described; a 429 (rate_limited, concurrency_limited) or 503 (upstream_busy) handshake waits Retry-After, then retries.
- Supports multi-frame turns (task_start, then task_continue ..., finalize: true), e.g. feeding LLM
output.
TEST PLAN
- Unit tests against a local fake WebSocket server: single-shot turn (task_start with finalize:
true, s16le) collects PCM and resolves on task_done; audio_chunk/binary pairing with two
interleaved contexts; a fifth concurrent context is rejected locally; non-fatal voice_not_found
fails only that context; non-fatal voice_not_allowed fails only that context; fatal insufficient_credits fails all contexts and closes; task_cancel
resolves with task_cancelled; close 1011 and 1013 map to the right errors without reconnect loops; a 429
concurrency_limited handshake is retried only after Retry-After;
session_end resolves on session_ended.
- Smoke script:
- Get a ready voice id from FLAM_VOICE_ID, or by calling GET https://fi.production.flamapis.com/flam-voice-svc/api/v1/public/voices (same
X-API-Key header; voices are in data.voices) and picking the first one whose status is "ready".
- Mint a token with POST .../public/tokens (X-API-Key from FINESSE_API_KEY), connect with
subprotocols ["finesse.v1", token], send one task_start with finalize: true, output_format "s16le", sample_rate 24000 and
the text "Hello from Finesse, streaming in realtime.", collect PCM until task_done, wrap it as
a mono WAV at the task_started sample_rate, write realtime.wav, and print time to first audio
chunk, total bytes and task_done.profile.
- Then run a second context as a multi-frame turn: task_start with "The quick answer is yes.",
task_continue " The longer answer involves a few tradeoffs worth knowing.", and task_continue
" Ask me about any of them." with finalize: true. Send session_end and exit 0 on
session_ended; exit non-zero on any error.
AMBIGUITIES TO ASK ABOUT, NOT GUESS
- Whether a finalize-only task_continue with empty text is accepted (the spec only says empty text
with finalize: true is rejected on task_start). Until confirmed, finalize by setting
finalize: true on the last task_continue that carries text.
- Any per-context or per-session total text limit beyond the documented per-frame limits.
RULES
- Implement only what this spec describes. Do not invent parameters, fields, headers, endpoints or
error codes. If something is ambiguous, missing, or conflicts with the existing codebase, stop
and ask me before guessing.
- Match the project's existing style and conventions; do not refactor unrelated code.