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.

async knowledge ingest via Upstash QStash (no more timeouts on big PDFs)

nirholas696f72a0d108
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index 6bfa25149..d27eb3733 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -511,8 +511,9 @@ create table if not exists widget_knowledge_docs (
byte_size integer not null default 0,
chunk_count integer not null default 0,
token_count integer not null default 0,
- status text not null default 'ready' check (status in ('processing', 'ready', 'failed')),
+ status text not null default 'ready' check (status in ('queued', 'processing', 'ready', 'failed')),
error text,
+ source_text text, -- held server-side until QStash worker consumes it
created_at timestamptz not null default now(),
updated_at timestamptz not null default now()
);
diff --git a/api/widgets/[id]/_knowledge.js b/api/widgets/[id]/_knowledge.js
index 2f7ac7047..12598ca35 100644
--- a/api/widgets/[id]/_knowledge.js
+++ b/api/widgets/[id]/_knowledge.js
@@ -14,6 +14,8 @@ import { embed, embeddingsConfigured, cosine } from '../../_lib/embeddings.js';
import { chunk, estimateTokens } from '../../_lib/chunker.js';
import { fetchAndExtract } from '../../_lib/text-extract.js';
import { shortId } from '../../_lib/ids.js';
+import { publishJob, qstashEnabled } from '../../_lib/qstash.js';
+import { env } from '../../_lib/env.js';
const MAX_DOCS_PER_WIDGET = 25;
const MAX_TEXT_BYTES = 4 * 1024 * 1024;
@@ -25,6 +27,11 @@ const MAX_PREVIEW_QS = 3;
// at a small unit.
const EMBED_BATCH = 64;
+// Docs bigger than this run async via QStash to avoid Vercel function timeouts
+// on large PDFs. Small docs stay inline so the studio UI doesn't have to poll
+// for the common case.
+const INLINE_CHUNK_THRESHOLD = 32;
+
const baseSchema = z.object({
title: z.string().trim().min(1).max(160).optional(),
source_type: z.enum(['url', 'text', 'pdf', 'markdown']),
@@ -196,30 +203,57 @@ export async function ingestKnowledge({ widgetId, userId, input }) {
const docId = shortId('wkd');
const tokenSum = chunks.reduce((s, c) => s + (c.token_count || 0), 0);
+ // Route to QStash worker when the doc is large enough to risk a function
+ // timeout AND a publish endpoint is configured. The worker reads source_text
+ // straight off the doc row — no chunk payload over the wire.
+ const shouldQueue = qstashEnabled() && chunks.length > INLINE_CHUNK_THRESHOLD;
+
await sql`
insert into widget_knowledge_docs
- (id, widget_id, user_id, title, source_type, source_url, byte_size, chunk_count, token_count, status)
+ (id, widget_id, user_id, title, source_type, source_url, byte_size,
+ chunk_count, token_count, status, source_text)
values
(${docId}, ${widgetId}, ${userId}, ${title.slice(0, 160)}, ${body.source_type},
- ${sourceUrl}, ${byteSize}, ${chunks.length}, ${tokenSum}, 'processing')
+ ${sourceUrl}, ${byteSize}, ${chunks.length}, ${tokenSum},
+ ${shouldQueue ? 'queued' : 'processing'},
+ ${shouldQueue ? text : null})
`;
- try {
- for (let i = 0; i < chunks.length; i += EMBED_BATCH) {
- const slice = chunks.slice(i, i + EMBED_BATCH);
- const embedded = await embed(slice.map((c) => c.content));
- const inserts = slice.map((c, j) => {
- const vec = Array.from(embedded[j]);
- return sql`
- insert into widget_knowledge_chunks
- (doc_id, widget_id, chunk_index, content, embedding, token_count)
- values
- (${docId}, ${widgetId}, ${i + j}, ${c.content},
- ${JSON.stringify(vec)}::jsonb, ${c.token_count})
- `;
+ if (shouldQueue) {
+ try {
+ await publishJob({
+ url: `${env.APP_ORIGIN}/api/widgets/${widgetId}/knowledge-process`,
+ body: { doc_id: docId, widget_id: widgetId },
+ deduplicationId: `wkd:${docId}`,
+ retries: 3,
});
- await sql.transaction(inserts);
+ } catch (err) {
+ // QStash itself failed — mark failed so the UI doesn't spin forever.
+ await sql`
+ update widget_knowledge_docs
+ set status = 'failed', error = ${String(err?.message || 'queue failed').slice(0, 500)},
+ source_text = null
+ where id = ${docId}
+ `.catch(() => {});
+ throw httpError(502, 'queue_failed', err.message || 'queueing failed');
}
+
+ return {
+ id: docId,
+ title: title.slice(0, 160),
+ source_type: body.source_type,
+ source_url: sourceUrl,
+ byte_size: byteSize,
+ chunk_count: chunks.length,
+ token_count: tokenSum,
+ status: 'queued',
+ preview_questions: synthesizePreviewQs(chunks),
+ };
+ }
+
+ // Inline path for small docs: embed + insert here, return when ready.
+ try {
+ await embedAndInsertChunks({ docId, widgetId, chunks });
await sql`update widget_knowledge_docs set status = 'ready' where id = ${docId}`;
} catch (err) {
await sql`
@@ -230,8 +264,6 @@ export async function ingestKnowledge({ widgetId, userId, input }) {
throw httpError(err.status || 502, 'embed_failed', err.message || 'embedding failed');
}
- const previewQuestions = synthesizePreviewQs(chunks);
-
return {
id: docId,
title: title.slice(0, 160),
@@ -241,10 +273,81 @@ export async function ingestKnowledge({ widgetId, userId, input }) {
chunk_count: chunks.length,
token_count: tokenSum,
status: 'ready',
- preview_questions: previewQuestions,
+ preview_questions: synthesizePreviewQs(chunks),
};
}
+// Shared embed+insert loop used by both the inline path and the QStash worker.
+async function embedAndInsertChunks({ docId, widgetId, chunks }) {
+ for (let i = 0; i < chunks.length; i += EMBED_BATCH) {
+ const slice = chunks.slice(i, i + EMBED_BATCH);
+ const embedded = await embed(slice.map((c) => c.content));
+ const inserts = slice.map((c, j) => {
+ const vec = Array.from(embedded[j]);
+ return sql`
+ insert into widget_knowledge_chunks
+ (doc_id, widget_id, chunk_index, content, embedding, token_count)
+ values
+ (${docId}, ${widgetId}, ${i + j}, ${c.content},
+ ${JSON.stringify(vec)}::jsonb, ${c.token_count})
+ `;
+ });
+ await sql.transaction(inserts);
+ }
+}
+
+// Worker entrypoint — called by QStash after publishJob in ingestKnowledge.
+// Reads source_text off the doc row, re-chunks (chunker is deterministic so
+// indices match what we returned to the client), embeds + inserts chunks,
+// clears source_text, marks ready. Idempotent: re-running after partial
+// failure picks up where chunks left off.
+export async function processQueuedDoc({ docId, widgetId }) {
+ const [doc] = await sql`
+ select id, widget_id, source_text, status, chunk_count
+ from widget_knowledge_docs
+ where id = ${docId} and widget_id = ${widgetId}
+ limit 1
+ `;
+ if (!doc) throw httpError(404, 'not_found', 'doc not found');
+ if (doc.status === 'ready') return { ok: true, status: 'ready' };
+
+ if (!doc.source_text || doc.source_text.length < 12) {
+ await sql`
+ update widget_knowledge_docs set status = 'failed',
+ error = 'source_text missing on queued doc'
+ where id = ${docId}
+ `.catch(() => {});
+ throw httpError(500, 'empty_source', 'no source_text on queued doc');
+ }
+
+ await sql`update widget_knowledge_docs set status = 'processing' where id = ${docId}`;
+
+ try {
+ const chunks = chunk(doc.source_text).slice(0, MAX_CHUNKS_PER_DOC);
+
+ // Idempotency: drop any partial chunks from a previous failed run so we
+ // don't end up with duplicates at the same chunk_index.
+ await sql`delete from widget_knowledge_chunks where doc_id = ${docId}`;
+
+ await embedAndInsertChunks({ docId, widgetId: doc.widget_id, chunks });
+
+ await sql`
+ update widget_knowledge_docs
+ set status = 'ready', source_text = null, error = null,
+ chunk_count = ${chunks.length}
+ where id = ${docId}
+ `;
+ return { ok: true, status: 'ready', chunk_count: chunks.length };
+ } catch (err) {
+ await sql`
+ update widget_knowledge_docs
+ set status = 'failed', error = ${String(err?.message || 'embed failed').slice(0, 500)}
+ where id = ${docId}
+ `.catch(() => {});
+ throw err;
+ }
+}
+
// "Your bot now knows X" preview — pulls salient sentences from the first few
// chunks and reshapes them into starter questions so the creator can sanity-
// check that the doc landed in retrieval. Heuristic, not LLM-generated.
diff --git a/api/widgets/[id]/knowledge-process.js b/api/widgets/[id]/knowledge-process.js
new file mode 100644
index 000000000..825db4dca
--- /dev/null
+++ b/api/widgets/[id]/knowledge-process.js
@@ -0,0 +1,78 @@
+// QStash worker endpoint for async knowledge embedding.
+//
+// Called by QStash after _knowledge.ingestKnowledge() queues large docs.
+// Verifies the inbound signature so only QStash (or replays of valid messages)
+// can trigger processing. Reads the queued doc by ID, embeds its chunks,
+// marks ready. Idempotent — safe to retry on transient failures.
+
+import { wrap, json, error, method } from '../../_lib/http.js';
+import { verifyQstashSignature, qstashEnabled } from '../../_lib/qstash.js';
+import { processQueuedDoc } from './_knowledge.js';
+import { env } from '../../_lib/env.js';
+
+function readRawBody(req, limit = 1_000_000) {
+ return new Promise((resolve, reject) => {
+ const chunks = [];
+ let total = 0;
+ req.on('data', (c) => {
+ total += c.length;
+ if (total > limit) {
+ reject(Object.assign(new Error('payload too large'), { status: 413 }));
+ req.destroy();
+ return;
+ }
+ chunks.push(c);
+ });
+ req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));
+ req.on('error', reject);
+ });
+}
+
+export default wrap(async (req, res) => {
+ if (!method(req, res, ['POST'])) return;
+
+ if (!qstashEnabled()) {
+ return error(res, 503, 'qstash_disabled', 'QStash not configured on this deployment');
+ }
+
+ const signature = req.headers['upstash-signature'];
+ const rawBody = await readRawBody(req).catch((err) => {
+ throw Object.assign(new Error(err?.message || 'body read failed'), {
+ status: err?.status || 400,
+ });
+ });
+
+ const widgetIdFromQuery = req.query?.id || '';
+ const verifyUrl = `${env.APP_ORIGIN}/api/widgets/${widgetIdFromQuery}/knowledge-process`;
+
+ try {
+ await verifyQstashSignature({ signature, body: rawBody, url: verifyUrl });
+ } catch (err) {
+ console.warn('[knowledge-process] signature verify failed:', err?.message);
+ return error(res, 401, 'invalid_signature', 'QStash signature verification failed');
+ }
+
+ let payload;
+ try {
+ payload = JSON.parse(rawBody || '{}');
+ } catch {
+ return error(res, 400, 'invalid_json', 'body must be JSON');
+ }
+
+ const docId = String(payload?.doc_id || '').trim();
+ const widgetId = String(payload?.widget_id || widgetIdFromQuery || '').trim();
+ if (!docId || !widgetId) {
+ return error(res, 400, 'invalid_request', 'doc_id and widget_id required');
+ }
+
+ try {
+ const result = await processQueuedDoc({ docId, widgetId });
+ return json(res, 200, { ok: true, ...result });
+ } catch (err) {
+ const status = err?.status || 500;
+ // Return 5xx so QStash retries with backoff. 4xx terminates retries.
+ const code = err?.code || 'process_failed';
+ console.error('[knowledge-process] failed', { docId, widgetId, err: err?.message });
+ return error(res, status, code, err?.message || 'processing failed');
+ }
+});
diff --git a/prompts/dashboard-next/02-avatars.md b/prompts/dashboard-next/02-avatars.md
new file mode 100644
index 000000000..aff72b922
--- /dev/null
+++ b/prompts/dashboard-next/02-avatars.md
@@ -0,0 +1,75 @@
+# 02 — Avatars page
+
+**Read `prompts/dashboard-next/_shared.md` first.** It contains the project rules, foundation paths, atomic classes, smoke-test recipe, and commit instructions. Then build the slice below.
+
+## Your slice
+
+Build the Avatars page at **`/dashboard-next/avatars`** — a grid of every avatar the signed-in user owns, with live 3D thumbnails and inline management.
+
+## Layout (top to bottom)
+
+1. **Page header row** — `.dn-h1` ("Avatars") + `.dn-h1-sub` ("Your 3D models, animated and ready to embed."). On the right of the row, a `.dn-btn.primary` "+ New avatar" that opens a small popover with three options:
+ - "From a selfie" → `/create/selfie`
+ - "Upload a GLB" → `/create`
+ - "From an existing avatar" → `/marketplace`
+
+2. **Filter bar** — a thin row with:
+ - Search input (`.dn-btn`-styled, full-width on the left) — filters client-side by name as the user types
+ - Visibility filter chips: All · Public · Unlisted · Private (one chip active, click toggles)
+ - Sort dropdown: Newest · Oldest · Name A→Z · Name Z→A
+
+3. **Avatar grid** — `grid-template-columns: repeat(auto-fill, minmax(220px, 1fr))`. Each card:
+ - Top: live `<threews-avatar avatar-id="…" hide-chrome bg="transparent">` (load via `<script src="/embed.js">` in the page HTML), 220×280 portrait
+ - Below: name (editable inline on click — pencil icon on hover), visibility tag (`.dn-tag.success` for public, `.dn-tag` neutral for unlisted, `.dn-tag.warn` for private), `relTime(updated_at)`
+ - Top-right corner of the card: a `⋮` menu button revealing: Rename · Change visibility · Copy embed snippet · Open in viewer (`/app#avatar=<id>`) · Download GLB · Delete (`.dn-btn.danger`, confirm modal required)
+
+4. **Pagination** — cursor-based using `/api/avatars?cursor=…&limit=24`. Render a `.dn-btn.ghost` "Load more" at the bottom while `next_cursor` is non-null. Auto-load the next page when the button enters the viewport (IntersectionObserver). Stop showing the button when `next_cursor === null`.
+
+## Files you create
+
+- `pages/dashboard-next/avatars.html` (use the page boilerplate from `_shared.md`, add `<script src="/embed.js"></script>`)
+- `src/dashboard-next/pages/avatars.js`
+
+Do not modify any other file.
+
+## API endpoints to use
+
+- `GET /api/avatars?limit=24&cursor=…` → `{ avatars: [{ id, name, visibility, updated_at, thumbnail_url?, source_meta? }], next_cursor }`
+- `PATCH /api/avatars/:id` → `{ name?, visibility? }` for inline rename and visibility change
+- `DELETE /api/avatars/:id` → confirm via a custom modal (not `confirm()`), then optimistically remove from the grid and toast on success / undo on failure
+- `GET /api/avatars/:id` → for the embed snippet (returns id you already have, but read the helper in `src/dashboard/dashboard.js` to see what extra metadata the existing avatar page uses)
+
+Read `src/dashboard/dashboard.js` for the existing avatar list/edit/delete patterns before writing — match them.
+
+## Empty / loading / error states
+
+- **First load:** show 8 skeleton cards (`.dn-skeleton` boxes shaped 220×280).
+- **No avatars at all:** `.dn-empty` block:
+ > **No avatars yet.** Build your first 3D agent — drop a selfie or upload a GLB.
+ > [Create from selfie] [Upload a GLB]
+- **Network failure:** inline error banner above the (empty) grid with a Retry button. Do not blank the page.
+- **Inline action failure** (rename, visibility change, delete): toast with the server error string, never silently fail.
+
+## Visual quality bar
+
+- Card hover: scale 1.015 over 180ms, soft accent glow (`box-shadow: 0 0 0 1px var(--nxt-accent-soft), 0 8px 24px rgba(0,0,0,0.4)`)
+- Visibility chips: pill-shaped, `--nxt-accent-soft` background when active
+- ⋮ menu opens with a 120ms fade + 4px upward translate; closes on outside click and ESC
+- Delete confirm modal uses a `.dn-panel` style with `.dn-btn.danger` for Delete, `.dn-btn.ghost` for Cancel
+
+## Verification
+
+Smoke-test per `_shared.md`:
+```bash
+node scripts/_dn-shot.mjs http://127.0.0.1:3010/dashboard-next/avatars /tmp/dn-avatars.png
+```
+Open the image. Verify:
+- At least one real 3D avatar is rendered in the grid (if the test user has avatars)
+- No console errors
+- Hover an avatar card in headless mode by appending `await p.hover('.dn-avatar-card:first-child')` before screenshot to capture the hover treatment
+
+Run `npx vite build` and confirm clean.
+
+## Commit message
+
+`dashboard-next: avatars page — live 3D grid + inline manage + cursor pagination`
diff --git a/prompts/dashboard-next/03-widgets.md b/prompts/dashboard-next/03-widgets.md
new file mode 100644
index 000000000..5e93428cd
--- /dev/null
+++ b/prompts/dashboard-next/03-widgets.md
@@ -0,0 +1,88 @@
+# 03 — Widgets page
+
+**Read `prompts/dashboard-next/_shared.md` first.** Then build the slice below.
+
+## Your slice
+
+Build the Widgets page at **`/dashboard-next/widgets`** — a grid of every widget the user has configured, each with a live iframe preview, stats, and quick management actions.
+
+## Layout (top to bottom)
+
+1. **Header row** — `.dn-h1` "Widgets" / `.dn-h1-sub` "Embed your agents anywhere — and see how they're performing." On the right, `.dn-btn.primary` "+ New widget" → `/widget-studio`.
+
+2. **Aggregate stat strip** — four small inline stats (not full cards, more like an inline summary row): Total widgets · Views (7d) · Chat turns (7d) · Avg session (s). Compact, single-line, separated by `·` characters in `--nxt-ink-fade`. Fetch in parallel; each shows `—` until ready. Skip the entire strip if all four return zero.
+
+3. **Widget grid** — `grid-template-columns: repeat(auto-fill, minmax(320px, 1fr))`, gap 14px. Each card is a `.dn-panel` with:
+ - **Top half (220px tall):** live `<iframe src="/widget#widget=<id>&kiosk=true" loading="lazy" sandbox="allow-scripts allow-same-origin allow-popups">`. This is the same surface the public embed uses, so we're dogfooding.
+ - **Bottom (padding 14px):** widget name (link to `/widget-studio?id=<id>`), tiny status badge (`.dn-tag.success` "Active" if last view < 24h else `.dn-tag` "Idle"), two columns of stats: Views 7d / Turns 7d.
+ - **Top-right corner ⋮ menu:** Open studio · Copy embed snippet · Duplicate · Open transcripts · Delete
+
+4. **Empty state** — `.dn-empty` if `/api/widgets` returns no rows:
+ > **No widgets yet.** Turn any avatar into an embeddable agent — from a brand widget to a talking guide.
+ > [Open widget studio]
+
+## Files you create
+
+- `pages/dashboard-next/widgets.html`
+- `src/dashboard-next/pages/widgets.js`
+
+Do not modify any other file.
+
+## API endpoints
+
+- `GET /api/widgets` → `{ widgets: [...] }` (or array; check `src/dashboard/dashboard.js`)
+- `GET /api/widgets/:id/stats?days=7` → views, turns, avg session
+- `POST /api/widgets/:id/duplicate` → returns new widget id, push it to the front of the grid
+- `DELETE /api/widgets/:id` → confirm modal, optimistic remove
+
+For the aggregate stat strip, sum across the per-widget `/stats` calls rather than inventing a new endpoint. Fire all stats requests in `Promise.allSettled` and use `.value` on fulfilled ones.
+
+## "Copy embed snippet"
+
+Opens a small popover (NOT a full modal) with three tabs:
+
+1. **Script tag** (default, easiest):
+ ```html
+ <script async src="https://three.ws/embed.js"
+ data-widget="WIDGET_ID"
+ data-reveal="interaction"
+ data-poster="auto"></script>
+ ```
+2. **iframe**:
+ ```html
+ <iframe src="https://three.ws/widget#widget=WIDGET_ID&kiosk=true"
+ width="600" height="600" frameborder="0"></iframe>
+ ```
+3. **Web component**:
+ ```html
+ <threews-avatar avatar-id="AVATAR_ID" hide-chrome></threews-avatar>
+ ```
+
+Each tab has a "Copy" button (uses `navigator.clipboard.writeText`) and a toast on success.
+
+## Empty / loading / error states
+
+- 6 skeleton cards on first load (220px iframe slot shown as `.dn-skeleton`)
+- Stats failure on a single card: the card still renders, stats slots show `—`
+- Whole list failure: inline error banner with Retry, do not blank the page
+
+## Performance note
+
+Iframes are heavy. Use `loading="lazy"` and `<iframe>` only when the card scrolls into view (IntersectionObserver). Until then, render a poster image at `/api/widgets/<id>/og` (the existing OG-card endpoint — confirms exists in `public/embed.js`) inside the card with a "Click to preview" overlay.
+
+## Verification
+
+Smoke-test:
+```bash
+node scripts/_dn-shot.mjs http://127.0.0.1:3010/dashboard-next/widgets /tmp/dn-widgets.png
+```
+Verify:
+- Cards render with either iframes or poster images
+- Stats appear or skeleton, never `NaN`
+- No console errors (a `Failed to load resource: /api/widgets/.../og` 404 is acceptable if a widget has no OG; gracefully fall back to a generic placeholder gradient)
+
+`npx vite build` must pass.
+
+## Commit message
+
+`dashboard-next: widgets page — live iframe previews + per-card stats + embed snippet popover`
diff --git a/prompts/dashboard-next/04-library.md b/prompts/dashboard-next/04-library.md
new file mode 100644
index 000000000..39941ffb3
--- /dev/null
+++ b/prompts/dashboard-next/04-library.md
@@ -0,0 +1,83 @@
+# 04 — Library page (animations · memory · strategy · voice)
+
+**Read `prompts/dashboard-next/_shared.md` first.** Then build the slice below.
+
+## Your slice
+
+Build the Library page at **`/dashboard-next/library`** — a single page that consolidates the four "creator inputs" today scattered across separate routes: Animations, Memory, Strategy, and Voice. Tabs at the top switch between them. URL hash drives the active tab (`#tab=animations` default).
+
+## Layout
+
+1. **Header row** — `.dn-h1` "Library" / `.dn-h1-sub` "Animations, memories, strategy notes, and voices your agents can draw on."
+
+2. **Tab strip** — four pills under the header, click to switch tabs, ARIA `role="tablist"`:
+ - Animations · Memory · Strategy · Voice
+ - Sticky to the top of the main scroll area
+ - URL hash updates on switch (`history.replaceState` so refresh-able)
+ - Active tab uses `.dn-tag.success` styling (accent background)
+
+3. **Active tab content** — render inside a single `<div data-slot="tab-body">`. Each tab is its own render function.
+
+## Per-tab content
+
+### Animations tab
+- Grid of every animation in the user's library (`GET /api/animations`)
+- Each card shows: clip name, duration (rounded to 0.1s), tags, source (uploaded / preset / mocap), and a tiny waveform / preview thumb if available
+- "Upload .glb / .fbx" button at the top of the tab — wires to `/api/animations/presign` flow (read `src/dashboard/dashboard.js` for the existing animation-upload code — copy that pattern exactly)
+- Empty state: `.dn-empty` with copy: "No animations yet. Upload a .glb or pick from our mocap library." with two CTAs: [Upload] [Browse presets → `/walk`]
+
+### Memory tab
+- A list of every persistent memory entry across all the user's agents (`GET /api/agents/me` to list agents, then per-agent `GET /api/agents/:id/memory` — match existing dashboard.js)
+- Each entry: timestamp, agent name (chip), short content preview, source (which conversation it came from). Click to expand the full text inline.
+- "+ Add a note" button at top — opens a small inline editor that POSTs to `/api/agents/:id/memory` (let the user pick which agent the note attaches to via a dropdown)
+- Empty state: "No memories yet. Your agents will save notes here from their conversations — or you can add one yourself."
+
+### Strategy tab
+- A single editable strategy document per agent (current dashboard has `/dashboard/strategy`). Dropdown at top picks agent; below, a `<textarea>` that loads `GET /api/agents/:id/strategy` and saves on blur via `PUT /api/agents/:id/strategy` (debounce 800ms). Auto-save indicator chip ("Saving…" → "Saved · `relTime`")
+- If the user has no agents, show `.dn-empty` "You don't have any agents yet" with CTA to `/dashboard-next/account` or `/create`
+
+### Voice tab
+- Voice picker for each agent: dropdown of available voices (poll `GET /api/voices/list` if it exists, otherwise fall back to whatever `public/dashboard/voice.html` uses)
+- For each agent, show: current voice name, a 12-second sample audio player (`<audio controls>` pointed at `GET /api/voices/sample?voice=<id>`), and a "Test with custom text" input that POSTs to `/api/voices/preview` (text-to-speech preview)
+- "Save" button per agent that PATCHes `/api/agents/:id` with `{ voice: <id> }`
+
+## Files you create
+
+- `pages/dashboard-next/library.html`
+- `src/dashboard-next/pages/library.js`
+- Optional: `src/dashboard-next/pages/library/animations.js`, `memory.js`, `strategy.js`, `voice.js` if you want per-tab split (recommended for readability — keep each under 250 lines)
+
+Do not modify any other file.
+
+## API endpoints
+
+Inspect `src/dashboard/dashboard.js`, `public/dashboard/memory.html`, `public/dashboard/strategy.html`, `public/dashboard/voice.html` for the canonical endpoint paths the existing code uses. **Reuse those paths verbatim** — do not invent new ones.
+
+Likely:
+- `GET /api/animations`, `POST /api/animations/presign`
+- `GET /api/agents`, `GET /api/agents/me`, `GET /api/agents/:id/memory`, `POST /api/agents/:id/memory`
+- `GET /api/agents/:id/strategy`, `PUT /api/agents/:id/strategy`
+- `GET /api/voices/list`, `POST /api/voices/preview`
+
+## Empty / loading / error states
+
+Every tab needs all three. A failed fetch in one tab must not break the others — they each have isolated try/catch blocks.
+
+## Verification
+
+Smoke-test each tab (one screenshot per tab):
+```bash
+for tab in animations memory strategy voice; do
+ node scripts/_dn-shot.mjs "http://127.0.0.1:3010/dashboard-next/library#tab=$tab" "/tmp/dn-library-$tab.png"
+done
+```
+Open all four images. Verify:
+- Tab strip highlights the active tab in each shot
+- Real data is present (animations list, memories, etc.) if the test user has any
+- No console errors across any tab
+
+`npx vite build` must pass.
+
+## Commit message
+
+`dashboard-next: library page — animations + memory + strategy + voice tabs`
diff --git a/prompts/dashboard-next/05-api-embed.md b/prompts/dashboard-next/05-api-embed.md
new file mode 100644
index 000000000..912ddbf7a
--- /dev/null
+++ b/prompts/dashboard-next/05-api-embed.md
@@ -0,0 +1,83 @@
+# 05 — API & Embed page
+
+**Read `prompts/dashboard-next/_shared.md` first.** Then build the slice below.
+
+## Your slice
+
+Build the API & Embed page at **`/dashboard-next/api`** — the developer / integrator surface. API keys, MCP integration, ready-to-paste embed snippets, embed-policy controls, and webhook config (if any).
+
+## Layout
+
+1. **Header** — `.dn-h1` "API & embed" / `.dn-h1-sub` "Issue keys, configure MCP clients, embed agents anywhere."
+
+2. **Section: API keys** — `.dn-panel`:
+ - Table of keys: name · prefix (e.g. `tws_…abc12`) · scopes (chips) · created · last used (`relTime` or "never") · Revoke button
+ - "+ New key" button → opens modal: name input, scopes multi-select (pull scopes list from the existing dashboard.js — likely `avatars:read avatars:write agents:read agents:write widgets:read widgets:write`), expiry dropdown (Never · 30d · 90d · 1y)
+ - On create, show the full secret ONCE in a copy-to-clipboard modal with a warning "This is the only time you'll see this key. Store it somewhere safe."
+ - Revoke is destructive — confirm modal required
+
+3. **Section: MCP setup** — `.dn-panel`:
+ - Subtitle: "Point Claude Desktop, Cursor, or any MCP client at your agents."
+ - Three tabs: Claude Desktop · Cursor · Generic JSON
+ - Each tab shows the exact config block to paste, with the user's actual API key pre-filled (use a placeholder `tws_yourkeyhere` and an inline "Pick which key" dropdown that swaps the displayed secret)
+ - Copy button per snippet
+ - "Test connection" button that calls a real endpoint (likely `/api/mcp/health` — check existing dashboard.js for the actual MCP test endpoint) and shows pass/fail inline
+
+4. **Section: Embed snippets** — `.dn-panel`:
+ - Dropdown: pick one of the user's avatars OR widgets
+ - Three tabs: Script tag · iframe · Web component (`<threews-avatar>`)
+ - Live preview pane next to the snippets (320×320 iframe) so the user sees what they're about to paste
+ - Each snippet has knobs that update both the code and the preview:
+ - Width · Height · Background (transparent / dark / light) · Reveal mode (auto / interaction) · Hide chrome (checkbox)
+ - Copy button per snippet
+
+5. **Section: Embed policy** — `.dn-panel`:
+ - Origin allowlist per avatar — table of avatar → allowed origins (one per line), saved via PATCH to `/api/embed-policy/:avatarId` (read `api/_lib/embed-policy.js` for shape — `api/_mcp/embed-policy.js` exists). Default is `*` (anywhere). User can lock down to specific origins.
+ - Per-row Save button (debounced auto-save on blur, indicator chip)
+ - Help link: "Why does this matter?" → tooltip / inline explainer
+
+## Files you create
+
+- `pages/dashboard-next/api.html`
+- `src/dashboard-next/pages/api.js` (the file, not the directory — `api.js` is fine because it's under `pages/`)
+
+Do not modify any other file.
+
+## API endpoints
+
+Inspect `src/dashboard/dashboard.js`, `public/dashboard/storage.html`, and `public/dashboard/embed-policy.html` for the exact endpoint paths and request/response shapes — match them exactly.
+
+Likely:
+- `GET /api/keys` / `POST /api/keys` / `DELETE /api/keys/:id`
+- `GET /api/embed-policy?avatar_id=…` / `PUT /api/embed-policy/:avatar_id`
+- `GET /api/mcp/config` if it exists, otherwise build the JSON client-side from the user's session
+- `GET /api/avatars` and `GET /api/widgets` for the dropdowns
+
+## Empty / loading / error states
+
+- Keys empty: `.dn-empty` "No keys yet. Issue one to start hitting the API." + [+ New key]
+- MCP test failure: red chip inline next to the button
+- Embed-policy save failure: revert local state, toast with server error
+
+## Visual quality bar
+
+- Code snippets use a `<pre><code>` block with a dark inner background (`#0a0a10`), 1px stroke, monospace, soft accent line on the left
+- Copy buttons sit absolute top-right of the code block, become more visible on hover
+- Tab strips use the same pill style as the Library page
+
+## Verification
+
+```bash
+node scripts/_dn-shot.mjs http://127.0.0.1:3010/dashboard-next/api /tmp/dn-api.png
+```
+Verify:
+- All four sections visible
+- Real keys list (if test user has any) or empty state
+- Embed snippet preview iframe actually renders
+- No console errors
+
+`npx vite build` passes.
+
+## Commit message
+
+`dashboard-next: api & embed page — keys + MCP setup + live embed snippets + policy`
diff --git a/prompts/dashboard-next/06-monetize.md b/prompts/dashboard-next/06-monetize.md
new file mode 100644
index 000000000..5936595bd
--- /dev/null
+++ b/prompts/dashboard-next/06-monetize.md
@@ -0,0 +1,95 @@
+# 06 — Monetize page
+
+**Read `prompts/dashboard-next/_shared.md` first.** Then build the slice below.
+
+## Your slice
+
+Build the Monetize page at **`/dashboard-next/monetize`** — consolidates Revenue, Payments, Subscriptions, Plan & Usage, Withdrawals, Earnings, and Tokens into one creator-friendly money hub.
+
+## Layout (top to bottom)
+
+1. **Header** — `.dn-h1` "Money" / `.dn-h1-sub` "Where your agents earn — and where it goes."
+
+2. **Hero metric row** — three large stat cards (`.dn-panel`):
+ - **Available to withdraw** (`formatUsdc`) — sum of `referral_earnings_total` + agent revenue not yet withdrawn. Below: `.dn-btn.primary` "Withdraw" → opens withdraw modal
+ - **30-day revenue** (`formatUsdc`) — `/api/billing/revenue?from=<30d ago>&to=<now>&granularity=day`
+ - **Active subscriptions** (count + `formatUsdc`/mo MRR) — `/api/billing/subscriptions` (or whatever the existing path is — check `src/dashboard/dashboard.js`)
+
+3. **Revenue chart** — `.dn-panel`:
+ - Title "Revenue · last 30 days" with a small dropdown to switch range (7d / 30d / 90d / 1y)
+ - Vanilla `<svg>` bar chart, 240px tall, full width. One bar per day. Hover shows tooltip with day + amount.
+ - Granularity adjusts with range: day for ≤90d, week for >90d
+ - Source breakdown legend below the chart: how much came from API calls · subscriptions · skill unlocks · tips · token royalties
+
+4. **Recent payments table** — `.dn-panel`:
+ - Columns: When (`relTime`) · Source · Amount · Status (`.dn-tag.success` "Settled" / `.dn-tag.warn` "Pending" / `.dn-tag.danger` "Failed") · TX link
+ - Source examples: "API call · key tws_abc" · "Subscription · @handle" · "Skill unlock · pump-strategy"
+ - Pagination: cursor or "Load more"
+ - Filter chips at top: All · Subscriptions · API · Skills · Tips
+
+5. **Withdrawals section** — `.dn-panel`:
+ - Pending withdrawals table at top (id · amount · chain · status · est arrival)
+ - "Withdraw now" button → opens modal: chain selector (Solana / Base / Polygon / etc, only those with treasury keys configured), destination address (validate format per chain), amount input (clamps to available)
+ - Past withdrawals (last 10) collapsed under a "Show past withdrawals" toggle
+
+6. **Plan & usage** — `.dn-panel`:
+ - Current plan name + price + renewal date (`relTime`)
+ - Usage bars: avatars (X / Y), widgets (X / Y), LLM tokens this period (X / Y), storage GB (X / Y)
+ - "Upgrade plan" CTA → `/pricing`
+
+7. **Token earnings** (only if user has launched a token via Pump.fun):
+ - Per-token row: ticker · holders · royalties earned · "View token" link
+ - Hide section entirely if `/api/tokens?owner=me` is empty
+
+## Files you create
+
+- `pages/dashboard-next/monetize.html`
+- `src/dashboard-next/pages/monetize.js`
+
+Do not modify any other file. This page is dense — consider splitting into per-section helper functions for readability, all in the one `monetize.js` file or under `src/dashboard-next/pages/monetize/` if helpful.
+
+## API endpoints
+
+Read `src/dashboard/dashboard.js` and the existing `public/dashboard/` HTML files (`monetization.html`, `payments.html`, `subscriptions.html`, `billing.html`, `revenue.html`, `withdrawals.html`, `earnings.html`, `tokens.html`) to find the canonical endpoint paths. **Reuse them exactly.**
+
+Likely:
+- `GET /api/billing/revenue` `?from=&to=&granularity=`
+- `GET /api/billing/usage`
+- `GET /api/billing/payments`
+- `GET /api/billing/subscriptions`
+- `GET /api/agent-withdrawals` / `POST /api/agent-withdrawals`
+- `GET /api/tokens?owner=me`
+
+If an endpoint doesn't exist (e.g. unified "available to withdraw"), compute client-side from the data you do have, or surface `—` with a tooltip — don't invent backend.
+
+## Empty / loading / error states
+
+- Skeleton bars on the chart while loading
+- Empty payments: `.dn-empty` "No payments yet. Hook a widget into your site or issue an API key to start earning."
+- Withdrawal modal errors (insufficient balance, bad address): inline error message, keep modal open
+
+## Chart implementation hint
+
+Vanilla SVG. No chart library. Each bar:
+```js
+<rect x="..." y="..." width="..." height="..." fill="var(--nxt-accent)" rx="2"
+ data-day="..." data-amount="..." />
+```
+On mouseover, position a `<g>` tooltip absolutely. Keep it under 80 lines.
+
+## Verification
+
+```bash
+node scripts/_dn-shot.mjs http://127.0.0.1:3010/dashboard-next/monetize /tmp/dn-monetize.png
+```
+Verify:
+- Hero metrics render real values (or `—` with tooltip)
+- Chart bars visible
+- Tables render with real or empty-state content
+- No `NaN`, no `undefined`, no console errors
+
+`npx vite build` passes.
+
+## Commit message
+
+`dashboard-next: monetize page — revenue chart + payments + withdrawals + plan + tokens`
diff --git a/vercel.json b/vercel.json
index 6143c7f10..bb9ded240 100644
--- a/vercel.json
+++ b/vercel.json
@@ -1281,6 +1281,10 @@
"src": "/api/widgets/([A-Za-z0-9_-]+)/knowledge",
"dest": "/api/widgets/[id]/knowledge?id=$1"
},
+ {
+ "src": "/api/widgets/([A-Za-z0-9_-]+)/knowledge-process",
+ "dest": "/api/widgets/[id]/knowledge-process?id=$1"
+ },
{
"src": "/api/agent-strategy",
"dest": "/api/agent-strategy"