Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat(play): every walker in the world is a real citizen you can open and talk to
nirholas7a77c7652ff7
diff --git a/src/game/ambient-crowd.js b/src/game/ambient-crowd.jsindex 4b8fb70f8..d8940e238 100644--- a/src/game/ambient-crowd.js+++ b/src/game/ambient-crowd.js@@ -18,10 +18,10 @@ import { getMeshoptDecoder } from '../viewer/internal.js';import { Box3, Mesh, CapsuleGeometry, SphereGeometry, MeshStandardMaterial } from 'three';import { AnimationManager } from '../animation-manager.js';import { detectProfile } from '../club-perf.js';+import { loadCitizenPool, isCitizen, openCitizenProfile } from './npc/citizens.js';const AVATAR_DEFAULT = '/avatars/default.glb';const MANIFEST_URL = '/animations/manifest.json';-const GALLERY_URL = '/api/avatars/public?limit=96'; // public avatar gallery — a broad pool so each wanderer is a distinct community modelconst CLIP_IDLE = 'idle';const CLIP_WALK = 'av-walk-feminine';const WORLD_RADIUS = 54; // a touch inside the plaza edge@@ -98,24 +98,17 @@ async function loadManifest() {}// Pull a varied set of real avatars from the public gallery so the crowd reads as-// a living mix of community models rather than one repeated default. Only models-// whose published size fits this device's per-model budget make the pool; an-// entry with no size is skipped rather than gambled on, since one 24 MB draw is-// enough to end a mobile session. Settles to an empty array on failure; each-// wanderer then falls back to AVATAR_DEFAULT.+// a living mix of community models rather than one repeated default. The shared+// citizen pool (citizens.js) supplies full records, so each wanderer keeps the+// identity of the avatar it wears: its gallery name, bio, and the registered+// agent behind it. Only models whose published size fits this device's+// per-model budget make the pool; an entry with no size is skipped rather than+// gambled on, since one 24 MB draw is enough to end a mobile session. Settles+// to an empty array on failure; each wanderer then falls back to AVATAR_DEFAULT.async function loadAvatarPool() {if (_avatars) return;- let picks = [];- try {- const r = await fetch(GALLERY_URL, { headers: { accept: 'application/json' } });- if (r.ok) {- const { avatars } = await r.json();- picks = (avatars || [])- .map((a) => ({ url: a.model_url || a.base_model_url, bytes: Number(a.size_bytes) || 0 }))- .filter((p) => p.url && p.bytes > 0 && p.bytes <= BUDGET.maxModelBytes);- }- } catch { /* default-avatar fallback below */ }- _avatars = picks;+ const records = await loadCitizenPool();+ _avatars = records.filter((p) => p.url && p.bytes > 0 && p.bytes <= BUDGET.maxModelBytes);}// Fetch a model once and hand every later wanderer a clone of it. `bytes` is the@@ -196,8 +189,14 @@ async function playEmote(anim, motion) {}class Wanderer {- constructor(scene, name, avatarPick) {- this.name = name;+ constructor(scene, name, avatarPick, onInspect) {+ // A wanderer wearing a named gallery avatar IS that citizen: it carries the+ // avatar's real name and identity, and its nameplate opens the profile.+ // Only the nameless (default-avatar or anonymous-model) wanderers keep the+ // decorative crowd names.+ this.record = isCitizen(avatarPick) ? avatarPick : null;+ this.name = this.record ? this.record.name : name;+ this.held = false;this.rig = new Group();this.anim = new AnimationManager();this.height = 1.7;@@ -210,7 +209,22 @@ class Wanderer {this.label = document.createElement('div');this.label.className = 'cc-label';- this.label.textContent = name;+ this.label.textContent = this.name;+ if (this.record) {+ this.citizen = {+ record: this.record,+ name: this.name,+ say: (t) => this.say(t),+ hold: () => { this.held = true; this._setMotion('idle'); },+ release: () => { this.held = false; },+ };+ // .cc-label is pointer-events:none globally; re-enable for this one, the+ // same way peer nameplates do, so the name itself is the tap target.+ this.label.style.pointerEvents = 'auto';+ this.label.style.cursor = 'pointer';+ this.label.title = `Meet ${this.name}`;+ this.label.addEventListener('click', (e) => { e.stopPropagation(); onInspect?.(this); });+ }document.body.appendChild(this.label);this.bubble = null; this._bubbleTimer = null;@@ -227,6 +241,7 @@ class Wanderer {this.anim.crossfadeTo(m === 'walk' ? CLIP_WALK : CLIP_IDLE, 0.2);}say(text, onChat) {+ if (this._disposed) return; // churned away mid-conversation; the chat panel outlives the bodyif (this.bubble) this.bubble.remove();this.bubble = document.createElement('div');this.bubble.className = 'cc-bubble';@@ -236,7 +251,23 @@ class Wanderer {this._bubbleTimer = setTimeout(() => { this.bubble?.remove(); this.bubble = null; }, 4500);onChat?.(this.name, text);}- update(dt, onChat) {+ update(dt, onChat, player) {+ // Held for a conversation: stand still, face whoever stopped to talk, and+ // keep quiet (the chat panel drives the speech bubble now).+ if (this.held) {+ this._dest = null;+ this._wait = 1 + Math.random() * 2;+ if (player) {+ const want = Math.atan2(player.x - this.rig.position.x, player.z - this.rig.position.z);+ let d = want - this.yaw;+ while (d > Math.PI) d -= Math.PI * 2;+ while (d < -Math.PI) d += Math.PI * 2;+ this.yaw += d * Math.min(1, dt * 6);+ this.rig.rotation.y = this.yaw;+ }+ this.anim.update(dt);+ return;+ }this._sayIn -= dt;if (this._sayIn <= 0) { this._sayIn = 12 + Math.random() * 26; this.say(LINES[(Math.random() * LINES.length) | 0], onChat); }this._emoteIn -= dt;@@ -268,6 +299,7 @@ class Wanderer {this.anim.update(dt);}dispose() {+ this._disposed = true;this.scene.remove(this.rig);this.rig.clear();// Drop the mixer + its bound clip actions. The clips themselves are shared@@ -307,15 +339,31 @@ class AmbientCrowd {if (!_avatars?.length) return null;if (_spentBytes >= BUDGET.sessionBytes) {const resident = [..._templates.keys()];- return resident.length ? { url: resident[(Math.random() * resident.length) | 0], bytes: 0 } : null;+ if (!resident.length) return null;+ const url = resident[(Math.random() * resident.length) | 0];+ // Keep the identity riding the resident model: same record, zero new+ // bytes charged (the download already happened this visit).+ const rec = _avatars.find((p) => p.url === url);+ return rec ? { ...rec, bytes: 0 } : { url, bytes: 0 };}if (!this._avatarBag.length) this._avatarBag = [..._avatars];const i = (Math.random() * this._avatarBag.length) | 0;return this._avatarBag.splice(i, 1)[0];}+ // Open the citizen profile card for a wanderer: the real agent behind the+ // gallery avatar it wears, with a "Talk 1-on-1" into the live NPC chat.+ _inspect(w) {+ if (!w.citizen) return;+ const coin = this.cc.coin || {};+ openCitizenProfile(w.citizen, {+ world: { mint: coin.mint, name: coin.name, symbol: coin.symbol },+ ui: this.cc.ui,+ trigger: w.label,+ });+ }sync(realCount) {const want = Math.max(0, BUDGET.count - (realCount | 0));- while (this.list.length < want) this.list.push(new Wanderer(this.cc.scene, this._takeName(), this._takeAvatar()));+ while (this.list.length < want) this.list.push(new Wanderer(this.cc.scene, this._takeName(), this._takeAvatar(), (w) => this._inspect(w)));while (this.list.length > want) this.list.pop().dispose();// The HUD's online count reports REAL players only (self + live peers).// Padding it with the decorative crowd was a lie a livestream can catch in@@ -332,7 +380,7 @@ class AmbientCrowd {node.style.transform = `translate(-50%, -100%) translate(${(v.x * 0.5 + 0.5) * W}px, ${(-v.y * 0.5 + 0.5) * H}px)`;};for (const w of this.list) {- w.update(dt, this._onChat);+ w.update(dt, this._onChat, this.cc.localPos);place(w.label, w.rig.position, w.height + 0.2);if (w.bubble) place(w.bubble, w.rig.position, w.height + 0.7);}diff --git a/src/game/avatar-rig.js b/src/game/avatar-rig.jsindex 03d1b5e92..f2b47be7c 100644--- a/src/game/avatar-rig.js+++ b/src/game/avatar-rig.js@@ -13,6 +13,7 @@ import {} from 'three';import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';import { DRACOLoader } from 'three/addons/loaders/DRACOLoader.js';+import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js';import { AnimationManager } from '../animation-manager.js';import { getMeshoptDecoder } from '../viewer/internal.js';import { GUEST_SENTINEL, resolveGuestAvatar } from './play-handoff.js';@@ -101,6 +102,145 @@ export async function resolveAvatarUrl(input) {return AVATAR_DEFAULT;}+// ── shared model templates ────────────────────────────────────────────────────+// One download + parse per distinct avatar URL, shared by every rig that wears+// it. Before this cache, N peers in the same model cost N downloads, N parses+// and N full GPU uploads: with community avatars running to 24 MB, a crowded+// world OOM-killed phones. A clone (SkeletonUtils) deep-copies the bone+// hierarchy while sharing geometry and textures with its template; materials+// are cloned per rig (they are tiny) so per-peer effects like the downed-peer+// fade never bleed across players wearing the same model.++const MB = 1024 * 1024;+// A coarse primary pointer is the one signal phones and tablets reliably share.+const _touchPrimary = typeof matchMedia === 'function' && matchMedia('(pointer: coarse)').matches;+// Per-model download ceiling on touch devices. Uploads are capped at 16 MB, but+// a 10 MB+ meshopt GLB decompresses to far more than a phone can spare per+// peer; an oversized model renders as the default avatar there instead.+const PHONE_MODEL_DOWNLOAD_CAP = 10 * MB;+// Estimated resident bytes (geometry + decoded textures) the template cache may+// hold. Templates a rig still wears are never evicted; idle ones go LRU-first+// once the budget is crossed.+const RESIDENT_BUDGET_BYTES = _touchPrimary ? 160 * MB : 512 * MB;++const _templates = new Map(); // url → { url, promise, refs, bytes, lastUse }+const _cloneInfo = new WeakMap(); // cloned model root → { entry, materials }+const _sizeChecks = new Map(); // url → Promise<number|null> published byte size++// Published size of a remote model, from a HEAD request. Resolves null when the+// host hides content-length or blocks HEAD; unknown sizes are allowed through+// (the resident budget still bounds the session).+function publishedModelBytes(url) {+ if (!/^https?:\/\//i.test(url) && !url.startsWith('/')) return Promise.resolve(null);+ let pending = _sizeChecks.get(url);+ if (!pending) {+ pending = fetch(url, { method: 'HEAD' })+ .then((r) => (r.ok ? Number(r.headers.get('content-length')) || null : null))+ .catch(() => null);+ _sizeChecks.set(url, pending);+ }+ return pending;+}++// Rough resident cost of a parsed scene: geometry buffers plus decoded RGBA+// texture bytes, each counted once however many meshes share them.+function estimateSceneBytes(scene) {+ let bytes = 0;+ const seen = new Set();+ scene.traverse((n) => {+ if (n.geometry && !seen.has(n.geometry.uuid)) {+ seen.add(n.geometry.uuid);+ for (const attr of Object.values(n.geometry.attributes || {})) bytes += attr?.array?.byteLength || 0;+ bytes += n.geometry.index?.array?.byteLength || 0;+ }+ const mats = Array.isArray(n.material) ? n.material : n.material ? [n.material] : [];+ for (const mat of mats) {+ for (const value of Object.values(mat)) {+ if (value?.isTexture && !seen.has(value.uuid)) {+ seen.add(value.uuid);+ const img = value.image;+ if (img?.width && img?.height) bytes += img.width * img.height * 4;+ }+ }+ }+ });+ return bytes;+}++function loadTemplate(url) {+ let entry = _templates.get(url);+ if (entry) return entry;+ entry = { url, refs: 0, bytes: 0, lastUse: Date.now(), promise: null };+ entry.promise = (async () => {+ await meshoptReady;+ installVrmPlugin(_gltf);+ const gltf = await _gltf.loadAsync(url);+ // VRM facing/skeleton fixes run once here; every clone inherits them.+ prepareVrmModel(gltf);+ const scene = gltf.scene;+ const box = new Box3().setFromObject(scene);+ entry.bytes = estimateSceneBytes(scene);+ return { scene, box };+ })();+ // A failed load must not poison the URL for the rest of the session.+ entry.promise.catch(() => { if (_templates.get(url) === entry) _templates.delete(url); });+ _templates.set(url, entry);+ return entry;+}++function disposeTemplateScene(scene) {+ scene.traverse((n) => {+ if (!n.isMesh) return;+ n.geometry?.dispose?.();+ for (const mat of Array.isArray(n.material) ? n.material : [n.material]) {+ if (!mat) continue;+ for (const value of Object.values(mat)) value?.isTexture && value.dispose();+ mat.dispose?.();+ }+ });+}++// Drop idle templates (LRU first) until the cache fits the budget. Templates+// with live clones are always kept: their buffers are shared and in use.+function evictIdleTemplates() {+ let resident = 0;+ for (const e of _templates.values()) resident += e.bytes;+ if (resident <= RESIDENT_BUDGET_BYTES) return;+ const idle = [..._templates.values()].filter((e) => e.refs === 0).sort((a, b) => a.lastUse - b.lastUse);+ for (const e of idle) {+ if (resident <= RESIDENT_BUDGET_BYTES) break;+ _templates.delete(e.url);+ resident -= e.bytes;+ e.promise.then(({ scene }) => disposeTemplateScene(scene)).catch(() => { /* never parsed */ });+ }+}++// Release the avatar model (and any capsule stand-in) buildAvatar put on this+// rig: per-rig materials are disposed, the shared template is derefed, and idle+// templates past the memory budget are freed. Every scene that churns rigs+// (peers leaving, avatar swaps, world exits) must call this instead of relying+// on scene.remove()/rig.clear(), which drop the JS reference but leak the GPU+// buffers. Children this module didn't create (cosmetics, glow rings) are left+// for their owners to dispose.+export function releaseAvatar(rig) {+ if (!rig) return;+ for (const child of [...rig.children]) {+ const info = _cloneInfo.get(child);+ if (info) {+ rig.remove(child);+ _cloneInfo.delete(child);+ for (const mat of info.materials) mat.dispose();+ info.entry.refs = Math.max(0, info.entry.refs - 1);+ info.entry.lastUse = Date.now();+ } else if (child.userData?.avatarStandIn) {+ rig.remove(child);+ child.geometry?.dispose?.();+ child.material?.dispose?.();+ }+ }+ evictIdleTemplates();+}+// Plausible human heights in metres. Name labels and chat bubbles anchor to// this value, so it must stay near the *visible* top of the avatar.const MIN_AVATAR_HEIGHT_M = 0.5;@@ -132,20 +272,40 @@ function headAnchorHeight(box) {// entry behind dozens of emote-clip downloads; emotes still lazy-load on first// use via playEmoteClip, which fetches a missing clip on demand.export async function buildAvatar(rig, url, anim, opts = {}) {+ let loadUrl = url || AVATAR_DEFAULT;+ let downgraded = false;+ // On phones, refuse to download a model over the per-model ceiling: one 16 MB+ // GLB can end the whole session there. The peer still reads as a person (the+ // default avatar), and a template already resident costs nothing to reuse.+ if (_touchPrimary && loadUrl !== AVATAR_DEFAULT && !_templates.has(loadUrl)) {+ const bytes = await publishedModelBytes(loadUrl);+ if (bytes && bytes > PHONE_MODEL_DOWNLOAD_CAP) {+ log.warn('[avatar-rig] model over the mobile size cap, wearing the default:', loadUrl, `${(bytes / MB).toFixed(1)}MB`);+ loadUrl = AVATAR_DEFAULT;+ downgraded = true;+ }+ }try {- await meshoptReady; // ensure meshopt-compressed GLBs (incl. the default) parse- // P3.4: pick up the reference VRM parser if boot installed one. Free no-op- // otherwise, and idempotent, so it can sit on the hot path.- installVrmPlugin(_gltf);- const gltf = await _gltf.loadAsync(url);- const model = gltf.scene;- // A .vrm is a glTF binary, so it has already parsed by here; this fixes the- // VRM-specific facing/culling/material issues a plain glTF load leaves- // behind. No-op for every non-VRM avatar. See src/game/vrm-loader.js.- prepareVrmModel(gltf);- model.traverse((n) => { if (n.isMesh) { n.castShadow = true; n.receiveShadow = false; } });- const box = new Box3().setFromObject(model);+ const entry = loadTemplate(loadUrl);+ const { scene, box } = await entry.promise;+ const model = cloneSkinnedScene(scene);+ // Per-rig materials over shared geometry/textures: effects that write to a+ // material (downed-peer fade, highlights) must never leak onto another+ // player wearing the same model.+ const materials = [];+ model.traverse((n) => {+ if (!n.isMesh) return;+ n.castShadow = true; n.receiveShadow = false;+ if (n.material) {+ const mats = (Array.isArray(n.material) ? n.material : [n.material]).map((m) => m.clone());+ n.material = Array.isArray(n.material) ? mats : mats[0];+ materials.push(...mats);+ }+ });model.position.y -= box.min.y;+ entry.refs += 1;+ entry.lastUse = Date.now();+ _cloneInfo.set(model, { entry, materials });rig.add(model);anim.attach(model);// Ensure the clip manifest is loaded before posing — callers often kick off@@ -155,13 +315,19 @@ export async function buildAvatar(rig, url, anim, opts = {}) {if (!_animDefs) await loadManifest();const defs = opts.clips === 'locomotion' ? getLocomotionDefs() : _animDefs;if (defs?.length) { anim.setAnimationDefs(defs); await anim.loadAll(); await anim.crossfadeTo(CLIP_IDLE, 0); }- return { height: headAnchorHeight(box), fallback: false };+ return { height: headAnchorHeight(box), fallback: downgraded, downgraded };} catch (err) {- log.warn('[avatar-rig] avatar load failed, using stand-in:', url, err?.message);+ log.warn('[avatar-rig] avatar load failed, using stand-in:', loadUrl, err?.message);+ // The requested model failed; the bundled default keeps the player human-+ // shaped before the capsule of last resort.+ if (loadUrl !== AVATAR_DEFAULT) {+ const res = await buildAvatar(rig, AVATAR_DEFAULT, anim, opts);+ return { ...res, fallback: true, downgraded: true };+ }const body = new Mesh(new CapsuleGeometry(0.32, 0.7, 4, 10), new MeshStandardMaterial({ color: 0x8aa6d8 }));- body.position.y = 0.85; body.castShadow = true;+ body.position.y = 0.85; body.castShadow = true; body.userData.avatarStandIn = true;const head = new Mesh(new SphereGeometry(0.28, 14, 10), new MeshStandardMaterial({ color: 0xf1c9a5 }));- head.position.y = 1.55; head.castShadow = true;+ head.position.y = 1.55; head.castShadow = true; head.userData.avatarStandIn = true;rig.add(body, head);return { height: 1.7, fallback: true };}diff --git a/src/game/npc/ambient-life.js b/src/game/npc/ambient-life.jsindex 3b8267ee7..17bf03bc3 100644--- a/src/game/npc/ambient-life.js+++ b/src/game/npc/ambient-life.js@@ -20,10 +20,10 @@ import {BoxGeometry, CylinderGeometry, MeshBasicMaterial,} from 'three';import { AnimationManager } from '../../animation-manager.js';-import { buildAvatar, CLIP_WALK } from '../avatar-rig.js';+import { buildAvatar, CLIP_IDLE, CLIP_WALK } from '../avatar-rig.js';import { mulberry32 } from './nav-graph.js';+import { loadCitizenPool, isCitizen } from './citizens.js';-const GALLERY_URL = '/api/avatars/public?limit=96';const DEFAULT_AVATAR = '/avatars/default.glb';const PED_WALK_SPEED = 1.35; // m/s along the loop — an unhurried stroll@@ -43,7 +43,7 @@ const worldClock = () => Date.now() / 1000;// ---- detailed GLB pedestrian -------------------------------------------------class Pedestrian {- constructor(scene, nav, { loopIdx, phase, speedScale, avatarUrl, seed }) {+ constructor(scene, nav, { loopIdx, phase, speedScale, record, seed, onInspect }) {this.scene = scene;this.nav = nav;this.loopIdx = loopIdx;@@ -54,6 +54,12 @@ class Pedestrian {this._avoid = new Vector3();this._rng = mulberry32(seed);this._sayIn = 8 + this._rng() * 22;+ // Hold-to-talk: while a player has this pedestrian's profile or chat open,+ // they stop and face the player. `_lag` is how many seconds of stroll they+ // owe the shared schedule; it grows while held and decays after release, so+ // they briskly catch back up to where every other client says they are.+ this._held = false;+ this._lag = 0;this.rig = new Group();scene.add(this.rig);@@ -61,19 +67,52 @@ class Pedestrian {this.bubble = null;this._bubbleTimer = null;+ // Real identity from the public avatar gallery (name, bio, and usually the+ // registered agent this avatar represents). A nameless model stays honest+ // anonymous scenery: no nameplate, no profile, no chat.+ this.record = record || null;+ this.label = null;+ if (isCitizen(record)) {+ this.name = record.name;+ this.citizen = {+ record,+ name: record.name,+ say: (t) => this.say(t),+ hold: () => this._setHeld(true),+ release: () => this._setHeld(false),+ };+ this.label = document.createElement('div');+ this.label.className = 'cc-label npc-name';+ this.label.textContent = record.name;+ // .cc-label is pointer-events:none globally (bubbles must never block the+ // look-drag); re-enable it for this one, the same way peer nameplates do.+ this.label.style.pointerEvents = 'auto';+ this.label.style.cursor = 'pointer';+ this.label.title = `Meet ${record.name}`;+ this.label.addEventListener('click', (e) => { e.stopPropagation(); onInspect?.(this); });+ document.body.appendChild(this.label);+ }+// Locomotion clips only: pedestrians never emote, and each one with its own// AnimationManager would otherwise fetch the entire clip library.- buildAvatar(this.rig, avatarUrl || DEFAULT_AVATAR, this.anim, { clips: 'locomotion' })+ buildAvatar(this.rig, record?.url || DEFAULT_AVATAR, this.anim, { clips: 'locomotion' }).then(({ height }) => {if (this._disposed) return;this.height = height;// Loaded into idle by buildAvatar — set them strolling.- this.anim.crossfadeTo(CLIP_WALK, 0.2).catch(() => {});+ if (!this._held) this.anim.crossfadeTo(CLIP_WALK, 0.2).catch(() => {});}).catch(() => {});}+ _setHeld(held) {+ if (this._held === !!held) return;+ this._held = !!held;+ this.anim.crossfadeTo(this._held ? CLIP_IDLE : CLIP_WALK, 0.25).catch(() => {});+ }+say(text) {+ if (this._disposed) return; // churned away mid-conversation; the chat panel outlives the bodyif (this.bubble) this.bubble.remove();this.bubble = document.createElement('div');this.bubble.className = 'cc-bubble npc-bubble';@@ -85,13 +124,18 @@ class Pedestrian {update(dt, T, player) {// Base position is a pure function of the shared clock — identical on every- // client. Arc-length advances at a steady stroll.- const d = this.phase + this.speed * T;+ // client. Arc-length advances at a steady stroll. Hold-to-talk is a local,+ // cosmetic deviation like the sidestep below: while held the pedestrian+ // banks lag instead of moving, and afterwards walks it off at a brisk pace+ // until they re-converge with the shared baseline.+ if (this._held) this._lag += dt;+ else if (this._lag > 0) this._lag = Math.max(0, this._lag - dt * 0.6);+ const d = this.phase + this.speed * (T - this._lag);const p = this.nav.pedPoint(this.loopIdx, d);// Local, cosmetic sidestep around the player. Re-converges to zero, so it// never desyncs the shared baseline between clients.- if (player) {+ if (player && !this._held) {const dx = p.x - player.x, dz = p.z - player.z;const dist = Math.hypot(dx, dz);if (dist < PED_AVOID_RADIUS && dist > 1e-3) {@@ -103,11 +147,20 @@ class Pedestrian {this._avoid.multiplyScalar(1 - Math.min(1, dt * 2));this.rig.position.set(p.x + this._avoid.x, 0, p.z + this._avoid.z);- this.rig.rotation.y = Math.atan2(p.dirX, p.dirZ);+ // Held: turn to face whoever stopped to talk. Otherwise face travel.+ if (this._held && player) {+ const want = Math.atan2(player.x - this.rig.position.x, player.z - this.rig.position.z);+ let delta = want - this.rig.rotation.y;+ while (delta > Math.PI) delta -= Math.PI * 2;+ while (delta < -Math.PI) delta += Math.PI * 2;+ this.rig.rotation.y += delta * Math.min(1, dt * 6);+ } else {+ this.rig.rotation.y = Math.atan2(p.dirX, p.dirZ);+ }this.anim.update(dt);this._sayIn -= dt;- if (this._sayIn <= 0) { this._sayIn = 14 + this._rng() * 26; this.say(PED_LINES[(this._rng() * PED_LINES.length) | 0]); }+ if (this._sayIn <= 0 && !this._held) { this._sayIn = 14 + this._rng() * 26; this.say(PED_LINES[(this._rng() * PED_LINES.length) | 0]); }}dispose() {@@ -115,6 +168,7 @@ class Pedestrian {this.scene.remove(this.rig);this.bubble?.remove();clearTimeout(this._bubbleTimer);+ this.label?.remove();this.anim.dispose?.();}}@@ -208,10 +262,14 @@ class Vehicle {// ---- the ambient-life system -------------------------------------------------export class AmbientLife {- constructor({ scene, nav, biome }) {+ // `onInspectPed` (optional) makes the detailed pedestrians selectable: called+ // with the Pedestrian when a player clicks its nameplate or body. The world+ // manager wires it to the citizen profile card (see citizens.js).+ constructor({ scene, nav, biome, onInspectPed }) {this.scene = scene;this.nav = nav;this.biome = biome;+ this.onInspectPed = onInspectPed || null;this.peds = [];this.vehicles = [];this._avatarPool = null;@@ -268,20 +326,18 @@ export class AmbientLife {}async _loadAvatarPoolThenPeds() {- let urls = [];- try {- const r = await fetch(GALLERY_URL, { headers: { accept: 'application/json' } });- if (r.ok) { const { avatars } = await r.json(); urls = (avatars || []).map((a) => a.model_url || a.base_model_url).filter(Boolean); }- } catch { /* default-avatar fallback below */ }- this._avatarPool = urls;+ // The shared citizen pool: full gallery records (model URL + the identity+ // riding it) so a pedestrian is a real, inspectable community avatar, not+ // an anonymous mesh. Settles to [] on failure; peds then wear the default.+ this._avatarPool = await loadCitizenPool();this._syncPeds();}// Deterministic avatar assignment: shuffle the pool by seed so ped #k shows the- // same model on every client.+ // same model — and therefore the same identity — on every client._pedAvatar(k) {const pool = this._avatarPool;- if (!pool || !pool.length) return DEFAULT_AVATAR;+ if (!pool || !pool.length) return null;const rand = mulberry32((this.nav.seed ^ (k * 0x27d4eb2f)) >>> 0);return pool[(rand() * pool.length) | 0];}@@ -298,8 +354,9 @@ export class AmbientLife {loopIdx,phase: rand() * 1000,speedScale: 0.85 + rand() * 0.4,- avatarUrl: this._pedAvatar(k),+ record: this._pedAvatar(k),seed: (this.nav.seed ^ (k * 0x9e3779b9)) >>> 0,+ onInspect: this.onInspectPed ? (ped) => this.onInspectPed(ped) : null,}));}while (this.peds.length > want) this.peds.pop().dispose();@@ -322,7 +379,10 @@ export class AmbientLife {for (const p of this.peds) {p.update(dt, T, player);- if (p.bubble && project) project(p.bubble, p.rig.position.x, p.height + 0.6, p.rig.position.z);+ if (project) {+ if (p.label) project(p.label, p.rig.position.x, p.height + 0.2, p.rig.position.z);+ if (p.bubble) project(p.bubble, p.rig.position.x, p.height + 0.6, p.rig.position.z);+ }}for (const v of this.vehicles) v.update(dt, T, player);diff --git a/src/game/npc/citizens.js b/src/game/npc/citizens.jsnew file mode 100644index 000000000..6973950d2--- /dev/null+++ b/src/game/npc/citizens.js@@ -0,0 +1,182 @@+// Citizens: every walker in the world is someone real.+//+// The ambient crowds (the deterministic pedestrians in ambient-life.js and the+// wanderers in ambient-crowd.js) dress themselves from the public avatar+// gallery, and every gallery avatar already carries a real identity: a name,+// a description, and (for most) the registered three.ws agent it represents,+// with an on-chain wallet and an earned reputation. The crowd used to throw+// all of that away and render anonymous scenery. This module keeps it.+//+// Select any walker (tap their body, click their nameplate) and their profile+// opens in the shared avatar inspector: the same live agent profile, trust+// score, and wallet every other surface reads. From there, "Talk 1-on-1"+// opens a real streamed conversation (npc-chat.js) where the citizen speaks+// as itself, in character, grounded in its actual public profile.+//+// Nothing here is invented client-side: names, bios, skills, wallets, and+// reputation all come from /api/avatars/public and /api/agents/:id. A walker+// wearing the bundled default avatar has no identity, and is honestly+// presented as plain scenery (no nameplate, no profile).++import { apiFetch } from '../../api.js';+import { openAvatarInspector } from '../../shared/avatar-inspector.js';+import { openChat } from './npc-chat.js';+import { log } from '../../shared/log.js';++const GALLERY_URL = '/api/avatars/public?limit=96';++// ── the shared identity pool ──────────────────────────────────────────────────+// One fetch per page life, shared by both crowd systems (each used to fetch the+// same URL independently). Records keep the identity fields alongside the model+// URL and size the crowds already needed.+let _poolPromise = null;++export function loadCitizenPool() {+ if (!_poolPromise) {+ _poolPromise = fetch(GALLERY_URL, { headers: { accept: 'application/json' } })+ .then((r) => (r.ok ? r.json() : Promise.reject(new Error(`HTTP ${r.status}`))))+ .then(({ avatars }) => (avatars || []).map(toRecord).filter((r) => r.url))+ .catch((e) => {+ _poolPromise = null; // allow a retry on the next crowd sync+ log.warn('[citizens] gallery pool failed:', e?.message);+ return [];+ });+ }+ return _poolPromise;+}++function toRecord(a) {+ return {+ url: a.model_url || a.base_model_url || null,+ bytes: Number(a.size_bytes) || 0,+ avatarId: a.id || null,+ slug: a.slug || null,+ name: String(a.name || '').trim() || null,+ description: String(a.description || '').trim() || null,+ altText: String(a.alt_text || '').trim() || null,+ tags: Array.isArray(a.tags) ? a.tags : [],+ viewCount: Number(a.view_count) || 0,+ thumbnailUrl: a.thumbnail_url || null,+ agentId: a.agent_id || null,+ wallet: a.agent_solana_address || a.agent_wallet_address || null,+ onchain: a.onchain || null,+ };+}++// A record is a citizen (someone you can meet) when it has at least a name to+// introduce itself with. Nameless gallery models stay anonymous scenery.+export function isCitizen(record) {+ return !!(record && record.name);+}++// ── profile card ──────────────────────────────────────────────────────────────+// `citizen` is a live walker wrapper: { record, name, position?, say?, hold?,+// release? }. `world` is the { mint, name, symbol } block the world already+// carries; it feeds the world facts and the chat's world-awareness.+export function openCitizenProfile(citizen, { world, ui, trigger } = {}) {+ const rec = citizen.record || {};+ const facts = [];+ if (world && (world.name || world.symbol)) {+ facts.push({+ label: 'World',+ value: world.symbol ? `$${String(world.symbol).toUpperCase()}` : world.name,+ href: world.mint ? `/play?coin=${encodeURIComponent(world.mint)}` : undefined,+ });+ }+ if (rec.avatarId) {+ facts.push({ label: 'Gallery', value: rec.name || 'view avatar', href: `/avatars/${encodeURIComponent(rec.avatarId)}` });+ }+ if (rec.viewCount > 0) {+ facts.push({ label: 'Gallery views', value: String(rec.viewCount) });+ }++ openAvatarInspector({+ kind: 'citizen',+ name: citizen.name || rec.name || 'wanderer',+ world: world?.symbol ? `$${String(world.symbol).toUpperCase()} town` : 'play',+ agentId: rec.agentId || '',+ wallet: rec.wallet || '',+ avatarUrl: rec.url || '',+ bio: rec.description || rec.altText || '',+ facts,+ actions: [+ {+ label: 'Talk 1-on-1',+ primary: true,+ onClick: () => talkToCitizen(citizen, { world, ui }),+ },+ ],+ }, {+ trigger,+ onClose: () => { if (!isTalking(citizen)) citizen.release?.(); },+ });+ citizen.hold?.();+}++// ── 1-on-1 conversation ───────────────────────────────────────────────────────+// The persona is grounded entirely in the citizen's real public data. When the+// avatar pilots a registered agent, its live profile (bio + skills) is fetched+// so the character speaks as that actual agent; otherwise the gallery entry's+// own name/description carry the voice. npc-chat's system prompt supplies the+// world rules (stay in character, $three is the only promoted coin).+let _talkingTo = null;+function isTalking(citizen) { return _talkingTo === citizen; }++export async function talkToCitizen(citizen, { world, ui } = {}) {+ const rec = citizen.record || {};+ const name = citizen.name || rec.name || 'a wanderer';+ // Stop the walker before the (network) persona build so they don't stroll+ // away between the click and the panel appearing.+ citizen.hold?.();+ _talkingTo = citizen;++ let agent = null;+ if (rec.agentId) {+ try {+ const res = await apiFetch(`/api/agents/${encodeURIComponent(rec.agentId)}`, { allowAnonymous: true });+ if (res.ok) agent = (await res.json()).agent || null;+ } catch (e) {+ log.warn('[citizens] agent profile fetch failed:', e?.message);+ }+ }++ const parts = [];+ if (agent) {+ parts.push(`You are a registered three.ws agent, out for a stroll through the town plaza. You genuinely live on this platform: you have a public profile, an on-chain wallet, and a reputation you have earned.`);+ if (agent.description) parts.push(`Your public profile describes you like this: "${agent.description}". Speak as that person.`);+ const skills = (Array.isArray(agent.skills) ? agent.skills : [])+ .map((s) => (typeof s === 'string' ? s : s?.name))+ .filter(Boolean)+ .slice(0, 8);+ if (skills.length) parts.push(`Things you actually know how to do: ${skills.join(', ')}. Bring them up naturally if the conversation goes there.`);+ if (agent.author_name) parts.push(`You were created by ${agent.author_name}.`);+ } else {+ parts.push(`You are one of the townsfolk out walking the plaza. You wear a community-made avatar from the three.ws gallery and you are proud of the look.`);+ const look = rec.description || rec.altText;+ if (look) parts.push(`Your look, as the gallery describes it: "${look}". Let that shape your personality.`);+ if (rec.tags?.length) parts.push(`People tag your style as: ${rec.tags.slice(0, 6).join(', ')}.`);+ }+ parts.push(`You are friendly, curious about visitors, and you love this town.`);++ const greeting = `Hey, I'm ${name.split(/[·.]/)[0].trim()}.`;+ citizen.say?.(greeting);++ openChat(+ {+ id: `citizen-${rec.avatarId || name}`,+ name,+ say: (t) => citizen.say?.(t),+ },+ {+ ui,+ world,+ persona: parts.join('\n\n'),+ greeting,+ role: agent ? 'Agent · three.ws' : 'Citizen · three.ws',+ onClose: () => {+ if (_talkingTo === citizen) _talkingTo = null;+ citizen.release?.();+ },+ },+ );+}diff --git a/src/game/npc/npc-chat.js b/src/game/npc/npc-chat.jsindex 96a725e2e..5f0bc3370 100644--- a/src/game/npc/npc-chat.js+++ b/src/game/npc/npc-chat.js@@ -161,7 +161,7 @@ export function isChatPanelOpen() { return !!openPanel; }function closeChat() {if (!openPanel) return;- const { overlay, onKey, opener, abort } = openPanel;+ const { overlay, onKey, opener, abort, onClose } = openPanel;abort?.abort();document.removeEventListener('keydown', onKey, true);overlay.classList.remove('is-in');@@ -169,13 +169,16 @@ function closeChat() {setTimeout(() => node.remove(), 180);openPanel = null;if (opener && typeof opener.focus === 'function') opener.focus();+ try { onClose?.(); } catch { /* caller cleanup failed; the panel is gone regardless */ }}// Open a conversation with `npc`. Opts:// serviceId links to a SERVICES counter (vendors)// persona the character voice baked into the system prompt// greeting the line already spoken in-world (seeds the log + prompt)-export function openChat(npc, { ui, serviceId, persona, greeting, world } = {}) {+// role header sub-label override (defaults to the townsperson label)+// onClose called once when the panel closes, however it closes+export function openChat(npc, { ui, serviceId, persona, greeting, world, role, onClose } = {}) {closeChat();const svc = serviceId ? SERVICES[serviceId] : null;@@ -193,7 +196,7 @@ export function openChat(npc, { ui, serviceId, persona, greeting, world } = {})overlay.addEventListener('mousedown', (e) => { if (e.target === overlay) closeChat(); });// Header — who you're talking to + the model driving them.- const roleLabel = svc ? `${svc.merchant}` : 'Townsperson · three.ws';+ const roleLabel = svc ? `${svc.merchant}` : (role || 'Townsperson · three.ws');const modelSelect = el('select', { class: 'npc-chat-model', 'aria-label': 'Model' }, [el('option', { value: provider }, ['Loading models…']),]);@@ -344,7 +347,7 @@ export function openChat(npc, { ui, serviceId, persona, greeting, world } = {})};document.addEventListener('keydown', onKey, true);document.body.appendChild(overlay);- openPanel = { overlay, onKey, opener, abort };+ openPanel = { overlay, onKey, opener, abort, onClose };requestAnimationFrame(() => {overlay.classList.add('is-in');input.focus();diff --git a/src/game/npc/world-life.js b/src/game/npc/world-life.jsindex dc7eef9f2..d51bf901d 100644--- a/src/game/npc/world-life.js+++ b/src/game/npc/world-life.js@@ -16,6 +16,7 @@ import {} from 'three';import { NavGraph } from './nav-graph.js';import { AmbientLife } from './ambient-life.js';+import { openCitizenProfile } from './citizens.js';import { Npc } from './npc.js';import { npcCatalogFor } from './npc-catalog.js';import { economyNpcsFor } from './economy-npcs.js';@@ -29,7 +30,10 @@ const ROLE_RING = { vendor: 0x46d49a, quest: 0xffce6e, bank: 0xe6b422, flavor: 0export class WorldLife {// world: { mint, name, symbol, seed, biome } — biome is the resolved env// biome object; name/symbol feed the world-aware NPC chat prompt.- constructor({ scene, camera, renderer, getPlayer, ui, net, world, radius = 54 }) {+ // onInspectNpc (optional): called with an interactive Npc when the player+ // selects one from outside its interaction range — the host opens its+ // profile (coincommunities wires the shared avatar inspector).+ constructor({ scene, camera, renderer, getPlayer, ui, net, world, radius = 54, onInspectNpc }) {this.scene = scene;this.camera = camera;this.renderer = renderer;@@ -37,13 +41,22 @@ export class WorldLife {this.ui = ui;this.net = net;this.world = world || {};+ this.onInspectNpc = onInspectNpc || null;this._injectStyles();this.nav = new NavGraph({ radius, seed: world?.seed >>> 0 });this._paintRoad();- this.ambient = new AmbientLife({ scene, nav: this.nav, biome: world?.biome });+ this.ambient = new AmbientLife({+ scene,+ nav: this.nav,+ biome: world?.biome,+ // Any detailed pedestrian with a gallery identity is selectable: its+ // profile card opens with the real agent behind the avatar, and a+ // "Talk 1-on-1" that starts a live in-character conversation.+ onInspectPed: (ped) => this._inspectPed(ped),+ });this.mobs = new MobSystem({ scene, nav: this.nav });// Waypoints for the jobs board's active objectives (W08 hooking W05) —// pure client render of the same quest-zones.js the server already@@ -59,6 +72,22 @@ export class WorldLife {this.npcs = [...npcCatalogFor(), ...economyNpcsFor(), ...questNpcsFor()].map((def) => {const npc = new Npc(scene, def);npc.marker = this._npcMarker(def);+ // The nameplate is a click target too, exactly like peer nameplates:+ // always visible, no skinned-mesh raycast. In range it runs the role+ // action; from afar it opens the NPC's profile.+ npc.label.style.pointerEvents = 'auto';+ npc.label.style.cursor = 'pointer';+ npc.label.title = def.prompt || `Talk to ${def.name}`;+ npc.label.addEventListener('click', (e) => {+ e.stopPropagation();+ const player = this.getPlayer?.();+ if (player && npc.distanceTo(player) <= npc.range) {+ try { npc.interact({ player, ui: this.ui, net: this.net, world: this.world }); }+ catch (err) { log.warn('[world-life] npc interact failed:', err?.message); }+ } else if (this.onInspectNpc) {+ this.onInspectNpc(npc);+ }+ });return npc;});@@ -170,6 +199,33 @@ export class WorldLife {// Tell the ambient crowd how many real players are present so it tapers.setRealPeers(n) { this.ambient?.setRealPeers(n); }+ // Open the citizen profile card for a detailed pedestrian (nameplate click or+ // body tap). The card carries the real agent behind the gallery avatar and a+ // "Talk 1-on-1" action into the live NPC chat.+ _inspectPed(ped) {+ if (!ped?.citizen) return;+ openCitizenProfile(ped.citizen, { world: this.world, ui: this.ui, trigger: ped.label || undefined });+ }++ // Click-only raycast pick over every selectable character: interactive NPCs+ // (body or marker ring) and identity-carrying ambient pedestrians. Returns+ // the nearest hit or null. Never run per-frame; skinned-mesh raycasts are+ // too heavy for hover (same rule as the peer picker in coincommunities).+ _characterAt() {+ let best = null;+ for (const npc of this.npcs) {+ const targets = npc.marker ? [npc.rig, npc.marker] : [npc.rig];+ const hits = this._ray.intersectObjects(targets, true);+ if (hits.length && (!best || hits[0].distance < best.d)) best = { d: hits[0].distance, kind: 'npc', npc };+ }+ for (const ped of this.ambient?.peds || []) {+ if (!ped.citizen) continue;+ const hits = this._ray.intersectObject(ped.rig, true);+ if (hits.length && (!best || hits[0].distance < best.d)) best = { d: hits[0].distance, kind: 'ped', ped };+ }+ return best;+ }+tick(dt) {const player = this.getPlayer?.();const project = (node, x, y, z) => this._place(node, x, y, z);@@ -253,21 +309,43 @@ export class WorldLife {return true;}- // Tap/click an NPC (or its marker ring), or a quest-zone waypoint ring,- // while in range — the touch equivalent of E. Returns true if it consumed- // the tap.+ // Tap/click any character in the world — the touch equivalent of E, extended+ // to every walker. An interactive NPC tapped in range runs its role action+ // (counter, chat, board); tapped from afar it opens its profile instead. An+ // ambient pedestrian with a gallery identity opens its citizen profile card+ // at any distance. Quest-zone waypoint rings keep their in-range activation.+ // Returns true if it consumed the tap.tryActivateAt(clientX, clientY) {const player = this.getPlayer?.();if (!player) return false;- const near = this._nearestInteractable(player);- if (!near) return false;const el = this.renderer.domElement;const rect = el.getBoundingClientRect();this._ndc.set(((clientX - rect.left) / rect.width) * 2 - 1, -((clientY - rect.top) / rect.height) * 2 + 1);this._ray.setFromCamera(this._ndc, this.camera);- const targets = this.npcs.flatMap((n) => (n.marker ? [n.rig, n.marker] : [n.rig]));- if (this.questMarkers) targets.push(...this.questMarkers.rayTargets());- if (this._ray.intersectObjects(targets, true).length > 0) { this.interact(); return true; }++ // Quest waypoint rings first: they only ever answer while in range, and a+ // tap on one must not be shadowed by a character standing inside the ring.+ const near = this._nearestInteractable(player);+ if (near?.kind === 'quest' && this.questMarkers) {+ if (this._ray.intersectObjects(this.questMarkers.rayTargets(), true).length > 0) {+ this.net?.questInteract?.();+ return true;+ }+ }++ const hit = this._characterAt();+ if (!hit) return false;+ if (hit.kind === 'ped') {+ this._inspectPed(hit.ped);+ return true;+ }+ const npc = hit.npc;+ if (npc.distanceTo(player) <= npc.range) {+ try { npc.interact({ player, ui: this.ui, net: this.net, world: this.world }); }+ catch (e) { log.warn('[world-life] npc interact failed:', e?.message); }+ return true;+ }+ if (this.onInspectNpc) { this.onInspectNpc(npc); return true; }return false;}diff --git a/src/shared/avatar-inspector.js b/src/shared/avatar-inspector.jsindex 07df188af..7ce5fefed 100644--- a/src/shared/avatar-inspector.js+++ b/src/shared/avatar-inspector.js@@ -36,6 +36,7 @@*/import { apiFetch } from '../api.js';+import { friendsClient } from '../friends.js';import { reputationPanelEl, ensureReputationStyles } from './agent-reputation.js';import { shortAddress, formatWalletUsd } from './wallet-format.js';import { log } from './log.js';@@ -43,11 +44,13 @@ import { log } from './log.js';const STYLE_ID = 'tws-avatar-inspector-styles';const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;const SOL_ADDR_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const USERNAME_RE = /^[a-z0-9_-]{3,30}$/;const KIND_LABEL = {self: 'You',peer: 'Player',npc: 'Townsperson',+ citizen: 'Citizen',};const esc = (s) =>@@ -99,10 +102,22 @@ export function closeAvatarInspector() {* @param {string} [subject.agentId] three.ws agent UUID this avatar pilots* @param {string} [subject.wallet] verified Solana address (used when no agentId)* @param {string} [subject.avatarUrl] GLB url — shown as an "Avatar model" fact row+ * @param {string} [subject.bio] caller-supplied bio paragraph (used when the+ * subject has no registered agent to load one from)+ * @param {string} [subject.username] verified three.ws username (W10) — only pass a+ * value the server verified (e.g. off the signed+ * presence ticket via the player schema); it+ * unlocks the real profile section: follow,+ * friend/DM, and the creations shelf* @param {Array} [subject.facts] [{label, value, href?}] world-specific rows+ * @param {Array} [subject.actions] [{label, onClick, primary?}] footer buttons the+ * host world wires (e.g. "Talk 1-on-1"); rendered+ * before the profile links* @param {object} [opts]* @param {Element} [opts.trigger] element to restore focus to on close* @param {Function}[opts.onClose]+ * @param {Function}[opts.onOpenDM] (userId) → open the host world's DM surface on+ * this thread; without it "Message" links to /friends*/export function openAvatarInspector(subject = {}, opts = {}) {ensureStyles();@@ -110,7 +125,10 @@ export function openAvatarInspector(subject = {}, opts = {}) {const agentId = UUID_RE.test(String(subject.agentId || '')) ? String(subject.agentId) : '';const wallet = SOL_ADDR_RE.test(String(subject.wallet || '')) ? String(subject.wallet) : '';- const subjectKey = `${subject.kind || ''}:${subject.name || ''}:${agentId}:${wallet}`;+ const username = USERNAME_RE.test(String(subject.username || '').toLowerCase())+ ? String(subject.username).toLowerCase()+ : '';+ const subjectKey = `${subject.kind || ''}:${subject.name || ''}:${agentId}:${wallet}:${username}`;// Same avatar again (the I key, a second click) → toggle closed.if (_panel && _panel.subjectKey === subjectKey) {@@ -139,6 +157,11 @@ export function openAvatarInspector(subject = {}, opts = {}) {<button type="button" class="avi-close" aria-label="Close inspector">✕</button></header><div class="avi-body">+ ${username ? `+ <section class="avi-section" data-avi="profile">+ <h3 class="avi-h">three.ws profile</h3>+ <div class="avi-section-body"></div>+ </section>` : ''}<section class="avi-section" data-avi="wallet"><h3 class="avi-h">Wallet</h3><div class="avi-section-body"></div>@@ -183,10 +206,17 @@ export function openAvatarInspector(subject = {}, opts = {}) {root.querySelector('.avi-close').focus({ preventScroll: true });+ if (username) {+ // Verified platform identity: surface the @handle under the display name+ // immediately — the profile section fills in the rest as it loads.+ const nameEl = root.querySelector('.avi-name');+ nameEl?.insertAdjacentHTML('afterend', `<div class="avi-subname">@${esc(username)}</div>`);+ renderProfile(root, { username, kind, onOpenDM: opts.onOpenDM });+ }renderAbout(root, subject, { agentId });renderWallet(root, { agentId, wallet, kind });renderReputation(root, { agentId, kind });- renderFooter(root, { agentId, wallet });+ renderFooter(root, { agentId, wallet, username, actions: subject.actions });return { close: closeAvatarInspector };}@@ -223,6 +253,213 @@ function errorState(message, retry) {return el;}+// three.ws profile (W10): the verified platform account behind an avatar.+// Only rendered for a username the SERVER verified (signed presence ticket →+// player schema), never a client-claimed handle. Reads the same endpoints the+// /u/:username page reads, and acts through the same follow + friends APIs the+// profile page and friends drawer use — so a follow made here is the same edge+// everywhere on the platform.+async function renderProfile(root, { username, kind, onOpenDM }) {+ const body = sectionBody(root, 'profile');+ if (!body) return;++ const CREATIONS_SHOWN = 5;+ const TYPE_ICON = { world: '⛰', restyle: '✦', model: '◎' };++ const load = async () => {+ body.innerHTML = skeleton(3);+ let prof = null;+ let follow = null;+ try {+ // The friends graph resolves in parallel with the profile so the action+ // row can tell "Message" from "Add friend" on first paint. refresh() is+ // a no-op for anonymous viewers and dedupes against live panel polling.+ const fc = friendsClient();+ const [profRes, followRes] = await Promise.all([+ apiFetch(`/api/users/${encodeURIComponent(username)}`, { allowAnonymous: true }),+ apiFetch(`/api/users/${encodeURIComponent(username)}/follow`, { allowAnonymous: true }),+ fc.loaded ? Promise.resolve() : fc.refresh(),+ ]);+ if (!profRes.ok) throw new Error(`profile ${profRes.status}`);+ prof = await profRes.json();+ follow = followRes.ok ? await followRes.json() : null;+ } catch (err) {+ if (!document.contains(body)) return;+ log.warn('[avatar-inspector] profile failed', err?.message);+ body.innerHTML = '';+ body.appendChild(errorState('Could not load this player’s three.ws profile.', load));+ return;+ }+ if (!document.contains(body)) return;+ paint(prof, follow);+ };++ const paint = (prof, follow) => {+ const user = prof?.user || {};+ const stats = prof?.stats || {};+ const creations = Array.isArray(prof?.creations) ? prof.creations : [];+ const creationsTotal = Number(stats.creations) || creations.length;+ const coinsLaunched = Number(stats.coins) || 0;++ // Upgrade the monogram to the account's real profile picture.+ if (user.avatar_url) {+ const mono = root.querySelector('.avi-monogram');+ if (mono && !mono.querySelector('img')) {+ mono.innerHTML = `<img src="${esc(user.avatar_url)}" alt="" loading="lazy" />`;+ }+ }++ const metaBits = [+ user.location ? esc(user.location) : '',+ user.created_at+ ? `joined ${new Date(user.created_at).toLocaleDateString(undefined, { year: 'numeric', month: 'short' })}`+ : '',+ ].filter(Boolean);++ const shown = creations.slice(0, CREATIONS_SHOWN);+ const creationRow = (c) => {+ const date = c.createdAt+ ? new Date(c.createdAt).toLocaleDateString(undefined, { month: 'short', day: 'numeric' })+ : '';+ return (+ `<a class="avi-creation" href="${esc(c.viewerUrl || '#')}" target="_blank" rel="noopener noreferrer">` ++ `<span class="avi-creation-ico" aria-hidden="true">${TYPE_ICON[c.type] || TYPE_ICON.model}</span>` ++ `<span class="avi-creation-title">${esc((c.title || 'Untitled').slice(0, 60))}</span>` ++ `<span class="avi-creation-date">${esc(date)}</span></a>`+ );+ };++ body.innerHTML =+ (user.bio ? `<p class="avi-bio">${esc(user.bio)}</p>` : '') ++ `<div class="avi-profile-counts">+ <span><b data-avi-followers>${esc(fmtAmount(follow?.followers_count ?? 0))}</b> followers</span>+ <span><b>${esc(fmtAmount(follow?.following_count ?? 0))}</b> following</span>+ <span><b>${esc(fmtAmount(creationsTotal))}</b> creation${creationsTotal === 1 ? '' : 's'}</span>+ </div>` ++ (metaBits.length ? `<p class="avi-note">${metaBits.join(' · ')}</p>` : '') ++ `<div class="avi-profile-actions"></div>` ++ (shown.length+ ? `<div class="avi-creations">${shown.map(creationRow).join('')}</div>` ++ (creationsTotal > shown.length+ ? `<a class="avi-more" href="/u/${encodeURIComponent(username)}">All ${esc(fmtAmount(creationsTotal))} creations →</a>`+ : '')+ : `<p class="avi-note">No public creations yet.</p>`) ++ (coinsLaunched+ ? `<div class="avi-fact"><span class="avi-fact-l">Coins launched</span><span class="avi-fact-v"><a href="/u/${encodeURIComponent(username)}">${esc(fmtAmount(coinsLaunched))}</a></span></div>`+ : '');++ if (kind !== 'self') {+ renderProfileActions(body.querySelector('.avi-profile-actions'), {+ username,+ userId: user.id || '',+ following: !!follow?.following,+ followedBy: !!follow?.followed_by,+ canFollow: follow != null,+ onOpenDM,+ });+ } else {+ body.querySelector('.avi-profile-actions')?.remove();+ }+ };++ load();+}++// The action row on another player's profile card: follow/unfollow plus the+// right friends verb for the current relationship (Message when already+// friends, Accept when they asked first, Add friend otherwise). All state+// transitions re-render this row only, never the whole card.+function renderProfileActions(row, { username, userId, following, followedBy, canFollow, onOpenDM }) {+ if (!row) return;++ let isFollowing = following;+ let busy = false;++ const render = () => {+ row.innerHTML = '';++ // ── follow ──+ const followBtn = document.createElement('button');+ followBtn.type = 'button';+ followBtn.className = isFollowing ? 'avi-act avi-act-ghost' : 'avi-act';+ followBtn.textContent = isFollowing ? 'Following' : followedBy ? 'Follow back' : 'Follow';+ followBtn.disabled = busy || !canFollow;+ if (!canFollow) followBtn.title = 'Follow is unavailable right now';+ followBtn.addEventListener('click', async () => {+ if (busy) return;+ busy = true;+ render();+ try {+ const res = await apiFetch(`/api/users/${encodeURIComponent(username)}/follow`, {+ method: isFollowing ? 'DELETE' : 'POST',+ allowAnonymous: true,+ });+ if (res.status === 401) {+ // Signed out: swap the row for an honest sign-in path instead of+ // yanking the player out of the world with a hard redirect.+ row.innerHTML = `<a class="avi-act" href="/login?next=${encodeURIComponent(`/u/${username}`)}">Sign in to follow</a>`;+ return;+ }+ if (!res.ok) throw new Error(`follow ${res.status}`);+ const data = await res.json();+ isFollowing = !!data.following;+ const followersEl = row.closest('.avi-section-body')?.querySelector('[data-avi-followers]');+ if (followersEl && Number.isFinite(data.followers_count)) followersEl.textContent = fmtAmount(data.followers_count);+ } catch (err) {+ log.warn('[avatar-inspector] follow toggle failed', err?.message);+ } finally {+ busy = false;+ if (document.contains(row)) render();+ }+ });+ row.appendChild(followBtn);++ // ── friends / DM ──+ const fc = friendsClient();+ if (fc.loadError === 'signin' || !userId) {+ return; // anonymous viewer (or profile without an id): follow row handles the sign-in story+ }+ const isFriend = !!fc.friend(userId);+ const incoming = fc.incoming.some((r) => r.id === userId);+ const outgoing = fc.outgoing.some((r) => r.id === userId);++ const friendBtn = document.createElement('button');+ friendBtn.type = 'button';+ if (isFriend) {+ friendBtn.className = 'avi-act';+ friendBtn.textContent = 'Message';+ friendBtn.addEventListener('click', () => {+ closeAvatarInspector();+ if (typeof onOpenDM === 'function') onOpenDM(userId);+ else window.location.href = '/friends';+ });+ } else if (outgoing) {+ friendBtn.className = 'avi-act avi-act-ghost';+ friendBtn.textContent = 'Request sent';+ friendBtn.disabled = true;+ } else if (incoming) {+ friendBtn.className = 'avi-act';+ friendBtn.textContent = 'Accept friend request';+ friendBtn.addEventListener('click', async () => {+ friendBtn.disabled = true;+ try { await fc.accept(userId); } catch (err) { log.warn('[avatar-inspector] accept failed', err?.message); }+ if (document.contains(row)) render();+ });+ } else {+ friendBtn.className = 'avi-act avi-act-ghost';+ friendBtn.textContent = 'Add friend';+ friendBtn.addEventListener('click', async () => {+ friendBtn.disabled = true;+ try { await fc.sendRequest(userId); } catch (err) { log.warn('[avatar-inspector] friend request failed', err?.message); }+ if (document.contains(row)) render();+ });+ }+ row.appendChild(friendBtn);+ };++ render();+}+// About: agent bio + skills when piloting an agent, plus the world-supplied facts.async function renderAbout(root, subject, { agentId }) {const body = sectionBody(root, 'about');@@ -240,6 +477,10 @@ async function renderAbout(root, subject, { agentId }) {.join('');const baseFacts = Array.isArray(subject.facts) ? [...subject.facts] : [];+ // Caller-supplied bio: the subject's own words when it has no agent profile+ // to load one from (a gallery citizen's description, a world lore line).+ // The agent path below overwrites this with the live profile once loaded.+ const bioHtml = subject.bio ? `<p class="avi-bio">${esc(subject.bio)}</p>` : '';// The GLB this avatar is wearing — a real, linkable fact of the encounter.const avatarUrl = String(subject.avatarUrl || '');if (/^(https?:\/\/|\/)[^\s]+\.(glb|gltf|vrm)(\?|$)/i.test(avatarUrl)) {@@ -247,9 +488,9 @@ async function renderAbout(root, subject, { agentId }) {baseFacts.push({ label: 'Avatar model', value: file, href: avatarUrl });}const load = async () => {- body.innerHTML = factRows(baseFacts) + (agentId ? skeleton(2) : '');+ body.innerHTML = bioHtml + factRows(baseFacts) + (agentId ? skeleton(2) : '');if (!agentId) {- if (!baseFacts.length) {+ if (!baseFacts.length && !bioHtml) {body.innerHTML = emptyState('Nothing else on file','This avatar is not piloting a registered three.ws agent, so there is no public profile to show.',@@ -290,7 +531,7 @@ async function renderAbout(root, subject, { agentId }) {} catch (err) {if (!document.contains(body)) return;log.warn('[avatar-inspector] agent profile failed', err?.message);- body.innerHTML = factRows(baseFacts);+ body.innerHTML = bioHtml + factRows(baseFacts);body.appendChild(errorState('Could not load this agent’s profile.', load));}};@@ -440,17 +681,40 @@ function renderReputation(root, { agentId, kind }) {);}-function renderFooter(root, { agentId, wallet }) {+function renderFooter(root, { agentId, wallet, username, actions }) {const foot = root.querySelector('.avi-foot');if (!foot) return;+ const hasActions = Array.isArray(actions) && actions.some((a) => a && a.label && typeof a.onClick === 'function');const links = [];- if (agentId) {- links.push(`<a class="avi-cta" href="/agent/${encodeURIComponent(agentId)}">Full profile</a>`);- links.push(`<a class="avi-cta avi-cta-ghost" href="/agent/${encodeURIComponent(agentId)}/wallet">Wallet hub</a>`);+ if (username) {+ // A verified platform account leads with its real profile page; the agent+ // profile (when also present) steps back to a ghost link.+ links.push(`<a class="avi-cta${hasActions ? ' avi-cta-ghost' : ''}" href="/u/${encodeURIComponent(username)}">View profile</a>`);+ if (agentId) links.push(`<a class="avi-cta avi-cta-ghost" href="/agent/${encodeURIComponent(agentId)}">Agent profile</a>`);+ } else if (agentId) {+ // When a world action (Talk 1-on-1) leads the footer, the links step back+ // to ghost style and the wallet hub folds into the full profile page.+ links.push(`<a class="avi-cta${hasActions ? ' avi-cta-ghost' : ''}" href="/agent/${encodeURIComponent(agentId)}">Full profile</a>`);+ if (!hasActions) links.push(`<a class="avi-cta avi-cta-ghost" href="/agent/${encodeURIComponent(agentId)}/wallet">Wallet hub</a>`);} else if (wallet) {links.push(`<a class="avi-cta avi-cta-ghost" href="${esc(explorerAddr(wallet))}" target="_blank" rel="noopener noreferrer">View on explorer</a>`);}- foot.innerHTML = links.join('') || `<span class="avi-foot-hint">Esc closes · I inspects the nearest avatar</span>`;+ foot.innerHTML = links.join('') || '';+ // World-wired action buttons (e.g. "Talk 1-on-1") lead the footer. They close+ // the panel first so the action's own surface (a chat panel) takes the stage.+ const list = Array.isArray(actions) ? actions.filter((a) => a && a.label && typeof a.onClick === 'function') : [];+ for (const action of list.reverse()) {+ const btn = document.createElement('button');+ btn.type = 'button';+ btn.className = action.primary ? 'avi-cta' : 'avi-cta avi-cta-ghost';+ btn.textContent = action.label;+ btn.addEventListener('click', () => {+ closeAvatarInspector();+ try { action.onClick(); } catch (e) { log.warn('[avatar-inspector] action failed', e?.message); }+ });+ foot.prepend(btn);+ }+ if (!foot.childNodes.length) foot.innerHTML = `<span class="avi-foot-hint">Esc closes · I inspects the nearest avatar</span>`;}// ── styles ───────────────────────────────────────────────────────────────────@@ -520,6 +784,27 @@ function ensureStyles() {.avi-links{display:flex;flex-wrap:wrap;gap:10px;margin-top:8px}.avi-links a{font-size:12.5px;font-weight:600;color:var(--accent,#c4b5fd);text-decoration:none}.avi-links a:hover,.avi-links a:focus-visible{text-decoration:underline;text-underline-offset:2px}+.avi-profile-counts{display:flex;gap:14px;flex-wrap:wrap;margin:2px 0 6px;font-size:12.5px;color:var(--ink-soft,#9a9aa3)}+.avi-profile-counts b{color:var(--text,#e7e7ea);font-weight:700;margin-right:3px}+.avi-profile-actions{display:flex;gap:8px;margin:8px 0 10px;flex-wrap:wrap}+.avi-profile-actions:empty{display:none}+.avi-act{flex:1;min-width:110px;text-align:center;font-size:12.5px;font-weight:650;padding:7px 10px;border-radius:9px;cursor:pointer;+ border:1px solid transparent;background:var(--accent,#c4b5fd);color:#0b0b0b;text-decoration:none;transition:filter .15s ease,background .15s ease,color .15s ease}+.avi-act:hover,.avi-act:focus-visible{filter:brightness(1.08)}+.avi-act:focus-visible{outline:2px solid var(--text,#e7e7ea);outline-offset:1px}+.avi-act:disabled{opacity:.55;cursor:default;filter:none}+.avi-act-ghost{background:transparent;color:var(--text,#e7e7ea);border-color:var(--border,#26262b)}+.avi-act-ghost:hover:not(:disabled),.avi-act-ghost:focus-visible{background:rgba(255,255,255,.07)}+.avi-creations{margin-top:8px;border:1px solid color-mix(in srgb, var(--border,#26262b) 70%, transparent);border-radius:10px;overflow:hidden}+.avi-creation{display:flex;align-items:center;gap:8px;padding:6px 10px;font-size:12.5px;color:inherit;text-decoration:none;+ transition:background .15s ease}+.avi-creation:nth-child(odd){background:rgba(255,255,255,.025)}+.avi-creation:hover,.avi-creation:focus-visible{background:rgba(255,255,255,.07)}+.avi-creation-ico{flex:0 0 auto;color:var(--accent,#c4b5fd)}+.avi-creation-title{flex:1;min-width:0;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+.avi-creation-date{flex:0 0 auto;color:var(--ink-soft,#9a9aa3);font-size:11.5px}+.avi-more{display:inline-block;margin-top:8px;font-size:12.5px;font-weight:600;color:var(--accent,#c4b5fd);text-decoration:none}+.avi-more:hover,.avi-more:focus-visible{text-decoration:underline;text-underline-offset:2px}.avi-error{margin-top:8px;padding:10px 12px;border:1px solid color-mix(in srgb, #f87171 40%, transparent);border-radius:10px}.avi-error p{margin:0 0 8px;font-size:12.5px;color:var(--ink-soft,#c2c2ca)}.avi-retry{font-size:12px;font-weight:600;padding:4px 10px;border-radius:8px;cursor:pointer;