Skip to content

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.

feat(persona): run the onboarding interview before the agent exists and record which questions shaped it

nirholasba33d02be997
diff --git a/api/agents/_id/persona.js b/api/agents/_id/persona.js
index 92f5e6e08..7a2640b6f 100644
--- a/api/agents/_id/persona.js
+++ b/api/agents/_id/persona.js
@@ -17,7 +17,10 @@ import { getSessionUser, authenticateBearer, extractBearer, isSameSiteOrigin } f
import { cors, json, method, readJson, wrap, error, rateLimited } from '../../_lib/http.js';
import { limits } from '../../_lib/rate-limit.js';
import { env } from '../../_lib/env.js';
-import { llmComplete, LlmUnavailableError } from '../../_lib/llm.js';
+import {
+ extractPersonaFromInterview,
+ PersonaExtractionError,
+} from '../../_lib/persona-interview-extract.js';
import { parse } from '../../_lib/validate.js';
import { z } from 'zod';
import {
@@ -27,11 +30,43 @@ import {
sanitizeVocabulary,
PERSONA_TRAIT_KEYS,
} from '../../../src/agents/persona-compile.js';
-
+import {
+ INTERVIEW_QUESTIONS,
+ normalizeInterview,
+ interviewTranscript,
+ MAX_INTERVIEW_ANSWERS,
+} from '../../../src/agents/persona-interview.js';
+
+// Two accepted answer shapes, one interview. The structured form
+// ([{ id?, question?, answer }]) is what the create-agent wizard and the current
+// Brain Studio modal send: 5 to 8 questions, any of them skippable. The legacy
+// form (five bare strings, positionally mapped onto the canonical questions) is
+// still accepted so an older client or an SDK caller keeps working.
const extractBody = z.object({
answers: z
- .array(z.string().trim().min(5, 'Each answer must be at least 5 characters').max(1000))
- .length(5, 'Exactly 5 answers required'),
+ .union([
+ z.array(z.string().max(1000)).min(1).max(MAX_INTERVIEW_ANSWERS),
+ z
+ .array(
+ z.object({
+ id: z.string().max(40).optional(),
+ question: z.string().max(240).optional(),
+ answer: z.string().max(1000),
+ }),
+ )
+ .min(1)
+ .max(MAX_INTERVIEW_ANSWERS),
+ ])
+ .transform((rows) =>
+ normalizeInterview(
+ rows.map((row, i) =>
+ typeof row === 'string'
+ ? { id: INTERVIEW_QUESTIONS[i]?.id, question: INTERVIEW_QUESTIONS[i]?.prompt, answer: row }
+ : row,
+ ),
+ ),
+ )
+ .refine((rows) => rows.length > 0, 'Answer at least one interview question'),
});
const traitsSchema = z.record(z.string(), z.number()).default({});
@@ -42,6 +77,20 @@ const saveBody = z.object({
vocabulary: z.array(z.string()).max(24).default([]),
base: z.string().max(4000).optional(),
changelog: z.string().trim().max(280).optional(),
+ // Interview provenance. The create-agent wizard runs the interview before the
+ // agent exists (POST /api/persona/interview) and hands the answers over on the
+ // first save, so the agent records WHICH questions produced its voice — that is
+ // what `persona.interview` on the public manifest reports.
+ interview: z
+ .array(
+ z.object({
+ id: z.string().max(40).optional(),
+ question: z.string().max(240).optional(),
+ answer: z.string().max(1000),
+ }),
+ )
+ .max(MAX_INTERVIEW_ANSWERS)
+ .optional(),
});
const restoreBody = z.object({ version: z.number().int().positive() });
@@ -72,13 +121,29 @@ function signPrompt(systemPrompt) {
}
// Read the structured persona state stored on the agent. persona_traits holds
-// { values: {key:0..1}, vocabulary: [...], base: "..." }.
+// { values: {key:0..1}, vocabulary: [...], base: "...", interview: {...} }.
function readStructured(agent) {
const raw = agent.persona_traits && typeof agent.persona_traits === 'object' ? agent.persona_traits : {};
return {
values: clampTraits(raw.values || {}),
vocabulary: sanitizeVocabulary(raw.vocabulary || []),
base: typeof raw.base === 'string' ? raw.base : '',
+ interview: raw.interview && typeof raw.interview === 'object' ? raw.interview : null,
+ };
+}
+
+// The interview provenance block stored inside persona_traits: which questions
+// were answered, when, and where the interview ran. The answers themselves are
+// kept so the owner can reopen and edit them; the public manifest exposes only
+// the counts (see api/agents/_id/_sub.js handleManifest).
+function interviewRecord(answers, source) {
+ return {
+ source,
+ question_ids: answers.map((row) => row.id),
+ questions_answered: answers.length,
+ questions_total: INTERVIEW_QUESTIONS.length,
+ answers,
+ at: new Date().toISOString(),
};
}
@@ -112,6 +177,7 @@ export const handlePersona = wrap(async (req, res, id, action) => {
tone_tags: agent.persona_tone_tags || [],
vocabulary: structured.vocabulary,
base: structured.base,
+ interview: structured.interview,
persona_prompt: agent.persona_prompt || '',
extracted_at: agent.persona_extracted_at || null,
updated_at: agent.persona_updated_at || null,
@@ -150,51 +216,36 @@ export const handlePersona = wrap(async (req, res, id, action) => {
if (!rl.success) return rateLimited(res, rl, 'persona extraction limit reached (5 per day)');
const body = parse(extractBody, await readJson(req));
- const { answers } = body;
+ const answers = body.answers;
- let raw;
+ let extracted;
try {
- ({ text: raw } = await llmComplete({
- maxTokens: 1024,
- system:
- 'You are a persona architect. Given a person\'s interview answers, extract their communication style, tone, and voice. Produce a concise first-person system prompt that an LLM can use to impersonate this person faithfully. Be specific. Avoid clichés.\n\n' +
- 'Output ONLY a single JSON object (no markdown fences, no prose) with EXACTLY these fields:\n' +
- '{\n' +
- ' "system_prompt": string, // 150-300 word first-person system prompt, starting with "You are ..."\n' +
- ' "tone_tags": string[], // up to 8 single-word tone descriptors\n' +
- ' "vocabulary_samples": string[] // up to 10 short phrases characteristic of this persona\n' +
- '}',
- user: `Interview answers:\n1. ${answers[0]}\n2. ${answers[1]}\n3. ${answers[2]}\n4. ${answers[3]}\n5. ${answers[4]}`,
- }));
+ extracted = await extractPersonaFromInterview({
+ name: agent.name,
+ description: agent.description,
+ greeting: agent.greeting,
+ answers,
+ userId: auth.userId,
+ tool: 'persona_extract_rerun',
+ });
} catch (err) {
- if (err instanceof LlmUnavailableError) {
- return error(res, 503, 'llm_unavailable', 'persona extraction is not available right now');
+ if (err instanceof PersonaExtractionError) {
+ return error(res, err.status, err.code, err.message);
}
- console.error('[persona/extract] LLM error', err.status || '', err.message);
- return error(res, 502, 'upstream_error', 'persona extraction failed');
+ throw err;
}
- let extracted;
- try {
- const stripped = raw.replace(/^```(?:json)?\s*/i, '').replace(/\s*```$/i, '').trim();
- extracted = JSON.parse(stripped);
- } catch {
- console.error('[persona/extract] non-JSON model output', raw.slice(0, 400));
- return error(res, 502, 'upstream_error', 'unexpected response from persona extraction');
- }
-
- const base = typeof extracted.system_prompt === 'string' ? extracted.system_prompt.trim() : '';
- const tone_tags = sanitizeToneTags(extracted.tone_tags).slice(0, 8);
- const vocabulary_samples = sanitizeVocabulary(extracted.vocabulary_samples);
- if (!base) {
- return error(res, 502, 'upstream_error', 'unexpected response from persona extraction');
- }
-
- // Seed the structured persona with the extracted base + current (or default)
- // traits, then compile so the saved prompt already reflects both. The
- // interview supplies the voice; the trait sliders refine it.
+ // The interview supplies the voice; the owner's trait sliders refine it.
+ // A FIRST extraction has no tuned sliders to protect, so the interview's own
+ // trait read is adopted. A re-run keeps whatever the owner has since dialled
+ // in — re-running the interview must never silently undo their edits.
const structured = readStructured(agent);
- const traits = structured.values;
+ const firstExtraction = !agent.persona_prompt_hash;
+ const traits = firstExtraction ? extracted.traits : structured.values;
+ const base = extracted.base;
+ const tone_tags = extracted.toneTags;
+ const vocabulary_samples = extracted.vocabulary;
+
const compiled = compilePersona({
name: agent.name,
description: agent.description,
@@ -204,7 +255,12 @@ export const handlePersona = wrap(async (req, res, id, action) => {
vocabulary: vocabulary_samples,
});
const { hash, sig } = signPrompt(compiled);
- const personaTraits = { values: traits, vocabulary: vocabulary_samples, base };
+ const personaTraits = {
+ values: traits,
+ vocabulary: vocabulary_samples,
+ base,
+ interview: interviewRecord(answers, 'brain-studio'),
+ };
const [updated] = await sql`
UPDATE agent_identities
@@ -220,14 +276,18 @@ export const handlePersona = wrap(async (req, res, id, action) => {
RETURNING persona_extracted_at
`;
+ const manifest = await publishAgentManifestSafely(id, { reason: 'persona_extract' });
+
return json(res, 200, {
system_prompt: compiled,
base,
traits,
tone_tags,
vocabulary: vocabulary_samples,
+ questions_answered: answers.length,
hash,
extracted_at: updated.persona_extracted_at,
+ manifest,
});
}
@@ -243,6 +303,15 @@ export const handlePersona = wrap(async (req, res, id, action) => {
const vocabulary = sanitizeVocabulary(body.vocabulary);
const base = body.base != null ? String(body.base).trim() : prev.base;
+ // A save that carries interview answers is the wizard handing over an
+ // interview that ran before the agent existed. Record it as provenance and
+ // stamp persona_extracted_at, so the agent reports an interviewed persona
+ // exactly like a Brain Studio re-run does.
+ const interviewAnswers = body.interview ? normalizeInterview(body.interview) : [];
+ const interview = interviewAnswers.length
+ ? interviewRecord(interviewAnswers, 'create-wizard')
+ : prev.interview;
+
const compiled = compilePersona({
name: agent.name,
description: agent.description,
@@ -252,7 +321,7 @@ export const handlePersona = wrap(async (req, res, id, action) => {
vocabulary,
});
const { hash, sig } = signPrompt(compiled);
- const personaTraits = { values: traits, vocabulary, base };
+ const personaTraits = { values: traits, vocabulary, base, ...(interview ? { interview } : {}) };
const changelog = body.changelog || 'Persona updated';
const [{ next_version }] = await sql`
@@ -268,6 +337,7 @@ export const handlePersona = wrap(async (req, res, id, action) => {
persona_prompt_sig = ${sig},
persona_tone_tags = ${JSON.stringify(toneTags)}::jsonb,
persona_traits = ${JSON.stringify(personaTraits)}::jsonb,
+ persona_extracted_at = CASE WHEN ${interviewAnswers.length > 0} THEN now() ELSE persona_extracted_at END,
persona_updated_at = now(),
updated_at = now()
WHERE id = ${id}
@@ -288,6 +358,11 @@ export const handlePersona = wrap(async (req, res, id, action) => {
`,
]);
+ // The prompt that just landed is the agent's behavior, so pin the proof of
+ // it now. Best-effort by design: the save above is already committed and a
+ // pinning hiccup reports itself in `manifest.reason` rather than failing.
+ const manifest = await publishAgentManifestSafely(id, { reason: 'persona_save' });
+
return json(res, 200, {
version: next_version,
persona_prompt: compiled,
@@ -298,6 +373,7 @@ export const handlePersona = wrap(async (req, res, id, action) => {
hash,
changelog,
updated_at: updatedRows[0]?.persona_updated_at || null,
+ manifest,
});
}
@@ -365,6 +441,8 @@ export const handlePersona = wrap(async (req, res, id, action) => {
`,
]);
+ const manifest = await publishAgentManifestSafely(id, { reason: 'persona_restore' });
+
return json(res, 200, {
version: next_version,
restored_from: snap.version,
@@ -375,6 +453,7 @@ export const handlePersona = wrap(async (req, res, id, action) => {
base,
hash,
changelog,
+ manifest,
});
}
diff --git a/api/persona/interview.js b/api/persona/interview.js
new file mode 100644
index 000000000..a46d7ef03
--- /dev/null
+++ b/api/persona/interview.js
@@ -0,0 +1,96 @@
+// POST /api/persona/interview
+//
+// The onboarding interview behind the create-agent wizard's personality step.
+// A person answers up to seven short questions in their own words (every one of
+// them optional) and gets back a real, structured persona: a base paragraph, the
+// personality trait values, tone tags, characteristic vocabulary, and the exact
+// compiled system prompt the agent will run on.
+//
+// Two properties make this endpoint worth its own route rather than reusing the
+// per-agent extractor (api/agents/[id]/persona/extract):
+//
+// 1. It is STATELESS and works before the agent exists. The wizard only
+// requires an account at the final "ship it" step, so the interview has to
+// run for a signed-out visitor with no agent id to write to. The wizard
+// holds the result in its draft and persists it through
+// POST /api/agents/:id/persona/save the moment the agent is created.
+// 2. It compiles with the SAME compiler the server uses on save
+// (src/agents/persona-compile.js), so the prompt previewed in the wizard is
+// byte-for-byte the prompt that ends up signed on the agent.
+//
+// Extraction itself lives in api/_lib/persona-interview-extract.js and is shared
+// with the per-agent re-run, so there is one prompt and one output contract.
+// Anonymous callers carry a tight per-IP budget, mirroring
+// /api/agents/suggest-spec.
+
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { extractPersonaFromInterview } from '../_lib/persona-interview-extract.js';
+import { compilePersona } from '../../src/agents/persona-compile.js';
+import {
+ normalizeInterview,
+ hasInterviewSignal,
+ MAX_ANSWER_CHARS,
+} from '../../src/agents/persona-interview.js';
+
+const clampStr = (v, n) => (typeof v === 'string' ? v.replace(/\s+/g, ' ').trim().slice(0, n) : '');
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ // Try-first, exactly like /api/agents/suggest-spec: the wizard runs the whole
+ // build signed-out and only asks for an account at the ship step, so auth is
+ // resolved but never required. Anonymous callers get the tighter budget.
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ const userId = session?.id ?? bearer?.userId ?? null;
+
+ const ip = clientIp(req);
+ const rl = userId ? await limits.personaInterview(ip) : await limits.personaInterviewAnon(ip);
+ if (!rl.success) return rateLimited(res, rl);
+
+ const body = await readJson(req).catch(() => ({}));
+ const name = clampStr(body?.name, 80);
+ const description = clampStr(body?.description, 240);
+ const greeting = clampStr(body?.greeting, 200);
+ const answers = normalizeInterview(body?.answers);
+
+ if (!hasInterviewSignal(answers)) {
+ return error(res, 400, 'validation_error',
+ `Answer at least one question (${MAX_ANSWER_CHARS} characters max each), or skip the interview.`);
+ }
+
+ let persona;
+ try {
+ persona = await extractPersonaFromInterview({
+ name,
+ description,
+ greeting,
+ answers,
+ userId,
+ tool: 'persona_interview',
+ });
+ } catch (err) {
+ return error(res, err.status || 502, err.code || 'extraction_failed', err.message);
+ }
+
+ return json(res, 200, {
+ base: persona.base,
+ traits: persona.traits,
+ tone_tags: persona.toneTags,
+ vocabulary: persona.vocabulary,
+ persona_prompt: compilePersona({
+ name,
+ description,
+ base: persona.base,
+ traits: persona.traits,
+ toneTags: persona.toneTags,
+ vocabulary: persona.vocabulary,
+ }),
+ questions_answered: answers.length,
+ interview: answers,
+ provider: persona.provider,
+ });
+});
diff --git a/src/agents/persona-interview.js b/src/agents/persona-interview.js
new file mode 100644
index 000000000..9997fe815
--- /dev/null
+++ b/src/agents/persona-interview.js
@@ -0,0 +1,172 @@
+// The onboarding interview that turns a person's own words into an agent voice.
+//
+// This is the SINGLE source of truth for the question set, for what counts as an
+// answered question, and for the persona an agent gets when the interview is
+// skipped entirely. It is imported by BOTH the browser (the create-agent wizard,
+// src/create-agent.js) and the server (POST /api/persona/interview and the
+// per-agent extract route) so the questions a user sees are byte-identical to
+// the questions the extractor is told were asked.
+//
+// The interview is always optional. Every question can be left blank, and the
+// whole step can be skipped: `defaultPersonaBase()` produces a real, working
+// base persona from the name/description/greeting the wizard already collected,
+// so a skipped interview still compiles a complete persona_prompt through
+// compilePersona() rather than leaving the agent voiceless.
+//
+// Pure ESM. No DOM, no Node, no imports — runs anywhere.
+
+/**
+ * The interview. Seven questions, ordered from the easiest to answer to the most
+ * revealing, so a user who bails after three still leaves usable signal behind.
+ *
+ * `id` stable key — persisted with the answer as interview provenance.
+ * `prompt` the question, exactly as the extractor is told it was asked.
+ * `hint` sub-label rendered under the field.
+ * `placeholder` example answer; never submitted, only shown.
+ */
+export const INTERVIEW_QUESTIONS = [
+ {
+ id: 'purpose',
+ prompt: 'What should this agent help people with?',
+ hint: 'A sentence or two. The job, not the job title.',
+ placeholder: 'Help builders read a Solana token launch and decide if it is worth their time.',
+ },
+ {
+ id: 'sound',
+ prompt: 'How should it sound when it talks?',
+ hint: 'Describe the voice the way you would describe a person you know.',
+ placeholder: 'Blunt, fast, a bit dry. Never salesy. Talks like a trader, not a brochure.',
+ },
+ {
+ id: 'expertise',
+ prompt: 'What should it know cold?',
+ hint: 'The topics it should never have to hedge on.',
+ placeholder: 'Bonding curves, liquidity, holder distribution, rug patterns.',
+ },
+ {
+ id: 'sample',
+ prompt: 'Write one line the way you want to hear it say something.',
+ hint: 'One real sentence in its voice beats three paragraphs describing the voice.',
+ placeholder: 'Curve is 60% through and the top holder owns 18%. That is not a moon, that is an exit.',
+ },
+ {
+ id: 'avoid',
+ prompt: 'What should it never do or say?',
+ hint: 'Hard limits, pet peeves, phrases that would make you cringe.',
+ placeholder: 'Never say "to the moon". Never give financial advice. No emoji.',
+ },
+ {
+ id: 'uncertainty',
+ prompt: 'When it is not sure, what should it do?',
+ hint: 'How it behaves at the edge of what it knows.',
+ placeholder: 'Say so in one line, then give the best read it has with the caveat attached.',
+ },
+ {
+ id: 'vocabulary',
+ prompt: 'Any words, phrases, or running jokes that belong to it?',
+ hint: 'Verbal fingerprints. Leave blank if none come to mind.',
+ placeholder: 'calls things "clean" or "cooked"; says "let me pull the chart" before every read.',
+ },
+];
+
+/** Stable question ids, in order. */
+export const INTERVIEW_QUESTION_IDS = INTERVIEW_QUESTIONS.map((q) => q.id);
+
+/** The interview is between 5 and 8 questions; the extractor enforces the same bound. */
+export const MAX_INTERVIEW_ANSWERS = 8;
+/** Shortest answer that carries any signal. Anything shorter reads as a skip. */
+export const MIN_ANSWER_CHARS = 4;
+/** Per-answer ceiling. Long enough for a paragraph, short enough to bound the prompt. */
+export const MAX_ANSWER_CHARS = 1000;
+
+const collapse = (v) => (typeof v === 'string' ? v.replace(/\s+/g, ' ').trim() : '');
+
+/**
+ * Normalize raw interview input into the wire shape the extractor consumes.
+ *
+ * Accepts either the wizard's `{ [questionId]: answerText }` map or an array of
+ * `{ id?, question?, answer }` rows (which is what the API receives). Blank and
+ * too-short answers are dropped, so skipping questions is a first-class outcome
+ * rather than an error: the result is simply shorter.
+ *
+ * @param {object|Array} input
+ * @returns {{id: string, question: string, answer: string}[]}
+ */
+export function normalizeInterview(input) {
+ const rows = [];
+ if (Array.isArray(input)) {
+ for (const row of input) {
+ if (!row || typeof row !== 'object') continue;
+ const id = collapse(row.id);
+ const known = INTERVIEW_QUESTIONS.find((q) => q.id === id);
+ const question = collapse(row.question) || known?.prompt || '';
+ const answer = collapse(row.answer);
+ if (!question || answer.length < MIN_ANSWER_CHARS) continue;
+ rows.push({
+ id: id || 'custom',
+ question: question.slice(0, 240),
+ answer: answer.slice(0, MAX_ANSWER_CHARS),
+ });
+ }
+ } else if (input && typeof input === 'object') {
+ for (const q of INTERVIEW_QUESTIONS) {
+ const answer = collapse(input[q.id]);
+ if (answer.length < MIN_ANSWER_CHARS) continue;
+ rows.push({ id: q.id, question: q.prompt, answer: answer.slice(0, MAX_ANSWER_CHARS) });
+ }
+ }
+ return rows.slice(0, MAX_INTERVIEW_ANSWERS);
+}
+
+/**
+ * Render normalized answers as the Q/A block handed to the model. Deterministic:
+ * the same answers always produce the same transcript, so the extraction is
+ * reproducible and the stored provenance matches what the model actually read.
+ *
+ * @param {{question: string, answer: string}[]} answers
+ * @returns {string}
+ */
+export function interviewTranscript(answers) {
+ return answers
+ .map((row, i) => `Q${i + 1}: ${row.question}\nA${i + 1}: ${row.answer}`)
+ .join('\n\n');
+}
+
+/**
+ * The base persona an agent gets when the interview is skipped (or produced
+ * nothing usable). Built from what the wizard already knows, so the compiled
+ * persona_prompt is a real, complete voice rather than an empty shell.
+ *
+ * @param {object} input
+ * @param {string} [input.name]
+ * @param {string} [input.description]
+ * @param {string} [input.greeting]
+ * @returns {string}
+ */
+export function defaultPersonaBase(input = {}) {
+ const name = collapse(input.name) || 'this agent';
+ const description = collapse(input.description);
+ const greeting = collapse(input.greeting);
+
+ const lines = [
+ description
+ ? `You are ${name}. Your job is ${description.replace(/\.$/, '')}.`
+ : `You are ${name}, an embodied agent on three.ws that helps people with whatever they bring you.`,
+ 'Answer from what you actually know. When you are not sure, say so plainly in one line and give your best read anyway, with the caveat attached.',
+ 'Never invent facts, numbers, or sources. Never give financial advice.',
+ ];
+ if (greeting) {
+ lines.push(`You open a conversation with something in the spirit of: "${greeting}"`);
+ }
+ return lines.join('\n');
+}
+
+/**
+ * True when the interview produced enough signal to be worth sending to the
+ * extractor. One answered question is enough — the extractor is told to infer
+ * conservatively from a sparse interview rather than fabricate.
+ * @param {{answer: string}[]} answers
+ */
+export function hasInterviewSignal(answers) {
+ return Array.isArray(answers) && answers.length > 0;
+}