Appearance
AI assistant
Every route needs a signed-in user (401 UNAUTHENTICATED for guests). Paths are under /v1. Replies are generated on the assistant queue and streamed over the /assistant socket; HTTP only accepts the message.
How a reply works
- Policy: typed or transcribed text is checked first. Self-harm, child safety, violence, prompt extraction, secrets, other users' data, piracy and harassment are answered at once with a fixed reply (
status: refused,finishReason: policy), with no model call and no quota used. Prompt-injection attempts scoring ≥ 0.8 are refused the same way. - Quota: one request from today's per-plan allowance (UTC day) is taken atomically (
429 ASSISTANT_QUOTA_EXCEEDED, withremedy: subscribeon the free plan). - Planner: keyword intent, plus a cheap-model classification when unsure. This picks a sub-agent (discovery, playback, personal stats, creator info, studio, app help, account help, small talk), and each sub-agent has its own tool whitelist.
- Router: picks the cheap, mid or top model by task, plan (the free plan never gets the top model), complexity and remaining cost budget, with a fallback chain for rate limits, 5xx errors and timeouts.
- Tool loop: limited by steps, per-step timeout, per-tool timeout, and a per-request token and cost budget. Tools are read-only. Playback commands come back as client actions. Anything with consequences (save playlist, follow, like, buy, subscribe, tip) only ever comes back as a confirmation card.
- Output filter: keys, tokens, JWTs, emails, phone, card and bank numbers are redacted from the stream and the stored text. A reply that leaks the system prompt is replaced.
Endpoints
| Method | Path | Body / query | Response | Errors |
|---|---|---|---|---|
| GET | /assistant/usage | { plan, limit, used, remaining, resetsAt } | ||
| GET | /assistant/conversations | ?cursor&limit&status=active|archived | page of Conversation | PAGINATION_CURSOR_INVALID |
| POST | /assistant/conversations | { title?, studioProfileId? } | 201 Conversation | ASSISTANT_STUDIO_FORBIDDEN (needs stats:read on the profile) |
| GET | /assistant/conversations/:id | Conversation | ASSISTANT_CONVERSATION_NOT_FOUND | |
| PATCH | /assistant/conversations/:id | { title?: string|null, status? } | Conversation | ASSISTANT_CONVERSATION_NOT_FOUND |
| DELETE | /assistant/conversations/:id | { status: "ok" } | ASSISTANT_CONVERSATION_NOT_FOUND | |
| GET | /assistant/conversations/:id/messages | ?cursor&limit (newest first) | page of Message | ASSISTANT_CONVERSATION_NOT_FOUND |
| POST | /assistant/conversations/:id/messages | { content (1-4000), clientRef? } | 202 { userMessage, reply } | ASSISTANT_QUOTA_EXCEEDED, ASSISTANT_REPLY_IN_PROGRESS, ASSISTANT_DUPLICATE_MESSAGE, ASSISTANT_PROVIDER_UNAVAILABLE |
| POST | /assistant/conversations/:id/voice | raw audio body; ?language&clientRef | 202 { status: "accepted", transcript, userMessage, reply } or 200 { status: "confirm", transcript, confidence } | ASSISTANT_AUDIO_INVALID (detail: empty, too_large, unsupported_format, unsupported_codec, too_long, sample_rate_out_of_range), ASSISTANT_AUDIO_UNCLEAR, ASSISTANT_VOICE_UNAVAILABLE, plus the send errors |
| POST | /assistant/messages/:id/cancel | { status: "ok" } | ASSISTANT_MESSAGE_NOT_FOUND (not yours, or already finished) | |
| POST | /assistant/messages/:id/feedback | { rating: up|down, reason?, comment? } | { status: "ok" } | ASSISTANT_MESSAGE_NOT_FOUND |
| POST | /assistant/messages/:id/speech | audio bytes (audio/mpeg, audio/ogg or audio/wav) | ASSISTANT_VOICE_UNAVAILABLE, ASSISTANT_MESSAGE_NOT_FOUND | |
| POST | /assistant/actions/:id/outcome | { outcome: confirmed|dismissed|failed } | { status: "ok" } | ASSISTANT_ACTION_NOT_FOUND |
Rate limits are per account per minute: create 30, send 20, voice 10, speech 20.
Voice: the bytes are sniffed, and the declared content type is ignored. Allowed formats are Ogg/Opus, WebM/Opus, MP4 (M4A)/AAC, WAV/PCM and MP3. The limits are 30 s, ASSISTANT_VOICE_MAX_BYTES, and a sample rate of 8 to 48 kHz. Duration comes from the container header, or from the speech provider when the header doesn't carry it. A transcript below ASSISTANT_VOICE_CONFIDENCE_THRESHOLD doesn't act: it comes back for the user to confirm, and is then sent as text.
Shapes
- Conversation:
{ id, title, status, studioProfileId, messageCount, lastMessageAt, createdAt } - Message:
{ id, conversationId, role, status (pending|streaming|completed|failed|cancelled|refused), inputMode (text|voice), content, replyToId, finishReason (completed|max_tokens|refused|step_limit|budget_exhausted|policy|cancelled|error), feedback, actions[], createdAt, completedAt } - Action:
{ id, kind (play|queue_next|queue_last|pause|resume|skip_next|skip_previous|confirm_card), cardKind (save_playlist|follow_creator|unfollow_creator|like_track|buy_product|subscribe_plan|tip_creator|open_screen), targetKind, targetId, title, description, requiresConfirmation, playbackMode (full|preview|none), outcome, items[{kind,id}] }. Cards always haverequiresConfirmation: true. A playback action needs confirmation when another device holds the playback lease. The client performs a confirmed action through the owning module's own API, then reports it with/actions/:id/outcome.
Socket /assistant
Every event goes to the caller's own user:<id> room.
| Direction | Event | Payload / ack |
|---|---|---|
| client → server | message:send | { conversationId, content, clientRef? } → ack { userMessage, reply } |
| client → server | message:cancel | { messageId } → ack { status: "ok" } |
| client → server | voice:send | { conversationId, audioBase64 (≤ 900 000 chars), language?, clientRef? } → ack like the voice route |
| server → client | reply:started | { conversationId, messageId } |
| server → client | reply:streamed | { conversationId, messageId, seq, text } (redacted text, in order) |
| server → client | reply:working | { conversationId, messageId, activity: searching|checking_stats|reading_insights|preparing_action|looking_up_help|thinking } |
| server → client | action:proposed | { conversationId, messageId, action } |
| server → client | reply:completed | { conversationId, messageId, content, finishReason }. content replaces whatever was streamed. |
| server → client | reply:failed | { conversationId, messageId, code } |
Events
assistant.reply.completed:{ conversationId, messageId, userId, domain, finishReason, model, steps, toolCalls, actionsProposed, inputTokens, outputTokens, costMicroUsd, viaVoice }. Never carries message text.assistant.policy.refused:{ userId, conversationId, messageId, category }.
Data
Conversations, messages, client actions and their items, feedback and daily usage are deleted with the user (identity.user.deleted). The tool-call audit log (redacted, truncated arguments plus a SHA-256 hash of the input) is unlinked from the user but kept until the retention cutoff. An hourly job fails replies stuck for over 15 minutes, purges conversations idle for longer than ASSISTANT_RETENTION_DAYS, and trims usage rows older than 400 days.
Models and routing
- Gateway: OpenRouter (
ASSISTANT_PROVIDER=openrouter, the production default), Chat Completions with SSE,tools/tool_calls,usage: {include: true}(tokens, cached tokens, cost),provider.data_collection(defaultdeny), and themodelsarray for in-request fallback. Anthropic models getcache_controlon the static system prompt. The direct Anthropic adapter (ASSISTANT_PROVIDER=anthropic, or as an extra route) caches the system prompt and the conversation, sends no sampling parameters, and retries 429/529 withretry-afterand jittered backoff.fakeis for development and tests and is refused in production. - Tiers:
free(intent, FAQ, small talk, summaries only),cheap,mid,top. Free plan: up to cheap. Trial and paid: mid, and top only for reasoning flagged complex. - Candidates per tier: pins first (
ASSISTANT_MODELS_FREE,ASSISTANT_MODEL_CHEAP|MID|TOP, or staff overrides), then catalogue models that meet the step's needs (tools, JSON, vision, context) ranked by our own health, then price. A rate-limited tier escalates to the next one within the plan's cap; the first step escalates once on invalid tool JSON, an empty refusal, or a refusal to use the tools; a low-confidence intent starts one tier up. - Catalogue:
assistant.models-sync(queueassistant, everyASSISTANT_CATALOGUE_SYNC_HOURS) readsGET /api/v1/modelsintoassistant_models. Every model call is logged toassistant_model_callsand rolled up hourly intoassistant_model_health(success rate, p50/p95 latency, rate limits).
Memory and handover
- Conversations past
ASSISTANT_SUMMARY_AFTER_MESSAGESget a running summary (assistant.summarize, free tier, redacted input and output) of what fell out of the history window. - Preference notes: the assistant may save a music preference with
save_preference_note; notes with health, religion, politics, sexuality, ethnicity, money, contact details or other people are refused. Notes and the summary reach the model as delimited data. - Handover: asking for a person, a payment dispute, account recovery, a legal or safety matter opens a support ticket at once and marks the conversation
handed_over; later messages there are forwarded to the ticket and acknowledged without a model. Two failed replies in a row or very negative messages add acontact_supportcard; confirming it calls the handover endpoint.
| Method | Path | Auth | Body / query | Response | Errors |
|---|---|---|---|---|---|
| POST | /v1/assistant/conversations/:id/handover | user | — | ConversationView with support { ticketId, reference, link } | ASSISTANT_CONVERSATION_NOT_FOUND, ASSISTANT_SUPPORT_UNAVAILABLE |
| GET | /v1/me/assistant/notes | user | — | [{ id, note, source, createdAt }] | |
| DELETE | /v1/me/assistant/notes/:noteId | user | — | { status: "ok" } | NOT_FOUND |
| DELETE | /v1/me/assistant/notes | user | — | { status: "ok" } | |
| GET | /v1/staff/assistant/models | staff assistant:manage | page, freeOnly | page of { id, name, prices, contextLength, supports*, isFree, isActive, health } | FORBIDDEN |
| GET | /v1/staff/assistant/pins | staff assistant:manage | — | { free[], cheap[], mid[], top[] } (effective) | |
| PUT | /v1/staff/assistant/pins/:tier | staff assistant:manage | { models: string[] } (empty restores env pins) | { status: "ok" } | |
| GET | /v1/staff/assistant/report | staff assistant:manage | from, to (≤ 93 days), groupBy=day|model|domain|plan|tier | [{ key, replies, inputTokens, outputTokens, cacheHitRate, costMicroUsd, latencyP50Ms, latencyP95Ms, firstTokenP50Ms, avgToolCalls, refusals, escalations, handovers, errors }] | VALIDATION_FAILED |
New tools: get_play_counts, get_discover_shelf, get_release_status (studio conversations, stats:read), get_wallet_summary (own wallet, read-only), save_preference_note, request_human_support; get_subscription_status now lists plan benefits. New socket activity: contacting_support. New card kinds: support_ticket, contact_support. New finish reason: handed_over.
Telemetry
assistant_reply_metrics (monthly partitions, 13 months): per reply plan, domain, tier, provider, model, steps, tool calls and errors, input/output/cache tokens, cost, latency, first-token time, finish reason, refusal category, escalation, fallbacks, voice, handover. No message text and no user id.
Evals
test/assistant/evals/cases.json: golden cases for intent routing, tool choice, refusals, prompt injection, PII redaction, confirmation cards, Pidgin/Yoruba/Igbo/Hausa basics and handover. test/assistant/evals.test.ts runs them offline and through the chain with the fake provider; scripts/assistant-eval.ts runs them against OpenRouter and prints pass rate, latency and cost.
Speech
- Speech-to-text:
ASSISTANT_STT_PROVIDER=openrouter(production default;fakeis refused in production). Audio is sniffed and size/duration-checked first. WAV, MP3 and Ogg go as they are; M4A/AAC and WebM/Opus are converted to 16 kHz mono WAV by ffmpeg in-process (stdin to stdout, no temp files,-tat the duration limit, timeout and output-size bounds). The audio goes as aninput_audiopart toASSISTANT_STT_MODEL(defaultgoogle/gemini-2.5-flash-lite), thenASSISTANT_STT_FALLBACK_MODELS(defaultmistralai/voxtral-small-24b-2507), while the catalogue still lists them with audio input; otherwise the cheapest healthy listed model. It returns{text, language, confidence}JSON; the confidence threshold still applies. - Text-to-speech:
openrouterin production (noneby default elsewhere) withASSISTANT_TTS_MODEL(defaultopenai/gpt-audio-mini) andASSISTANT_TTS_VOICE; streamed PCM is returned asaudio/wav. A model that drops off the catalogue's audio-output list falls back to the cheapest healthy model that has audio output.