Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(persona): harden the extract and preview handlers against bad input and upstream faults
nirholasacdf7aacd442
diff --git a/api/persona/extract.js b/api/persona/extract.jsindex 11ec02281..49a3e28ca 100644--- a/api/persona/extract.js+++ b/api/persona/extract.js@@ -1,8 +1,11 @@// POST /api/persona/extract// Synthesizes a structured persona JSON from a short onboarding interview.-// Runs through the shared LLM helper (api/_lib/llm.js) for Anthropic-first-// ordered failover: server Anthropic → Groq → OpenRouter, so a single upstream-// 429/5xx fails over to the next provider instead of returning a hard 502.+// Runs through the shared LLM helper (api/_lib/llm.js), which owns the ordered+// failover chain (free lanes first, the GCP-credits Vertex anchor behind them,+// the paid server keys last), so a single upstream 429/5xx falls through to the+// next provider instead of returning a hard 502. Do not restate the provider+// order here: providerChain() in api/_lib/llm.js is the only source of truth+// for it, and a copy of the list in this comment goes stale silently.import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';@@ -87,15 +90,18 @@ const handler = wrap(async (req, res) => {return error(res, 401, 'unauthorized', 'Sign in to build your persona.');}- // Each call is a paid LLM completion on the server key — meter per user so a- // free-signup loop can't run up an unbounded bill (5/day, matches the sibling- // agents/:id/persona route).- const rl = await limits.personaExtract(userId);- if (!rl.success) return rateLimited(res, rl);-+ // Validate BEFORE metering. The limiter exists to bound LLM spend (see below),+ // and a rejected body spends nothing, so charging it against a 5/day budget+ // just burns the user's quota on their own typos.const body = await readJson(req);const input = validateInput(body);+ // Each call is a metered LLM completion, so meter per user as well: a+ // free-signup loop must not be able to run up an unbounded bill (5/day,+ // matching the sibling agents/:id/persona route).+ const rl = await limits.personaExtract(userId);+ if (!rl.success) return rateLimited(res, rl);+let userMessage;if (input.mode === 'freeform') {userMessage = `Analyze the following text and synthesize a persona JSON that captures the voice, personality, and communication patterns present in it.\n\n---\n${input.text}\n---`;@@ -123,7 +129,15 @@ const handler = wrap(async (req, res) => {return error(res, err?.status || 502, 'upstream_error', 'Persona extraction is briefly unavailable. Please try again.');}+ // llmComplete prefers returning an empty-but-valid completion over throwing+ // when every provider answered 200 with no content. That is a failure for this+ // endpoint, not a persona, so surface it as a retryable 502 rather than+ // letting JSON.parse('') report it as a malformed model response.const raw = completion.text;+ if (!raw) {+ return error(res, 502, 'upstream_error', 'The model returned an empty response. Please try again.');+ }+let persona;try {const stripped = raw@@ -167,6 +181,15 @@ const handler = wrap(async (req, res) => {: '',};+ // Well-formed JSON with nothing usable in it (e.g. a bare `{}`) would otherwise+ // render as a blank persona card the user cannot act on. communication_style+ // is excluded from this check because it always defaults to a value.+ if (!normalized.tone && !normalized.sample_greeting+ && !normalized.vocabulary.length && !normalized.interests.length) {+ console.error('[persona/extract] model returned an empty persona', raw.slice(0, 500));+ return error(res, 502, 'parse_error', 'The model returned an empty persona. Please try again.');+ }+const usage = completion.usage;return json(res, 200, {diff --git a/api/persona/preview.js b/api/persona/preview.jsindex 67dea3920..4e5b4dc57 100644--- a/api/persona/preview.js+++ b/api/persona/preview.js@@ -1,8 +1,11 @@// POST /api/persona/preview// Replies to a user message in the voice of a supplied persona JSON.-// Runs through the shared LLM helper (api/_lib/llm.js) for Anthropic-first-// ordered failover: server Anthropic → Groq → OpenRouter, so a single upstream-// 429/5xx fails over to the next provider instead of returning a hard 502.+// Runs through the shared LLM helper (api/_lib/llm.js), which owns the ordered+// failover chain (free lanes first, the GCP-credits Vertex anchor behind them,+// the paid server keys last), so a single upstream 429/5xx falls through to the+// next provider instead of returning a hard 502. Do not restate the provider+// order here: providerChain() in api/_lib/llm.js is the only source of truth+// for it, and a copy of the list in this comment goes stale silently.import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../_lib/auth.js';@@ -10,6 +13,12 @@ import { limits } from '../_lib/rate-limit.js';import { llmComplete, LlmUnavailableError, promptTokens } from '../_lib/llm.js';const MAX_MSG_CHARS = 1500;+// The persona is pinned into the system prompt verbatim, so its serialized size+// is prompt size. Without a bound, a caller could post a megabyte-scale object+// (readJson's own limit) and turn one metered request into an arbitrarily+// expensive completion, which is exactly what the per-user limiter below exists+// to prevent. A persona from /api/persona/extract serializes to well under 1 KB.+const MAX_PERSONA_CHARS = 8000;async function resolveUser(req) {const session = await getSessionUser(req);@@ -27,25 +36,32 @@ function validateBody(input) {throw Object.assign(new Error('body must be an object'), { status: 400 });}const { persona, user_message } = input;- if (!persona || typeof persona !== 'object') {+ if (!persona || typeof persona !== 'object' || Array.isArray(persona)) {throw Object.assign(new Error('persona must be an object'), { status: 400 });}if (typeof user_message !== 'string' || !user_message.trim()) {throw Object.assign(new Error('user_message required'), { status: 400 });}+ const personaJson = JSON.stringify(persona, null, 2);+ if (personaJson.length > MAX_PERSONA_CHARS) {+ throw Object.assign(+ new Error(`persona is too large (max ${MAX_PERSONA_CHARS} characters serialized)`),+ { status: 400 },+ );+ }return {- persona,+ personaJson,user_message: user_message.trim().slice(0, MAX_MSG_CHARS),};}-function buildSystemPrompt(persona) {+function buildSystemPrompt(personaJson) {// Compact, deterministic system prompt. We pin the JSON inline so the model// has every persona field visible and can reference vocabulary / dont_say.- return `You are an agent speaking on behalf of a person whose persona is described by the following JSON profile. Embody this voice — tone, vocabulary, communication style — in every reply.+ return `You are an agent speaking on behalf of a person whose persona is described by the following JSON profile. Embody this voice (tone, vocabulary, communication style) in every reply.PERSONA:-${JSON.stringify(persona, null, 2)}+${personaJson}Rules:- Reply in 1-2 sentences. Never more.@@ -65,13 +81,15 @@ const handler = wrap(async (req, res) => {return error(res, 401, 'unauthorized', 'sign in or provide a valid bearer token');}- // Paid LLM completion on the server key — meter per user to bound the bill.+ // Validate before metering: a rejected body never reaches a provider, so it+ // should not consume the caller's completion budget.+ const body = validateBody(await readJson(req));++ // Metered LLM completion, so meter per user too and keep the bill bounded.const rl = await limits.personaPreviewUser(userId);if (!rl.success) return rateLimited(res, rl);- const body = validateBody(await readJson(req));-- const system = buildSystemPrompt(body.persona);+ const system = buildSystemPrompt(body.personaJson);const t0 = Date.now();let completion;try {@@ -82,13 +100,25 @@ const handler = wrap(async (req, res) => {});} catch (err) {if (err instanceof LlmUnavailableError) {+ // The caller cannot act on which server-side key is missing, and naming+ // the env vars in a public response advertises our provider inventory.+ // The operator sees the real cause in the log line below.+ console.error('[persona/preview] no LLM provider configured');return error(res, 503, 'config_missing',- 'No LLM provider configured. Set GROQ_API_KEY, OPENROUTER_API_KEY, or NVIDIA_API_KEY (free), or ANTHROPIC_API_KEY / OPENAI_API_KEY.');+ 'Persona preview is not available right now. Please try again later.');}console.error('[persona/preview] all providers failed', err?.status, err?.message);return error(res, err?.status || 502, 'upstream_error', 'Persona preview is briefly unavailable. Please try again.');}+ // llmComplete prefers an empty-but-valid completion over throwing when every+ // provider answered 200 with no content. A blank reply is not a preview, so+ // report it as retryable instead of shipping an empty bubble to the client.+ if (!completion.text) {+ console.error('[persona/preview] every provider returned an empty completion');+ return error(res, 502, 'upstream_error', 'The model returned an empty reply. Please try again.');+ }+const usage = completion.usage;return json(res, 200, {