Skip to content

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 ​

  1. 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.
  2. Quota: one request from today's per-plan allowance (UTC day) is taken atomically (429 ASSISTANT_QUOTA_EXCEEDED, with remedy: subscribe on the free plan).
  3. 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.
  4. 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.
  5. 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.
  6. 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 ​

MethodPathBody / queryResponseErrors
GET/assistant/usage{ plan, limit, used, remaining, resetsAt }
GET/assistant/conversations?cursor&limit&status=active|archivedpage of ConversationPAGINATION_CURSOR_INVALID
POST/assistant/conversations{ title?, studioProfileId? }201 ConversationASSISTANT_STUDIO_FORBIDDEN (needs stats:read on the profile)
GET/assistant/conversations/:idConversationASSISTANT_CONVERSATION_NOT_FOUND
PATCH/assistant/conversations/:id{ title?: string|null, status? }ConversationASSISTANT_CONVERSATION_NOT_FOUND
DELETE/assistant/conversations/:id{ status: "ok" }ASSISTANT_CONVERSATION_NOT_FOUND
GET/assistant/conversations/:id/messages?cursor&limit (newest first)page of MessageASSISTANT_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/voiceraw audio body; ?language&clientRef202 { 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/speechaudio 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 have requiresConfirmation: 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.

DirectionEventPayload / ack
client → servermessage:send{ conversationId, content, clientRef? } → ack { userMessage, reply }
client → servermessage:cancel{ messageId } → ack { status: "ok" }
client → servervoice:send{ conversationId, audioBase64 (≤ 900 000 chars), language?, clientRef? } → ack like the voice route
server → clientreply:started{ conversationId, messageId }
server → clientreply:streamed{ conversationId, messageId, seq, text } (redacted text, in order)
server → clientreply:working{ conversationId, messageId, activity: searching|checking_stats|reading_insights|preparing_action|looking_up_help|thinking }
server → clientaction:proposed{ conversationId, messageId, action }
server → clientreply:completed{ conversationId, messageId, content, finishReason }. content replaces whatever was streamed.
server → clientreply: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 (default deny), and the models array for in-request fallback. Anthropic models get cache_control on 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 with retry-after and jittered backoff. fake is 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 (queue assistant, every ASSISTANT_CATALOGUE_SYNC_HOURS) reads GET /api/v1/models into assistant_models. Every model call is logged to assistant_model_calls and rolled up hourly into assistant_model_health (success rate, p50/p95 latency, rate limits).

Memory and handover ​

  • Conversations past ASSISTANT_SUMMARY_AFTER_MESSAGES get 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 a contact_support card; confirming it calls the handover endpoint.
MethodPathAuthBody / queryResponseErrors
POST/v1/assistant/conversations/:id/handoveruser—ConversationView with support { ticketId, reference, link }ASSISTANT_CONVERSATION_NOT_FOUND, ASSISTANT_SUPPORT_UNAVAILABLE
GET/v1/me/assistant/notesuser—[{ id, note, source, createdAt }]
DELETE/v1/me/assistant/notes/:noteIduser—{ status: "ok" }NOT_FOUND
DELETE/v1/me/assistant/notesuser—{ status: "ok" }
GET/v1/staff/assistant/modelsstaff assistant:managepage, freeOnlypage of { id, name, prices, contextLength, supports*, isFree, isActive, health }FORBIDDEN
GET/v1/staff/assistant/pinsstaff assistant:manage—{ free[], cheap[], mid[], top[] } (effective)
PUT/v1/staff/assistant/pins/:tierstaff assistant:manage{ models: string[] } (empty restores env pins){ status: "ok" }
GET/v1/staff/assistant/reportstaff assistant:managefrom, 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; fake is 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, -t at the duration limit, timeout and output-size bounds). The audio goes as an input_audio part to ASSISTANT_STT_MODEL (default google/gemini-2.5-flash-lite), then ASSISTANT_STT_FALLBACK_MODELS (default mistralai/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: openrouter in production (none by default elsewhere) with ASSISTANT_TTS_MODEL (default openai/gpt-audio-mini) and ASSISTANT_TTS_VOICE; streamed PCM is returned as audio/wav. A model that drops off the catalogue's audio-output list falls back to the cheapest healthy model that has audio output.

Plemuz API v2