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.

57.2 KB
Raw Blame

Onboarding & Agent Creation

UX Flow Atlas — Cluster 01. Traced from real source. Route → source mapping resolved via vercel.json routes[] (Vite serves pages/*.html directly in dev; prod rewrites the clean route to the same HTML file).


Onboarding Wizard — /start

  • Source: pages/start.html + src/start.js (imports src/shared/usd-price.js, src/templates.js, src/shared/log.js)
  • Entry point: Marketing/nav CTAs and getting-started.js discovery layer. Returned-to as a round-trip target from /create/selfie and /create (those flows pass ?wizard=1&next=<return to /start?from=...>). Also accepts deep-links /start?template=<id> and resumes via sessionStorage key wz:state.
  • Prerequisites / gates: None to start (anonymous-friendly). Auth is hit lazily at deploy: every apiPost first fetches /api/csrf-token (credentials: include) — an unauthenticated user fails at Step 4 (deploy) with a server error toast. No wallet connect, no $THREE gate.
  • Steps (N):
    1. Land on /start; the template gallery screen renders (initTemplateGallery). If ?template=<id> matches, it auto-applies and jumps to Step 2 (skips gallery). If a saved wz:state exists, gallery is bypassed and the wizard resumes.
    2. (optional) Click a template card → applyTemplate prefills description/skills/model/cryptoMode and advances to wizard Step 2; OR click "Start from scratch" (#btn-blank-start) → reveals blank wizard at Step 1.
    3. Wizard Step 1 — Avatar. Choose an avatar method: "Selfie" (#btn-selfie) → navigates to /create/selfie?wizard=1&next=<return>; "Editor" (#btn-editor) → /create?wizard=1&next=<return>; "Upload" (#btn-upload) → opens file picker.
    4. (optional) For Upload: select a .glb/.gltf ≤ 50 MB → POST /api/avatars (multipart, with CSRF) → on success the avatar thumbnail/name render in the Step-1 preview.
    5. (optional) Click "Skip" (#btn-skip-step) on Step 1 to advance avatar-less to Step 2.
    6. Step 2 — Name & Brain. Type agent name (required) and bio/description; optionally click a personality preset (researcher/support/podcast/artist/assistant/crypto/community/defi) to fill the bio; pick a model (data-model). Click "Continue" → validateStep requires a non-empty name (else toast "Please give your agent a name.").
    7. (optional) Toggle Crypto mode (#crypto-toggle) to reveal crypto personality + crypto skills sections.
    8. Step 3 — Skills. Toggle skill cards (data-skill: memory/think/pumpfun/solana/x402/web). Click "Continue to deploy".
    9. Step 4, Deploy. startDeploy() runs automatically: (a) POST /api/agents (name, description, resolved skills via SKILL_MAP + BASE_SKILLS, optional avatar_id); (b) POST /api/widgets (type talking-agent, config.agent_id); (c) builds embed <script> snippet + live URL /agents/<id>. Shows live status labels per phase.
    10. On deploy success: success panel shows " is live", live URL link, and an embed code block. (optional) Click "Copy" (#copy-embed) to copy the embed snippet. Click "Continue".
    11. Step 5: Earn (conditional). If crypto skills were selected: enter a per-call price (USDC, shown as USD-equivalent hint) and a payout wallet (chain auto-detected SOL vs ETH/BASE). Click "Save & finish" → saveEarnSettings() POSTs /api/agents/:id/skills/set-price (USDC mint) and /api/billing/payout-wallets (through withPayoutStepUp: replacing a live payout wallet answers 403 step_up_required and asks for the account password, while a first wallet needs none; a failed wallet save is reported as a problem rather than swallowed), then clears state and redirects to /dashboard?welcome=1. If no crypto skills: a "skip" panel shows and the button reads "Go to dashboard" → straight to /dashboard?welcome=1.
  • Decision points / branches: template vs blank start; resume saved session vs fresh; avatar method (selfie / editor / upload / skip); crypto-mode on/off → governs whether Step 5 is the Earn panel (price+wallet) or the Skip panel; deploy success vs failure (retry button injected).
  • External calls / dependencies: GET /api/csrf-token; POST /api/avatars (upload); POST /api/agents; POST /api/widgets; POST /api/agents/:id/skills/set-price; POST /api/billing/payout-wallets. No on-chain txn from this page (wallet address is just registered as a payout target).
  • Success state: A real deployed agent + public widget, an embeddable <script> snippet, a live /agents/<id> URL, optional monetization configured; user lands on /dashboard?welcome=1.
  • Empty / error states: Toast (#wz-toast) for validation ("Please give your agent a name.", file-too-large). Deploy failure recolors the status label red and injects a "Try again" button that re-runs startDeploy(). Upload errors restore the card label.
  • Step count: 6 required (gallery → name → skills → deploy auto → deploy success → finish) + ~5 optional (template apply, avatar upload, skip avatar, crypto toggle, earn setup).

Avatar Method Picker — /create

  • Source: pages/create.html + src/create.js (imports src/account.js, src/avatar-creator.js, src/guest-avatar.js, src/shared/template-picker.js, src/shared/attended-rotation.js, src/shared/share-target.js, src/shared/wizard-return.js; the page also loads src/shared/crypto-optional.js and src/wallet-auth.js as their own module scripts)
  • Entry point: Nav/landing CTA; reached from /start Step 1 "Editor" with ?wizard=1&next=. Also handles ?fork=<avatarId> deep-links (remix an existing avatar).
  • Prerequisites / gates: Anonymous-friendly for the base-avatar editor / template / studio / direct GLB upload (guest avatar staged in IndexedDB; auth deferred to /create-review). Auth-gated paths: the selfie card (requireAuthForSelfie → redirect /login?next=/create/selfie), the prompt card (redirect /login?next=/create/prompt), and the video card (redirect /login?next=/create/video). Signed-in users also hit an avatar-quota check (/api/usage/summary) before opening a creator. No wallet/$THREE gate.
  • Steps (N):
    1. Land on /create. The page now opens with a four-card intent hub: "Build an AI agent" → /create-agent, "Make a 3D avatar" → #avatar-options (tagged "You're here"), "Generate a 3D model" → /forge, "Launch a token world" → /launchpad. Under the hub, a footer line points a returning creator at everything they have already made (/mine, "My creations") and at /play for live token worlds. The avatar method cards live below at #avatar-options. Card accessible names come from their visible text (the intent cards carry no aria-label; the current one sets aria-current="location"), and the method cards are role="button" with tabindex="0".
    2. boot() probes /api/config for the videoAvatar feature flag with three outcomes: off dims the video card with a "Coming soon" chip and CTA (keyboard activation gets the same explanation as a click), an unanswered probe keeps the card live and re-asks on activation, and on leaves it untouched. For signed-in users with avatars it loads /api/avatars (the { avatars } envelope) to render a "Start from one of yours" remix strip; a thumbnail whose storage object expired falls back to the silhouette. The prompt card cycles 7 example prompts with a reduced-motion-aware typewriter (#card-prompt-example).
    3. (optional) If ?fork=<id> present: handleFork runs last, after every card is wired, POSTing /api/avatars/fork (signed-in → owned copy → redirect /avatars/<id>); on 401/403 falls back to fetching the source, downloading its GLB, staging a guest copy, and redirecting to /create-review. A remix that cannot load renders a persistent inline alert in #create-alert-slot ("That remix could not be loaded") with "Try the remix again" and "Start something new instead" (which drops ?fork= from the URL), not a toast, so the visitor is never left on a page of cards wired to nothing.
    4. Choose a creation method card: Customize a base avatar (card-default-editor → AvatarCreator.openDefaultEditor), Describe it to 3D (card-prompt → /create/prompt, auth-gated), Start with a template (card-customize → createFromTemplate), Scan yourself to 3D (card-selfie → /create/selfie, auth-gated), Talking avatar video (card-video-avatar → /create/video, feature-flagged + auth-gated), Living world (Cosmos) (card-cosmos → /cosmos), Upload your own GLB (card-upload-glb → #glb-input), or Avatar Studio (beta) (card-agent-studio → /create/studio). The recommended base-editor card is the page's only 3D preview and it is fully deferred: the card paints a poster image, and both the model-viewer element bundle and the model itself arrive on the first hover, focus or tap (src/shared/attended-rotation.js), so a visit that never touches the card pays for neither. Below the cards, a footnote sends "need a model to upload" to /avatar-studio or /forge, and "bringing an avatar from another platform" to /import/rpm.
    5. (optional) Upload path: pick a .glb; handleGlbFile validates the glTF magic bytes, then stageAndReview stashes the blob via guest-avatar.js (IndexedDB) and navigates to /create-review.
    6. (optional) Editor/Template path: the in-page AvatarCreator produces a GLB blob → stageAndReview → /create-review.
    7. (optional) Remix strip: click a saved avatar thumbnail → handleFork(av.id) (same fork path as step 3).
    8. (optional) Share-sheet handoff (Android, and the iOS app): a file shared into the installed app is POSTed to /create/share, parked in the Cache API by public/share-target-sw.js, and the visitor lands here with ?shared=glb (a .glb, pulled back out through src/shared/share-target.js and fed into the upload path), ?shared=1 (a photo, handed on untouched to /create/selfie?shared=1), ?shared=nosw (the worker was not installed yet; share again) or ?shared=error. The iOS app has no service worker, so its share extension parks the files in the app instead and opens ?shared=glb&inbox=<id> (or /create/selfie?shared=1&inbox=<id> for photos); takeSharedFiles() reads them from the app's native bridge before falling back to the Cache API. The read is one-shot, so a reload never re-attaches the file.
  • Decision points / branches: intent hub (agent wizard / avatar options / Forge / launchpad) vs direct card pick; fork vs fresh; eight creation method cards (base editor / prompt / template / selfie / video / Cosmos / upload / studio); anonymous (stage→review) vs signed-in (direct save/fork); video flag on/off; avatar-quota reached vs not.
  • External calls / dependencies: GET /api/config; GET /api/avatars; GET /api/usage/summary; POST /api/avatars/fork; GET /api/avatars/:id + raw GLB fetch (guest fork). External avatar-platform iframes loaded by AvatarCreator.
  • Success state: A staged or owned avatar; the user is forwarded to /create-review (anonymous) or /avatars/<id> (forked) — onward to agent creation.
  • Empty / error states: status-toast for invalid GLB, quota-limit, a feature probe that could not reach three.ws, and a shared file that was not a .glb; fork failure uses the inline alert; video card carries a "Coming soon" chip when the flag is off; the boot blackout clears after 6 s even if /api/auth/me never answers (treated as signed out, the auth-gated cards re-check at /login); save overlay (#save-loading) covers staging. Remix strip stays hidden for anonymous users / users with no avatars.
  • Step count: 2 required (land → pick a method) + ~5 optional (fork, upload, editor produce, remix, shared file).

Guest Avatar Review: /create-review

  • Source: pages/create-review.html (inline auth boot) + src/create-review.js (imports src/account.js, src/api.js, src/attach-avatar-to-agent.js, src/guest-avatar.js, src/voice/talk-scene.js, src/idle-animation.js, src/usdz-pipeline.js, src/create-review-features.js, src/shared/log.js)
  • Entry point: The terminal step of every anonymous creation path in this cluster. /create sends users here after a GLB upload, after the in-page AvatarCreator (base editor or template) produces a blob, and as the 401/403 fallback of ?fork=<id>. The gallery's "Surprise me" reveal ("Make it mine") also stages into it (cluster 05). Re-entered by the /login?next=/create-review round trip.
  • Prerequisites / gates: A staged guest record in IndexedDB. boot() calls loadGuest(); with nothing staged it location.replace('/create') before any UI renders. The page itself loads anonymously: an inline fetch('/api/auth/me') resolves window.__authed and dispatches three-ws:auth-resolved, and applyAuthState only relabels the save button. Auth is required to save, nothing else. No wallet/$THREE gate.
  • Steps (N):
    1. Land. The staged blob mounts in a TalkScene parsed straight from the Blob (not the object URL, which sidesteps a "Failed to fetch" race when the page reloads mid-mount), IdleAnimation layers breathing, blink, micro-saccades and weight shift, and a baked av-idle-breath emote (falling back to idle) pulls the model out of T-pose. #tag-source and #tag-size label the provenance and file size.
    2. Name it. #f-name live-updates the heading plus a three.ws/@<slug> handle preview with its own copy button. An auto-generated Avatar #abc123 name is deliberately not prefilled, so the placeholder hint stays visible.
    3. Pick a creation type: Agent (#type-btn-avatar, the default for every source) or Item (#type-btn-object). Agents show the capability grid; items swap in #item-nudge explaining that items have no brain, with a one-click "make it an agent" promote back to the agent path.
    4. (optional) Try any of the 15 capability tiles before saving: Body (toggles a live emote strip on the mounted scene), Voice preview, Voice Library, Video, Mocap, On-Chain Identity, Token Launch, Paid Skills, Analytics, Embed Anywhere, Widgets, Developer API, Knowledge, Reputation, Download. All but Body open modals from create-review-features.js.
    5. Click save. Signed out the button reads "Sign in to save": it arms a 3dagent:guest-avatar-resume sentinel in sessionStorage and redirects to /login?next=/create-review; on return applyAuthState sees the sentinel and fires the save automatically. The sentinel is also armed before the network call so a session that expired since the cached auth hint still resumes.
    6. saveRemoteGlbToAccount runs behind a full-screen overlay with a real percent bar and a cancel button (backed by an AbortController, disabled once the upload crosses into commit).
    7. Item path: clear the staged record, best-effort thumbnail capture, redirect to /create/next?avatarId=…&name=…&from=object.
    8. Agent path: attachAvatarToAgent (GET /api/agents/me, POST /api/agents if the user has none yet, then PUT /api/agents/:id), then a thumbnail capture off the live canvas and an in-browser GLB to USDZ conversion uploaded for iOS Quick Look, both best-effort under an 8 s cap, then redirect to /create/next?agentId=…&avatarId=…&name=…&from=agent. If the tab is hidden, a system notification fires (only when permission was already granted elsewhere).
  • Decision points / branches: nothing staged (silent bounce to /create) vs staged; Agent vs Item (governs the save endpoint chain, the button label, and grid vs nudge); signed-in save vs login round trip with auto-resume; cancel mid-upload (returns to the editing UI with no error surface); plan_limit_count vs generic failure; upload_blocked arms a one-shot auto-retry on the next online event, disarming after 30 s; "Start over" (confirm, clear the staged record, back to /create).
  • External calls / dependencies: GET /api/auth/me; saveRemoteGlbToAccount (presign + R2 PUT + commit); GET /api/agents/me; POST /api/agents; PUT /api/agents/:id; POST /api/avatars/thumbnail; POST /api/avatars/presign-usdz + R2 PUT + PATCH /api/avatars/:id (USDZ). Also window.__twsGuide.complete('create') for the getting-started layer.
  • Success state: The guest blob is promoted to a real owned avatar (and on the agent path attached to a real agent), the staged IndexedDB record is cleared, the "create your first avatar" guide step is marked done, and the user lands on /create/next.
  • Empty / error states: No staged record redirects to /create before render. A viewer mount failure swaps #viewer-loading for "Couldn't render this model." and leaves the save path intact. The save overlay doubles as the error surface, with per-stage titles (presign / commit / fetch / upload_blocked / upload_failed / upload_aborted) and Retry + Cancel; retry re-runs the whole pipeline from the blob still in memory. Plan-limit shows a toast instead of the overlay.
  • Step count: 3 required (land → name → save) + ~4 optional (creation type, capability tiles, handle copy, start over).

Post-Creation Next Steps: /create/next

  • Source: pages/create-next.html (inline <script type="module">; there is no src/ module for this page)
  • Entry point: The single navigation target of a successful /create-review save, carrying ?agentId= / ?avatarId= / ?name= / ?from=. Not linked from nav; it exists to catch the moment right after a creation lands.
  • Prerequisites / gates: None enforced. Everything renders from the query params; the two enrichment fetches are credentialed and fail soft, so the screen still works signed out or offline. No wallet/$THREE gate.
  • Steps (N):
    1. Land. The script branches the whole screen on agent vs avatar: headline, step-1 target/label/description, step-2 and step-3 targets, the back link, the "3D AI Agent" vs "3D Avatar" tag, and the "I'll do this later" destination.
    2. mountStage() embeds /walk-embed as a non-interactive portrait (controls=none&click=false, transparent background, studio env) so the new figure idles instead of standing in a T-pose. Orbit stays on except under prefers-reduced-motion. An initial-letter placeholder covers the first frame and stays permanently if the model cannot be resolved.
    3. loadAgent() fetches GET /api/agents/:id (or GET /api/avatars/:id) to resolve the real name for the label, the initial, the document title, and the share text, falling back to the ?name= param. On the agent path it also marks step 1 done when the agent already has a system or persona prompt, and step 3 "Live" when it is registered on-chain.
    4. A single confetti burst fires about 450 ms in, once, and is skipped entirely under prefers-reduced-motion.
    5. Pick a next step: 1. Chat with your agent (/app?agent=<id>) or Give it a brain (/create-agent?avatar=<id>) for the avatar-only case; 2. Embed it anywhere (/embed.html?avatar=|?agent=); 3. Deploy on-chain (/deploy?agent=<id>, or /create-agent?avatar=<id>&then=deploy), optional; 4. Put it in a world (/diorama), optional; 5. See your profile (/profile).
    6. (optional, agents only) Copy the inline iframe embed snippet from #cnEmbed without leaving the page, copy the public /agents/<id> link, or share to X with a prefilled intent URL.
    7. (optional) "I'll do this later" exits to /dashboard/agents (agent) or /dashboard/avatars (avatar).
  • Decision points / branches: agent (?agentId) vs avatar-only (?avatarId) vs neither (placeholder portrait, generic step targets); already-has-a-prompt and already-on-chain mark their steps done instead of inviting a repeat; reduced-motion disables both the confetti and the orbit; agent-only surfaces (embed snippet, copy link, share on X) stay hidden for avatar saves.
  • External calls / dependencies: GET /api/agents/:id; GET /api/avatars/:id; the /walk-embed renderer in an iframe. Both fetches are wrapped so a failure degrades to the ?name= param.
  • Success state: The user sees their live, idling creation and a ranked set of real next steps, each deep-linked to the specific agent or avatar just created.
  • Empty / error states: No id params keeps the initial-letter placeholder and generic step targets. A failed name lookup falls back to ?name=, then to "Your agent" / "Your avatar". Clipboard failures relabel the button to "Press ⌘C" and toast a manual-copy hint.
  • Step count: 1 required (land → pick a next step) + ~3 optional (copy snippet, copy link/share, defer to dashboard).

Agent Creation Wizard — /create-agent

  • Source: pages/create-agent.html + src/create-agent.js (imports src/api.js, src/account.js, src/agents/guest-agent.js, src/create-agent-draft.js, src/voice/voice-setup.js, src/agents/persona-interview.js, src/analytics.js, src/shared/log.js, src/shared/glb-magic.js)
  • Entry point: Nav/landing CTA, marketplace "create your own" links, the /create intent hub, and the /agent/new 301 (see routing notes). Avatar surfaces hand off with ?avatar_id=&avatar_glb=&avatar_name= (applyAvatarHandoff pre-seeds the model step).
  • Prerequisites / gates: Try-first: anyone can build all six steps signed out. boot() calls getMe() but only records state.authed; there is no auth gate on the form. The one place an account is required is the ship step: submit() with no session saves the draft and redirects to /login?next=/create-agent; boot() restores the draft on return and drops the user on Review ("Welcome back, is ready. Ship it below."). Each agent gets a wallet at create. No $THREE gate.
  • Steps (N):
    1. Land; boot() resolves auth. Signed out, the ship CTA relabels to "Sign in to ship →" and a "no account needed to build" note (#build-free-note) unhides. A fresh guest draft (see below) or a guest-companion claim (peekGuestAgent() carries the companion's name in) can prefill the form.
    2. Step 0 (Basics). Enter name (required, ≤60), description (≤280), and tags (≤8, Enter/comma to add). (optional) Use the "Build it for me" AI box: type a one-line brief (or a chip / "✦ Surprise me") → POST /api/agents/suggest-spec → the returned spec fills the whole wizard and jumps to Review. Guests can generate too; the guest rate limit maps a 429 to a sign-in nudge. Click "Next" → validates name present.
    3. Step 1, Model. Choose a body via one of four tabs (a real ARIA tablist: arrow keys and Home/End move between them): Starter (4 shipped GLBs: Vern/CZ/Saga/Boss with model-viewer previews), Library (your owned avatars, paginated via GET /api/avatars, filtered to avatar/creature categories; signed out it never fires the request and shows "Sign in to reuse an avatar you already made" with a Sign in button that saves the draft first), Upload (drag-drop .glb ≤16 MB, validated by isValidGlbMagic: the glTF magic, version 2, and a declared length that is at least 20 bytes and no larger than the file, so a truncated upload is refused before it is sent), or Add later (must tick the #f-skip-ack confirm box → default starter assigned at create). Selected model renders in the live preview. Click "Next" → requires a starter/upload/library pick or acknowledged skip.
    4. Step 2 — Skills. Five core skills (greet/present-model/validate-model/remember/think) are locked on; toggle optional skills (wave/dance/pump-fun/explain-gltf/web-search). Click "Next".
    5. Step 3, Personality. Pick category (14 marketplace categories), greeting (≤200), and profile/system prompt (≤2000). (optional) Run the onboarding interview (#interview-*): answer any of the shared INTERVIEW_QUESTIONS in your own words → POST /api/persona/interview runs them through the platform LLM chain and writes the extracted paragraph into the profile field (editable), with tone tags rendered as chips; the structured result (traits, tone tags, vocabulary, answer provenance) rides in state until the agent exists. Click "Next" (soft tip if publishing without category+prompt).
    6. Step 4, Voice. Pick Built-in voice or Clone your voice (data-voice buttons). Choosing custom mounts VoiceSetup in bind:'later' mode: record or upload a short sample (validated in-browser, with inline BYOK ElevenLabs key entry via PATCH /api/user/provider-keys); the sample is held in memory and bound after create. Click "Next".
    7. Step 5 (Review). Editable summary grid (each row jumps back to its step). Toggle "Publish to marketplace" (#f-publish, default on). Click "Create" (or "Sign in to ship…" when signed out, which round-trips through /login and resumes here).
    8. submit(): (a) resolves the body to a real owned avatar, via saveRemoteGlbToAccount for starter URL or uploaded file (with upload % progress), library = connect directly, none = assign default starter; (b) POST /api/agents (name, description, skills, avatar_id, meta with greeting/voice/tags); (c) if a custom voice sample is held → voiceSetup.bindTo(agent.id) clones it onto the new agent (non-fatal: a failure becomes a soft warning); (d) if publish opted-in AND category+prompt present → POST /api/marketplace/agents/:id/publish; (e) if the interview produced a result → POST /api/agents/:id/persona/save persists the structured persona with interview provenance (also best-effort).
    9. Success panel: " is ready", 3D preview if public, and buttons: Go live (/agents/<id>/wallet#activate, primary; claims the on-chain welcome grant), Fund wallet (/agents/<id>/wallet#deposit), Open (/agents/<id>), Edit (/agents/<id>/edit), Create another (/create-agent), and View my profile (/profile); a "Take it further" row carries Give it a voice (/voice), Embed it anywhere (/studio?model=<avatar_model_url>), Put it in a world (/play) and Launch its token (/launchpad). A line under the buttons tells the creator where the agent lives from now on: "Need it later? It is always waiting under My creations in the menu.", linking /mine.
  • Guest draft autosave: every input change debounce-saves (600 ms) to localStorage['threews:create-agent:draft'] once the form has real content, with a beforeunload flush; drafts expire after 7 days (src/create-agent-draft.js). A returning guest resumes on the exact saved step with "Resumed your saved draft. [Start fresh]". A picked upload File cannot survive navigation: the draft marks it lost, downgrades the model to "Add later", and asks the user to re-attach on the model step. Creation stops the autosave so a shipped agent never resurrects as a draft.
  • Decision points / branches: signed-in ship vs signed-out login round-trip (draft preserved); AI-generated spec vs manual form; model tab (starter/library/upload/skip); interviewed persona vs hand-typed prompt (a fresh AI-spec fill resets the interview so a new concept never inherits the previous voice); built-in voice vs cloned sample; publish on/off and whether publish prerequisites are met (publishes vs creates private with a soft warning); name conflict (409 → bounce to Step 0 to rename); resume draft vs "Start fresh"; per-step jump-back via stepper pips (real buttons, so a completed step is a tab stop and the current one carries aria-current) and review "Edit" buttons.
  • External calls / dependencies: getMe() (account.js); POST /api/agents/suggest-spec (AI spec generator); POST /api/persona/interview (interview extraction); GET /api/avatars (library tab); saveRemoteGlbToAccount (account.js → presign + R2 upload + commit); POST /api/agents; POST /api/agents/:id/voice/clone (via VoiceSetup.bindTo) + PATCH /api/user/provider-keys (BYOK key); POST /api/marketplace/agents/:id/publish; POST /api/agents/:id/persona/save.
  • Success state: A real agent with its own wallet/on-chain identity, a guaranteed 3D body, optionally listed on the marketplace; success card links to go-live/fund/view/edit/embed.
  • Empty / error states: Library tab has loading / error (with "Try again") / empty (no character models) states; per-step inline validation via #foot-msg; 409 name conflict bounces back; guest generate 429 → "That's the guest generation limit. Sign in to keep going, or fill the form in by hand."; publish, voice-bind, and persona-save failures are non-fatal (soft warning, agent still created); submit failure re-enables the form with an error message; lost upload on draft resume → re-attach prompt.
  • Step count: 7 required (Basics → Model → Skills → Personality → Voice → Review → Create) + ~4 optional (AI spec generate, onboarding interview, tags/optional skills, sign-in round-trip when starting signed out).

Prompt → Avatar — /create/prompt (create-prompt)

  • Source: pages/create-prompt.html + src/create-prompt.js (imports src/shared/log.js)
  • Entry point: The "Prompt" card on /create (/create redirects signed-out users to /login?next=/create/prompt). Also reachable directly.
  • Prerequisites / gates: Auth required: the submit endpoint returns 401 → page redirects to /login with next=/create/prompt?prompt=<text>, so the typed prompt survives the round trip through the ?prompt= deep link (also enforced upstream by /create). No wallet/$THREE gate.
  • Steps (N):
    1. Land on the compose step; type a text prompt (3 to 600 chars; live counter), or dictate it: a mic button (src/voice/prompt-dictation.js, browser SpeechRecognition with an NVIDIA Riva fallback) mounts next to the textarea only when the browser can dictate. (optional) Click an example chip to fill the prompt; around July 4 (July 1-5, viewer local time) seasonal preset chips are injected via src/shared/festive-presets.js. A ?prompt=<text> deep-link prefills the composer (no auto-submit).
    2. Click "Generate" (or Cmd/Ctrl+Enter). start() → switches to the building step, starts the elapsed clock, sets progress to 8%. Escape (or the cancel button) aborts the build back to compose; Cancel is gated on the building step rather than on an in-flight request, so it still works after a failure. Every build claims a run token, and a cancelled or superseded run can no longer write to the screen (starting a second build no longer lets the abandoned poll drop the old avatar onto the done screen).
    3. POST /api/avatars/reconstruct { name (derived from prompt), prompt, visibility: 'private' }. Server renders a reference image (Flux) then runs reconstruct→auto-rig. Returns { jobId }.
    4. pollUntilDone(jobId) polls GET /api/avatars/regenerate-status?jobId=... every 3s (8-min timeout), advancing the progress bar by phase (queued→running→rigging).
    5. On { status: 'done', resultAvatarId }: renderDone fetches GET /api/avatars/:id, sets the model-viewer src (using the owner's presigned URL for private avatars), and tags it (Animation-ready / static, Private). Shows the done step with "Open in editor" (/avatars/<id>/edit) and "Make another"; dispatches tws:feature-done for the cross-feature discovery layer.
  • Decision points / branches: compose vs building vs done; typed vs dictated prompt; success vs failure (submitError/jobError build an ApiError carrying human copy plus whether retrying can help: rate-limited quotes the server's retry_after, unconfigured and needs-BYOK suggest the selfie scanner without a retry, a full library (402 plan_limit, or a job that lost the race mid-build) links to /dashboard and /pricing without a retry, no-face, NSFW, timeout, OOM); cancel mid-build; 401 mid-flow → login redirect carrying the prompt; "Make another" resets to compose (bound once at module scope).
  • External calls / dependencies: POST /api/avatars/reconstruct; GET /api/avatars/regenerate-status; GET /api/avatars/:id. Backend uses a text-to-image (Flux) + reconstruct/rig pipeline.
  • Success state: A private, riggable 3D avatar previewed in-page with an "Open in editor" path.
  • Empty / error states: Compose: inline #compose-error if prompt < 3 chars. Building: the screen stops claiming work is in flight (orb frozen, bar muted, phase line and Cancel hidden) and #build-error offers "Edit prompt" always, "Try again" only for a retryable failure (held as a "Try again in Ns" countdown while a Retry-After runs), and the dashboard / pricing links for a full library; a fetch-level failure says the engine could not be reached rather than "something went wrong"; 8-min timeout message suggesting the dashboard. Generate button disabled until prompt ≥ 3 chars.
  • Step count: 3 required (compose → generate/build → done) + 1 optional (example chip).

Selfie → Avatar — /create/selfie (create-selfie)

  • Source: pages/create-selfie.html (inline <script type="module">) + src/selfie-capture.js + src/selfie-pipeline.js (pipeline imports src/avatar-face-capture.js, src/shared/log.js)
  • Entry point: The "Selfie" card on /create (auth-gated redirect there); /start Step 1 "Selfie" with ?wizard=1&next=; and /scan + /features/scan redirect/link here. Reachable directly.
  • Prerequisites / gates: Auth required for platform-mode reconstruction (counts against plan quota; /create enforces requireAuthForSelfie; pipeline maps 401 → /login?next=/create/selfie and resumes the pending job after login). BYOK mode (/api/config → features.avatarReconstructMode === 'byok'): an API-key entry step (Meshy/Tripo) precedes capture; key is stored in sessionStorage only. No wallet/$THREE gate.
  • Steps (N):
    1. Land; inline boot fetches /api/config to pick platform vs BYOK mode and dynamically imports the capture UI + pipeline.
    2. (optional, BYOK only) api-key step: pick provider (Meshy/Tripo), paste key (>8 chars), submit → storeByokKey → advance to capture.
    3. capture step: capture or upload a frontal photo (required) via camera overlay (selfie-capture.js, with face-oval guidance) or file upload; optionally add left/right angle photos (fidelity boost). The live shutter gate and the still-photo check now judge frames through one shared threshold module (src/selfie-gates.js), and a blocked shutter surfaces the grader's retake reason in the capture UI (poor lighting, off-angle) instead of silently refusing to fire. Lighting is graded before blur (a dark frame trips both, and light is the root cause), a blown-out face is caught by the share of clipped pixels as well as mean luma (the badge reads "Blown out" and the hint says to move out of direct light), and the live blur floor is a measured 12 (Laplacian stddev on the 64px crop; the old 3.5 never fired on a real photograph). Photos shared from the Android share sheet arrive with ?shared=1 and fill frontal, then left and right, in order. Each added frontal photo is also quality-assessed on-device (src/selfie-refine.js assessPhoto), surfacing #quality-notice warnings (blurry / drawing / no face) before the user waits out a full build. Those checks can no longer strand the capture: every wait on a MediaPipe model is capped at 15 s by withVisionDeadline (src/shared/mediapipe-assets.js), past which the unrefined photo is submitted and the build proceeds, and a face count of null now means "no detector loaded" rather than "no face", so an unreachable model never accuses a good selfie of having no face in it. The page also cross-links /image-to-3d for object (non-face) photos.
    4. Click "Build my avatar" (#submit-btn) → dispatches selfie:submit. Pipeline downscales photos (≤1024px JPEG), runs a local MediaPipe face check, then dispatches selfie:preview (shows the user's own photo on a placeholder).
    5. POST /api/avatars/reconstruct { name, photos[], visibility: 'private', params:{bodyType,style}, optional provider_key/provider_name } → { jobId }. Stashes selfie:pendingJobId in sessionStorage (for resume across login). Dispatches selfie:building → shows the building step (and requests Notification permission).
    6. pollUntilDone polls GET /api/avatars/regenerate-status?jobId=... (1.5s first, then 3s w/ backoff, 8 to 10 min timeout), dispatching selfie:progress labels (mesh → geometry → rigging → finishing). A done job with no resultAvatarId (the server's materialize stage lost a transient race) is polled up to three more times before it is treated as final, and a failure whose errorKind is input is relayed in the server's own words when no local mapping matches, so "your library is full" is never rewritten as "try a clearer photo".
    7. On done: selfie:done fires; the page fetches GET /api/avatars/:id, renders the model in the done viewer, prefills the name. If the tab is hidden, flashes the title + fires an OS notification.
    8. done step actions: "Open my avatar" (#done-save-btn, optional PATCH name → /avatars/<id>), "List on marketplace" (#done-list-btn, PATCH name + visibility public → /marketplace/avatars/<id>), "Customize in editor" (#done-editor-btn → /avatars/<id>/edit), or "Not quite right? Try again" (#done-regen-btn, reset to capture).
  • Abandoned jobs finish server-side (platform mode): the browser poll is no longer the only engine. api/cron/reconstruct-sweep.js (every 5 min) picks up open reconstruct jobs quiet for over 3 minutes and runs the same finalize stages, so closing the tab mid-build still lands the avatar in the user's library (30-day rescue window). BYOK jobs stay browser-driven (the server has no user key).
  • Decision points / branches: platform vs BYOK mode (key step or not); camera vs upload; frontal-only vs +side angles; photo quality warnings vs proceed; mid-flow 401 → login + job resume; done vs build-error (per-slot error highlighting, retry); resume-pending-job on reload.
  • External calls / dependencies: GET /api/config; POST /api/avatars/reconstruct; GET /api/avatars/regenerate-status; GET /api/avatars/:id; PATCH /api/avatars/:id (save/list). MediaPipe tasks-vision for the client face check (bundled from the npm dependency; src/shared/mediapipe-assets.js serves the WASM runtime and the face landmarker model from the vendored copy under public/vendor/mediapipe first and a CDN second, and fetches the segmenter and face-detector models from Google's bucket under a deadline, so capture survives a blocked CDN; the host probe is shared across callers and only a definitive "not there" answer demotes our own copy, since a probe that merely timed out used to hand the load to a CDN on every real page load); camera getUserMedia; optional Meshy/Tripo BYOK providers.
  • Success state: A private, rigged 3D avatar (reconstructed from the selfie), previewed in-page with save/list/edit paths.
  • Empty / error states: selfie:needs-byok → key-entry form ("No API key found"); local face-check failure highlights the offending slot with guidance; selfie:build-error recolors the building step, shows tips, and a "Try again" → capture; rate-limit cooldown with a live countdown; the error banner scrolls into view on first appearance so a tap on the sticky submit bar from higher up the page never fails silently; viewer load failure marks the preview .failed; 8-min timeout message.
  • Step count: 4 required (capture frontal → build → poll → done) + ~4 optional (BYOK key step, side angles, upload-vs-camera, save/list/edit/make-another).

Talking Avatar Video: /create/video

  • Source: pages/create/video.html + src/create-video.js (imports src/account.js for apiFetch; the page also loads src/wallet-auth.js inline for the sign-in button)
  • Entry point: The "Talking avatar video" card on /create (card-video-avatar), which is both feature-flagged and auth-gated there. Also reachable from the Video capability tile on /create-review and directly by URL.
  • Prerequisites / gates: Auth required. boot() fetches /api/auth/me first and location.replace('/login?next=/create/video') on a non-OK response or a missing user, before anything renders. Feature-flagged upstream: /create greys the card out when /api/config reports videoAvatar off. Quota: the generate endpoint returns 402 free_trial_used after the one free video. Renderer probe: GET /api/avatar/video-generate answers { available, reason, free_generations }; when the GPU worker is unconfigured the page shows a "Video rendering is offline" banner (pointing at /avatar-studio and /create/prompt) and keeps Generate disabled with the hint "Generation is paused while the renderer is offline.", and a 503 from the real POST flips the same state. No wallet/$THREE gate.
  • Steps (N):
    1. Land; loadAvatars() fetches GET /api/avatars and fills the avatar strip, auto-selecting the first one. With no owned avatars the strip shows "No avatars yet. Make one and it shows up here, ready to speak." with a "Create an avatar" link, and a failed list shows "We could not load your avatars" with Retry (a failure is never rendered as an empty library); in both cases the stage shows /avatars/default.glb as decoration only, never as a generation source. The viewer starts with no src, so the login redirect cannot abort a model download mid-flight.
    2. Pick an avatar from the strip (click, or Enter/Space; each thumb is a real role="button" with an aria-label). Private avatars come back from the list endpoint with no CDN URL, so selectAvatar lazily resolves a short-lived signed URL from GET /api/avatars/:id and guards against the user switching avatars mid-await. The pick renders in the model-viewer stage.
    3. Add audio: drag-drop onto #audio-drop or pick a file. A non-audio drop is rejected with a toast. The chosen filename shows with its duration and size, an inline <audio> preview and a clear button; drops are accepted by MIME type or by extension. "Generate" stays disabled until both an avatar and an audio file are present, and the #generate-hint line under it always says what is still missing ("Pick an avatar to generate.", "Add an audio clip to generate.") or, once ready, roughly how many 3.72 s clips the audio will render into.
    4. (optional) Type a direction prompt in #prompt-input to steer the render.
    5. Click "Generate". uploadAudio requests POST /api/avatar/presign-audio (declaring bytes, capped at 64 MB) and PUTs the file to R2. A failed presign is reported as an error: there is no data-URI fallback, since video-generate only accepts an https three.ws-hosted audio_url.
    6. POST /api/avatar/video-generate { audio_url, avatar_id, prompt } returns { job_id }. The server resolves avatar_id to a real reference image (the stored thumbnail, else a cached portrait render through the /api/avatar/render pipeline), so the browser never sends an image_url; it used to send the GLB, which the worker wrote into its reference image and failed on minutes later.
    7. pollJob polls GET /api/avatar/video-status?job_id=… every 5 s with a 20-minute deadline. The status endpoint reports progress plus the worker's planned segments count and measured audio_seconds, so the label names the work ("Rendering N clips… X%", one 3.72 s clip per segment) instead of a bare percent. Transient non-2xx and network errors are retried, but six in a row (30 s) stop the poll with "Lost contact with the render job", and a failed job relays the worker's own error text.
    8. On status: 'done': the returned video_url loads into the result <video> with a Download link and a "Make another" button that resets to idle.
  • Decision points / branches: signed-in vs redirect to login; renderer available vs offline (banner, Generate disabled); owned avatars vs the empty-strip note vs a failed list with Retry; public (CDN URL) vs private (signed-URL resolve) avatar; presign success vs presign failure (413 too-large / 429 rate-limit / generic, each with its own message; no data-URI fallback exists); prompt vs no prompt; done vs failed vs 20-minute timeout; 402 free_trial_used retargets the retry button to "Upgrade plan" pointing at /dashboard.
  • External calls / dependencies: GET /api/auth/me; GET /api/avatar/video-generate (availability probe); GET /api/avatars; GET /api/avatars/:id (signed GLB URL); POST /api/avatar/presign-audio + R2 PUT; POST /api/avatar/video-generate; GET /api/avatar/video-status. Rendering runs on the talking-head worker, not in the browser; both worker calls go through the shared upstream breaker (a submit is never retried, a status read is).
  • Success state: A downloadable lip-synced talking-head clip of the user's own avatar, playable in-page, with a one-click path to generate another.
  • Empty / error states: No avatars shows the create-one note; a failed avatar list shows a retryable error; the offline banner covers an unconfigured renderer. An avatar whose model cannot be resolved toasts "Could not load this avatar's 3D model. Pick another one." and leaves Generate disabled. Audio upload failure, job-start failure, worker failure, and the 20-minute timeout each render in #error-area with a retry that returns to idle. Free-trial exhaustion swaps retry for an upgrade link.
  • Step count: 4 required (pick avatar → add audio → generate → poll to done) + ~2 optional (direction prompt, download / make another).

Agent Editor: /agents/<id>/edit (and the retired /agent/new)

  • Source: pages/agent-edit.html + src/agent-edit.js (vercel routes the canonical /agents/<id>/edit and the legacy /agent/<id>/edit both → /agent-edit.html, and the module accepts either path segment; imports src/avatar-creator.js, src/account.js, src/api.js, src/avatar-gallery-picker.js, src/shared/agent-wallet-chip.js, src/shared/glb-magic.js)
  • Entry point: "Edit" buttons on agent profiles and the create-agent success panel. /agent/new no longer serves this editor: the bare route 301s to /create-agent, and /agent/new?avatar_id= / ?avatar_glb= rewrites to create-agent.html, where applyAvatarHandoff() pre-seeds the wizard's model step (marketplace "Start an agent with this avatar" now lands in the wizard). Autopilot receipts link here as /agents/<id>/edit?tab=knowledge#mem-<memoryId>: the cited memory is highlighted and scrolled into view once the list renders, and the ?tab= section scroll stands down for it.
  • Prerequisites / gates: Auth required. Loading an agent you don't own (or with no session) hits a 401, which stashes login_redirect and redirects to /login. No $THREE gate.
  • Steps (N):
    1. Navigate to /agents/<id>/edit; loadAgent() fetches GET /api/agents/:id and the full editor renders (render()): identity (name/description), 3D body (starter/library picker/upload via avatar-gallery-picker.js + AvatarCreator), skills, animations, gesture slots (per-agent bindings for the fixed gesture vocabulary, saved via #anim-slots-save, previewable on /gestures), voice, wallet chip, and the embed/manifest panels. The wallet panel reads balances from GET /api/portfolio/summary ({ usd, native, tokens } per wallet), sends through POST /api/portfolio/send with asset: 'native' or the USDC mint and the typed decimal amount (echoing the returned tx_hash), and the Fund modal's deposit QR tries qrserver then quickchart before hiding the image behind the copyable address. The Social tab hides Connect X with a stated reason when X OAuth is not configured on the deployment (?x=unconfigured after a bounced connect). Embed and manifest panels emit the canonical /agents/<id> URLs.
    2. Edit any field → changes persist through the same verified endpoints (PUT /api/agents/:id, animations endpoint, etc.). PUT /api/agents/:id only links an avatar_id the signed-in owner owns: a non-UUID id returns 400 and an avatar that is missing, deleted or someone else's returns 404 avatar not found.
  • Decision points / branches: existing agent (URL id) vs the retired new-draft path (bare /agent/new now redirects to the /create-agent wizard before this page ever loads); signed-out → login; gesture overrides set vs cleared.
  • External calls / dependencies: GET /api/agents/:id; PUT /api/agents/:id; PUT /api/agents/:id/animations; GET /api/agents/:id/manifest; GET /api/portfolio/summary; POST /api/portfolio/send; GET /api/auth/x/connect?agent_id= (redirect); avatar APIs via saveRemoteGlbToAccount / gallery picker.
  • Success state: The agent loaded into the full editor for fine-grained configuration, with saves confirmed inline (e.g. "Saved N gesture overrides.").
  • Empty / error states: showError(...) for load failures; 401 → login redirect with return. The library picker no longer dead-ends on a failed grid: avatar-gallery-picker.js renders a role="alert" card ("Could not load avatars") that distinguishes a request that never reached three.ws from a service error and offers "Try again", which re-renders skeletons and reloads the page of avatars. A card whose thumbnail URL is dead swaps to the designed placeholder tile (data-thumb-fallback, wired by src/shared/thumb-fallback.js) instead of the browser's broken-image glyph.
  • Step count: 1 required (navigate → editor); the editor itself is open-ended.

Import Avatar (URL / Upload) — /import/rpm (import-rpm)

  • Source: pages/import-rpm.html (inline <script type="module">) + src/account.js (saveRemoteGlbToAccount)
  • Entry point: Direct link / docs / nav. "Import any GLB or VRM avatar and give it an agent brain."
  • Prerequisites / gates: Auth required at import time — saveRemoteGlbToAccount presigns/commits against the user's account; a not_signed_in/401 redirects to /login?return=<here>. No wallet/$THREE gate. (The page itself loads anonymously.)
  • Steps (N):
    1. Land; two tabs — Import from URL and Upload file.
    2. URL tab: paste an http(s) GLB or VRM URL (validated), optionally a name → click "Import".
    3. (alt) File tab: drag-drop or pick a .glb or .vrm ≤100 MB (validated by extension + size), optionally a name → click "Upload".
    4. runImport(...) → saveRemoteGlbToAccount(source, { name, visibility:'public', tags:['rpm','imported'], source:'readyplayer', source_meta }) where source_meta carries import_method (url or file) and the original source_url, with progress callbacks (Fetching → Normalizing bones → Uploading → Saving), showing a live progress bar.
    5. On success: showSuccess(avatar) swaps in the success card with " is ready" and a link to /avatars/<id>.
  • Decision points / branches: URL vs file upload; signed-out (401) → login round-trip; success vs error (friendly mapping by err.code/err.stage: fetch / presign / commit / upload_blocked / size_mismatch).
  • External calls / dependencies: saveRemoteGlbToAccount (account.js — presign + remote GLB fetch/normalize + R2 upload + commit). Source URL is fetched server-side.
  • Success state: An owned, public avatar in the user's library, linked at /avatars/<id> (ready to attach an agent brain).
  • Empty / error states: Per-tab status-msg (invalid file type, too large, invalid URL, fetch/upload failures); progress wrap during import; auth redirect on 401.
  • Step count: 2 required (choose source → import) + 1 optional (custom name).

3D Scanner (redirect) — /scan

  • Source: None. pages/scan.html has been deleted; /scan is now a pure routing rule in vercel.json (server-side 301 with Location: /create/selfie).
  • Entry point: Legacy /scan links, direct links, marketing.
  • Prerequisites / gates: N/A. The redirect fires before any page loads.
  • Steps (N):
    1. Hit /scan → 301 to /create/selfie. User experiences the /create/selfie flow (see that entry); there is no /scan UX at all anymore. Note: the 301 sends a bare Location: /create/selfie, so query params (?wizard=1&next=…) are dropped, unlike the old in-page redirect which preserved them.
  • Decision points / branches: None — unconditional redirect.
  • External calls / dependencies: None.
  • Success state: User arrives at /create/selfie (selfie pipeline success state applies there).
  • Empty / error states: None (route-level redirect).
  • Step count: 0 required on /scan itself (1 implicit redirect) — the real flow is /create/selfie.

Scan Landing Page — /features/scan

  • Source: pages/features/scan.html (static marketing page; loads /nav.js, /footer.js — no inline flow logic)
  • Entry point: /features index, marketing nav.
  • Prerequisites / gates: None — public landing page.
  • Steps (N):
    1. Land on the feature landing page ("Your face in 3D. In 60 seconds.") — hero, explainer sections, a model-viewer demo.
    2. Click a primary CTA "Start scanning →" → navigates directly to /create/selfie (the CTAs no longer route through /scan). Secondary CTAs link to /features, /features/forge.
  • Decision points / branches: CTA choice: start scanning (/create/selfie) vs "Try Forge instead" (/features/forge) vs "All features" (/features).
  • External calls / dependencies: None (static page; model-viewer loaded from CDN for the demo GLB /animations/soldier.glb).
  • Success state: User is routed into the selfie/scan creation flow.
  • Empty / error states: N/A — static content, no data fetching.
  • Step count: 1 required (land → click CTA). No optional steps.

Voice Lab — /voice

  • Source: pages/voice.html + src/voice-lab.js
  • Entry point: Nav/feature links; used to mint a cloned voice that agents/avatars can speak with.
  • Prerequisites / gates: Microphone permission (getUserMedia). The clone endpoint is called with credentials: 'include'; auth/credit limits are enforced server-side (a failure surfaces as a "Clone failed" status), and the route checks identity before configuration, so a signed-out caller gets a 401 rather than a reading of the server's ElevenLabs setup. No wallet/$THREE gate. Cloned-voice library is stored in localStorage (voicelab_voices_v1).
  • Steps (N):
    1. Land; a reading script is shown (cycle with "Next script"). Voice library + playground voice dropdown render from localStorage.
    2. Click "Record" (#btnRecord) → getUserMedia (mono, 48kHz, with AGC/NS/EC), live waveform + level meter, max 60s (recommended 20–30s).
    3. Click "Stop" (#btnStop) → builds a recorded Blob; rejects clips < 3s; on success shows the review state with an audio preview.
    4. (optional) "Re-record" (#btnRerecord) to discard and try again.
    5. Enter a voice name (required) and click "Clone" (#btnClone) → POST /api/tts/eleven-clone (multipart audio + name).
    6. On success: stores { voiceId, name, status } in localStorage, shows the done state (" cloned successfully"), re-renders the library + playground voice list.
    7. (optional) "Try in playground" (#btnTryPlayground): pick a voice, type text, click "Speak" → POST /api/tts/eleven { voiceId, text } to synthesize and play. "Play sample" on a library card does the same with a canned line. "Record another" loops back. A lane that goes down mid-session drops its voices from the picker (a lane-down error re-reads the catalog), an unavailable lane's pill stays legible with a greyed billing badge so it never reads as live, and Space toggles record/stop only when focus is not on a control.
  • Decision points / branches: record vs re-record; clone success vs failure (mic denied, recording too short, network error, server HTTP error); playground speak vs library sample playback; delete voice from library.
  • External calls / dependencies: POST /api/tts/eleven-clone (clone); POST /api/tts/eleven (TTS playback/sample). ElevenLabs via the server proxy. There is no free platform TTS lane: each clip is billed to the caller's own ElevenLabs key (BYOK, sent as x-eleven-key or saved via provider keys) or metered against the prepaid credit wallet, with an R2 cache absorbing repeats; the x-tts-billing response header reports which lane served the call, and the playground surfaces the per-clip cost. Browser getUserMedia / MediaRecorder / Web Audio.
  • Success state: A cloned voice ID saved to the local library, immediately usable in the in-page TTS playground (and selectable elsewhere for agent speech).
  • Empty / error states: Library empty state ("No cloned voices yet"); status banner (setStatus) for mic-denied, recorder-init failure, too-short clip, network/HTTP clone errors, name-required; playground/sample buttons surface synth errors inline, and an unknown voiceId comes back as a 400 validation_error naming the voice (ElevenLabs' 400/404 is the caller's fault, not a 502).
  • Step count: 4 required (record → stop → name → clone) + ~3 optional (cycle script, re-record, playground speak/sample).

Notes on routing resolution

  • /start, /create, /create-agent, /import/rpm, /features/scan, /voice all resolve via explicit vercel.json routes[] rewrites to their *.html files.
  • /create/prompt → create-prompt.html, /create/selfie → create-selfie.html.
  • /create-review → create-review.html, /create/next → create-next.html, /create/video → create/video.html, /create/studio → avatar-studio.html (the studio surface itself is documented in cluster 04).
  • /agent/new → 301 to /create-agent (or a rewrite to create-agent.html when the URL carries ?avatar_id=/?avatar_glb=); the existing-agent editor lives at /agents/<uuid>/edit → agent-edit.html (canonical; the legacy /agent/<uuid>/edit still rewrites there, while the bare /agent/<uuid> 301s to /agents/<uuid>).
  • /scan is a route-level 301 to /create/selfie (pages/scan.html no longer exists; the 301 drops query params).
  • /features/scan is a static landing page with no flow logic; its CTAs link straight to /create/selfie.