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
chore: update IRL surfaces, skill monetization pricing, and changelog
nirholas81a002b6e076
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 7219f237b..3bf90d191 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -22,6 +22,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Auto-rigging now keeps your original avatar — the rigged model is a separate, attested, reversible version** — When you upload or generate a static avatar, three.ws automatically rigs it so your agent can walk, wave, and emote. Until now that upgrade overwrote your uploaded model in place. It no longer does: the animation-ready result is saved as a brand-new model linked to your original as its parent, your agent is moved onto it automatically, and the original static avatar is preserved untouched. Each rigged model carries its own content hash, so on-chain glTF attestations and IPFS pins stay honest — nothing ever claims a signature or a pinned CID for bytes that quietly changed underneath it. A version trail records the upgrade so rigging is reversible, and if rigging ever fails you still own your original avatar, which animates through the built-in fallback skeleton. Only coin referenced is $THREE. `[improvement, fix]`- **Avatar creation errors are clearer — and never leak a vendor's billing page** — Reworked every failure message across selfie-to-avatar and prompt-to-avatar so you get plain, actionable guidance — 'the engine is busy, try again', 'we couldn't find a face, use a brighter photo' — instead of a raw third-party error, a provider's name, or a 'buy more credits' billing link. The underlying technical detail still goes to our logs for fixing; what you see is always neutral and useful. `[fix, security]`- **Avatars that didn't finish rigging now self-heal automatically** — Every avatar you create — a GLB upload, a URL import, or a chat/MCP "text → 3D avatar" — is quietly upgraded in the background so it can walk, wave, and emote. Occasionally the very last step of that upgrade could fail after the rig itself had already succeeded (a momentary storage or network blip), and the avatar would stay static with nothing able to retry it — most likely for avatars made headlessly through the API or MCP, which don't sit on a page polling for the result. The completion process is now crash-safe and eventually-consistent: a rig that finished at the provider always lands on your avatar, recovered no matter which path completes it, even after an earlier failure, and safe when several finish at once. The background safety-net sweep now also clears its backlog faster and never lets a stalled job pile up. Only coin referenced is $THREE. `[fix]`+- **Consistent currency formatting across the earnings dashboard** — Subscription income and plan prices on the Monetize dashboard now display with thousands separators (e.g. $1,234.56), matching how the rest of your earnings are shown. Large numbers are easier to read at a glance and every dollar figure on the page now reads the same way. `[improvement]`- **Copy-trading page now shows each of your agents' wallet identity** — On the Copy Trading page, every one of your agents listed under "your copy-trading" now carries the same wallet identity chip you see everywhere else — its vanity address, live value, and a tap-through to the full wallet — so you can read an agent's wallet at a glance before setting it to mirror a leader. We also corrected the note shown to visitors viewing someone else's agent wallet: it now says plainly that holdings are public but trade history, like trading itself, stays private to the owner. Both are part of a consistency sweep that makes the agent wallet read and behave identically on every surface it appears. (`/mirror`) `[improvement]`- **Cosmos Living Worlds: type a world, watch your avatar live in it** — Your avatar no longer has to stand in an empty void. The new Cosmos page turns a few words into a living, photoreal world that plays as a cinematic backdrop behind your 3D avatar — describe a neon Tokyo street in the rain, an alpine lake at sunrise, or a bioluminescent forest at midnight, and NVIDIA's Cosmos world model renders a short animated scene around your character. Pick any avatar (your own creations included), tap a prompt idea or write your own, and watch real progress as the clip renders; when it's done you can download the MP4 or copy a shareable link that reopens the exact world and avatar. It runs free on the NVIDIA NIM tier, and if the lane is ever unavailable your avatar still shines on a living animated backdrop instead of a blank screen. Find it on the Create page or at /cosmos. (`/cosmos`) `[feature]`- **Creating an agent never dead-ends on wallet setup** — Spinning up a new agent now always succeeds, even in the rare moment our custodial-wallet encryption service is briefly unavailable. Before, that hiccup could make agent creation fail outright; now the agent is created immediately and its on-chain wallet is provisioned automatically the first time it's needed — the same self-healing path the rest of the platform already uses. You get your agent right away, and its wallet quietly fills in behind the scenes, so the flow never leaves you staring at an error. `[fix]`diff --git a/api/agents/[id]/skills-pricing.js b/api/agents/[id]/skills-pricing.jsindex 21bdd28f6..2baac6155 100644--- a/api/agents/[id]/skills-pricing.js+++ b/api/agents/[id]/skills-pricing.js@@ -4,10 +4,14 @@ import { requireCsrf } from '../../_lib/csrf.js';import { MonetizationService } from '../../_lib/services/MonetizationService.js';import { z } from 'zod';+const SOLANA_ADDRESS_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const priceSchema = z.object({skill: z.string().trim().min(1).max(100),- amount: z.number().int().min(1),+ // Amount is required for a price gate, ignored (and stored as 0) for an NFT+ // gate, so it is optional here and refined below per gate_type.+ amount: z.number().int().min(1).optional(),currency_mint: z.string().trim().min(1).max(100),chain: z.string().trim().min(1).max(20),trial_uses: z.number().int().min(0).max(10).default(0),@@ -17,11 +21,23 @@ const priceSchema = z// name an amount at or above `minimum_amount` (atomic units, 0 = no floor).pricing_type: z.enum(['fixed', 'pwyw']).default('fixed'),minimum_amount: z.number().int().min(0).nullable().optional(),+ // Access gate: 'price' (default) sells the skill; 'nft' restricts it to+ // holders of `nft_collection_mint`.+ gate_type: z.enum(['price', 'nft']).default('price'),+ nft_collection_mint: z.string().trim().regex(SOLANA_ADDRESS_RE).nullable().optional(),+ })+ .refine((p) => p.gate_type === 'nft' || (p.amount ?? 0) >= 1, {+ message: 'amount is required for a priced skill',+ path: ['amount'],+ })+ .refine((p) => p.gate_type !== 'nft' || !!p.nft_collection_mint, {+ message: 'nft_collection_mint is required for an NFT gate',+ path: ['nft_collection_mint'],})- .refine((p) => p.pricing_type !== 'pwyw' || (p.minimum_amount ?? 0) <= p.amount, {- message: 'minimum cannot exceed the suggested amount',- path: ['minimum_amount'],- });+ .refine(+ (p) => p.gate_type === 'nft' || p.pricing_type !== 'pwyw' || (p.minimum_amount ?? 0) <= (p.amount ?? 0),+ { message: 'minimum cannot exceed the suggested amount', path: ['minimum_amount'] },+ );const pricingUpdateSchema = z.object({prices: z.array(priceSchema),diff --git a/api/auth/x/[action].js b/api/auth/x/[action].jsindex 7688a49eb..f0852b7e8 100644--- a/api/auth/x/[action].js+++ b/api/auth/x/[action].js@@ -137,7 +137,9 @@ async function handleConnect(req, res) {authUrl.searchParams.set('response_type', 'code');authUrl.searchParams.set('client_id', env.X_OAUTH_CLIENT_ID);authUrl.searchParams.set('redirect_uri', `${env.APP_ORIGIN}/api/auth/x/callback`);- authUrl.searchParams.set('scope', 'tweet.read tweet.write users.read offline.access');+ // media.write lets a connected account upload screenshots / walk clips via the+ // v2 media-upload endpoint (see api/share/x.js) before attaching them to a tweet.+ authUrl.searchParams.set('scope', 'tweet.read tweet.write users.read media.write offline.access');authUrl.searchParams.set('state', state);authUrl.searchParams.set('code_challenge', codeChallenge);authUrl.searchParams.set('code_challenge_method', 'S256');diff --git a/api/irl/agent-summary.js b/api/irl/agent-summary.jsindex 8e684dd31..d6e48f2e3 100644--- a/api/irl/agent-summary.js+++ b/api/irl/agent-summary.js@@ -50,6 +50,7 @@ export default wrap(async (req, res) => {SELECT p.id AS pin_id, p.agent_id, p.lat, p.lng, p.heading, p.caption,p.avatar_url, p.avatar_name, p.placed_at, p.expires_at, p.view_count,p.avatar_manifest, p.avatar_base_url, p.avatar_version,+ p.placement_kind, p.fuzz_radius_m,a.name AS agent_name,a.meta->>'solana_address' AS solana_address,COALESCE(ix.total, 0)::int AS interaction_count,@@ -67,6 +68,7 @@ export default wrap(async (req, res) => {SELECT p.id AS pin_id, p.agent_id, p.lat, p.lng, p.heading, p.caption,p.avatar_url, p.avatar_name, p.placed_at, p.expires_at, p.view_count,p.avatar_manifest, p.avatar_base_url, p.avatar_version,+ p.placement_kind, p.fuzz_radius_m,a.name AS agent_name,a.meta->>'solana_address' AS solana_address,0 AS interaction_count,diff --git a/api/monetization/prices.js b/api/monetization/prices.jsindex 4ecc3da0d..c4edb8964 100644--- a/api/monetization/prices.js+++ b/api/monetization/prices.js@@ -14,16 +14,32 @@ import { limits, clientIp } from '../_lib/rate-limit.js';import { requireCsrf } from '../_lib/csrf.js';const SKILL_RE = /^[a-zA-Z0-9][a-zA-Z0-9_-]{0,63}$/;+const SOLANA_ADDRESS_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;// USDC has 6 decimals. 0.000001 USDC = 1 atomic unit.const MIN_PRICE_ATOMIC = 1;-const putBody = z.object({- agent_id: z.string().uuid(),- skill_name: z.string().trim().min(1).max(64).regex(SKILL_RE, 'skill_name must be alphanumeric with hyphens/underscores, max 64 chars'),- price_usdc: z.number().positive(),- currency_mint: z.string().trim().min(1).max(100).default('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'),- chain: z.enum(['solana', 'base', 'evm']).default('solana'),-});+const putBody = z+ .object({+ agent_id: z.string().uuid(),+ skill_name: z.string().trim().min(1).max(64).regex(SKILL_RE, 'skill_name must be alphanumeric with hyphens/underscores, max 64 chars'),+ // Required for a price gate; ignored for an NFT gate (access is the holding,+ // not a payment), so optional here and refined below.+ price_usdc: z.number().positive().optional(),+ currency_mint: z.string().trim().min(1).max(100).default('EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v'),+ chain: z.enum(['solana', 'base', 'evm']).default('solana'),+ // Access gate: 'price' (default) sells the skill; 'nft' restricts it to+ // holders of an NFT from `nft_collection_mint`.+ gate_type: z.enum(['price', 'nft']).default('price'),+ nft_collection_mint: z.string().trim().regex(SOLANA_ADDRESS_RE, 'nft_collection_mint must be a base58 Solana address').nullable().optional(),+ })+ .refine((b) => b.gate_type === 'nft' || typeof b.price_usdc === 'number', {+ message: 'price_usdc is required for a priced skill',+ path: ['price_usdc'],+ })+ .refine((b) => b.gate_type !== 'nft' || !!b.nft_collection_mint, {+ message: 'nft_collection_mint is required for an NFT gate',+ path: ['nft_collection_mint'],+ });const deleteBody = z.object({agent_id: z.string().uuid(),@@ -70,7 +86,8 @@ export default wrap(async (req, res) => {if (!agent) return error(res, 404, 'not_found', 'Agent not found');const prices = await sql`- SELECT id, skill, currency_mint, chain, amount, is_active, created_at, updated_at+ SELECT id, skill, currency_mint, chain, amount, is_active,+ gate_type, nft_collection_mint, created_at, updated_atFROM agent_skill_pricesWHERE agent_id = ${agentId} AND is_active = trueORDER BY skill@@ -96,13 +113,17 @@ export default wrap(async (req, res) => {const body = parse(putBody, await readJson(req));// API field is `skill_name`; the DB column is `skill`. Bind to a local// named `skill` so the SQL reads `${skill}` against the real column.- const { agent_id, skill_name: skill, price_usdc, currency_mint, chain } = body;-- // Convert price_usdc (float like 0.001) to atomic units (bigint-safe integer)- const amountAtomic = Math.round(price_usdc * 1_000_000);- if (amountAtomic < MIN_PRICE_ATOMIC) {+ const { agent_id, skill_name: skill, price_usdc, currency_mint, chain, gate_type } = body;+ const isNft = gate_type === 'nft';++ // For a price gate, convert price_usdc (float like 0.001) to atomic units.+ // For an NFT gate there is no price — amount is stored as 0 so the row stays+ // a valid (premium, not free) entry while access is driven by the holding.+ const amountAtomic = isNft ? 0 : Math.round(price_usdc * 1_000_000);+ if (!isNft && amountAtomic < MIN_PRICE_ATOMIC) {return error(res, 400, 'validation_error', 'price_usdc must be at least 0.000001');}+ const nftCollectionMint = isNft ? body.nft_collection_mint : null;const ownership = await verifyAgentOwnership(agent_id, userId);if (ownership.error) {@@ -114,21 +135,29 @@ export default wrap(async (req, res) => {SELECT id FROM agent_skill_prices WHERE agent_id = ${agent_id} AND skill = ${skill}`;+ // Switching a row's gate type must also reset the columns the CHECK+ // constraint pairs with it (an 'nft' row may not carry trial/time-pass/pwyw+ // price machinery; a 'price' row may not carry a collection mint).await sql`INSERT INTO agent_skill_prices- (agent_id, skill, amount, currency_mint, chain, is_active, updated_at)+ (agent_id, skill, amount, currency_mint, chain, is_active,+ gate_type, nft_collection_mint, updated_at)VALUES- (${agent_id}, ${skill}, ${amountAtomic}, ${currency_mint}, ${chain}, true, now())+ (${agent_id}, ${skill}, ${amountAtomic}, ${currency_mint}, ${chain}, true,+ ${isNft ? 'nft' : 'price'}, ${nftCollectionMint}, now())ON CONFLICT (agent_id, skill) DO UPDATE SET- amount = EXCLUDED.amount,- currency_mint = EXCLUDED.currency_mint,- chain = EXCLUDED.chain,- is_active = true,- updated_at = now()+ amount = EXCLUDED.amount,+ currency_mint = EXCLUDED.currency_mint,+ chain = EXCLUDED.chain,+ is_active = true,+ gate_type = EXCLUDED.gate_type,+ nft_collection_mint = EXCLUDED.nft_collection_mint,+ updated_at = now()`;const [row] = await sql`- SELECT id, skill, currency_mint, chain, amount, is_active, created_at, updated_at+ SELECT id, skill, currency_mint, chain, amount, is_active,+ gate_type, nft_collection_mint, created_at, updated_atFROM agent_skill_pricesWHERE agent_id = ${agent_id} AND skill = ${skill}`;@@ -167,6 +196,7 @@ export default wrap(async (req, res) => {});function formatPrice(row) {+ const gateType = row.gate_type === 'nft' ? 'nft' : 'price';return {id: row.id,skill_name: row.skill,@@ -175,6 +205,8 @@ function formatPrice(row) {currency_mint: row.currency_mint,chain: row.chain,is_active: row.is_active,+ gate_type: gateType,+ nft_collection_mint: gateType === 'nft' ? row.nft_collection_mint ?? null : null,created_at: row.created_at,updated_at: row.updated_at,};diff --git a/data/changelog.json b/data/changelog.jsonindex f3feb30cb..77d90a521 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,14 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-23",+ "title": "Consistent currency formatting across the earnings dashboard",+ "summary": "Subscription income and plan prices on the Monetize dashboard now display with thousands separators (e.g. $1,234.56), matching how the rest of your earnings are shown. Large numbers are easier to read at a glance and every dollar figure on the page now reads the same way.",+ "tags": [+ "improvement"+ ]+ },{"date": "2026-06-23","title": "Top-trader leaderboard loads again",diff --git a/package.json b/package.jsonindex b0a3c68b3..dd4a06825 100644--- a/package.json+++ b/package.json@@ -202,6 +202,9 @@"@dimforge/rapier3d-compat": "^0.19.3","@elevenlabs/elevenlabs-js": "^2.51.0","@ethereum-attestation-service/eas-sdk": "^2.9.1",+ "@ffmpeg/core": "^0.12.10",+ "@ffmpeg/ffmpeg": "^0.12.15",+ "@ffmpeg/util": "^0.12.2","@gltf-transform/core": "^4.4.0","@gltf-transform/extensions": "^4.4.0","@gltf-transform/functions": "^4.4.0",diff --git a/public/changelog.json b/public/changelog.jsonindex 575c02b87..0f694e1e1 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-23T09:32:54.572Z",+ "generated_at": "2026-06-23T09:40:21.507Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -139,6 +139,16 @@"fix"]},+ {+ "date": "2026-06-23",+ "type": "update",+ "title": "Consistent currency formatting across the earnings dashboard",+ "summary": "Subscription income and plan prices on the Monetize dashboard now display with thousands separators (e.g. $1,234.56), matching how the rest of your earnings are shown. Large numbers are easier to read at a glance and every dollar figure on the page now reads the same way.",+ "link": null,+ "tags": [+ "improvement"+ ]+ },{"date": "2026-06-23","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex ed996f6eb..c10cda913 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -110,6 +110,14 @@<category>fix</category><description>Every avatar you create — a GLB upload, a URL import, or a chat/MCP "text → 3D avatar" — is quietly upgraded in the background so it can walk, wave, and emote. Occasionally the very last step of that upgrade could fail after the rig itself had already succeeded (a momentary storage or network blip), and the avatar would stay static with nothing able to retry it — most likely for avatars made headlessly through the API or MCP, which don't sit on a page polling for the result. The completion process is now crash-safe and eventually-consistent: a rig that finished at the provider always lands on your avatar, recovered no matter which path completes it, even after an earlier failure, and safe when several finish at once. The background safety-net sweep now also clears its backlog faster and never lets a stalled job pile up. Only coin referenced is $THREE.</description></item>+ <item>+ <title>Consistent currency formatting across the earnings dashboard</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-06-23:Consistent currency formatting across the earnings dashboard</guid>+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>Subscription income and plan prices on the Monetize dashboard now display with thousands separators (e.g. $1,234.56), matching how the rest of your earnings are shown. Large numbers are easier to read at a glance and every dollar figure on the page now reads the same way.</description>+ </item><item><title>Copy-trading page now shows each of your agents' wallet identity</title><link>https://three.ws/mirror</link>diff --git a/public/features.json b/public/features.jsonindex e8b9a0026..66f5de49d 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-23T09:32:54.507Z",+ "generated_at": "2026-06-23T09:40:21.449Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/src/avatar-edit-walk.js b/src/avatar-edit-walk.jsnew file mode 100644index 000000000..da83aedb9--- /dev/null+++ b/src/avatar-edit-walk.js@@ -0,0 +1,452 @@+/**+ * Walk preview for the avatar customizer — /avatars/:id/edit, "Walk" tab.+ *+ * Drives the *same* TalkScene.root the rest of the editor sculpts, so every+ * bone/blendshape/accessory edit shows up on the walking avatar instantly (no+ * rig reload needed — it's one shared Object3D). On top of the static pose the+ * editor normally shows, this module:+ *+ * • retargets the canonical idle + walk clips onto the avatar and crossfades+ * between them based on ground speed (foot-plant synced via mixer.timeScale),+ * • auto-pilots the avatar around a 1.5m circle when idle, and hands control+ * to WASD / arrow keys the moment the creator drives,+ * • takes over the camera as a smooth third-person follow rig,+ * • optionally loads a task-18 environment (void grid by default) behind it,+ * • caps the canvas to 30fps so the editor stays responsive.+ *+ * Lifecycle: construct once, call enter()/exit() as the Walk tab is shown/hidden,+ * dispose() on teardown. enter()/exit() are idempotent and safe to interleave.+ */++import { Box3, Vector3, MathUtils } from 'three';+import { AnimationManager } from './animation-manager.js';+import {+ fetchEnvironmentManifest,+ resolveEnvName,+ getEnvironment,+ loadEnvironmentScenery,+ loadEnvironmentHDR,+ applySky,+} from './walk-environments.js';+import { log } from './shared/log.js';++const MANIFEST_URL = '/animations/manifest.json';+const CLIP_IDLE = 'idle';+const CLIP_WALK = 'av-walk-feminine';+const NATURAL_WALK_SPEED = 1.5; // m/s cadence the walk clip was authored at++const CIRCLE_RADIUS = 1.5; // m — auto-pilot orbit radius+const WALK_SPEED = 1.0; // m/s — target ground speed+const TURN_RATE = 2.6; // rad/s — manual yaw rate (A/D)+const TURN_LERP = 0.15; // how snappily facing follows the auto-pilot heading+const CAM_DISTANCE = 3.2; // m behind the avatar+const CAM_HEIGHT = 1.85; // m above the ground, at the camera+const CAM_LOOK_HEIGHT = 1.05; // m — point the camera aims at on the avatar+const CAM_LERP = 0.12; // follow-camera smoothing+const FPS_CAP = 30;++export class AvatarWalkPreview {+ /**+ * @param {object} opts+ * @param {import('./voice/talk-scene.js').TalkScene} opts.scene+ * @param {HTMLElement} opts.stageEl the editor stage element (for the on-stage hint + sky)+ * @param {() => void} [opts.pauseAmbient] pause the editor's idle layer while walking+ * @param {() => void} [opts.resumeAmbient] resume it on exit+ */+ constructor({ scene, stageEl, pauseAmbient, resumeAmbient }) {+ this.scene = scene;+ this.stageEl = stageEl || null;+ this.pauseAmbient = pauseAmbient || (() => {});+ this.resumeAmbient = resumeAmbient || (() => {});++ this.active = false;+ this.anim = null;+ this._tickDispose = null;+ this._savedControls = null;+ this._savedSky = '';+ this._origEnvironment = undefined;++ // Locomotion state.+ this.pos = new Vector3(CIRCLE_RADIUS, 0, 0);+ this.heading = 0;+ this.feetY = 0;+ this._motion = null; // 'idle' | 'walk' — last crossfade target+ this._camPos = new Vector3();+ this._camLook = new Vector3();+ this._camReady = false;++ this.keys = { forward: false, back: false, left: false, right: false };++ // Environment.+ this.envManifest = null;+ this.envName = 'void';+ this._envGroup = null;+ this._envDispose = null;+ this._hdrDispose = null;+ this._envToken = 0;++ this._hintEl = null;+ this._onKeyDown = this._onKeyDown.bind(this);+ this._onKeyUp = this._onKeyUp.bind(this);+ this._statusCb = null;+ }++ supported() {+ return !!(this.anim && this.anim.supportsCanonicalClips());+ }++ onStatus(cb) {+ this._statusCb = cb;+ }++ _status(msg) {+ this._statusCb?.(msg);+ }++ /** Lazily load + retarget the idle/walk clips onto the avatar. */+ async _ensureAnim() {+ if (this.anim) return;+ const root = this.scene?.root;+ if (!root) throw new Error('avatar not loaded');+ const anim = new AnimationManager();+ anim.attach(root);+ let defs = [];+ try {+ const manifest = await fetch(MANIFEST_URL, { cache: 'force-cache' }).then((r) => {+ if (!r.ok) throw new Error(`HTTP ${r.status} loading animation manifest`);+ return r.json();+ });+ defs = manifest.filter((d) => d.name === CLIP_IDLE || d.name === CLIP_WALK);+ } catch (err) {+ log.warn('[avatar-edit-walk] manifest load failed:', err?.message);+ }+ anim.setAnimationDefs(defs);+ await anim.loadAll();+ this.anim = anim;+ }++ async enter() {+ if (this.active) return;+ this.active = true;+ this._status('Loading walk…');++ try {+ await this._ensureAnim();+ } catch (err) {+ this.active = false;+ this._status(`Could not start walk: ${err.message}`);+ throw err;+ }+ // A concurrent exit() may have fired while clips streamed in.+ if (!this.active) return;++ this.pauseAmbient();++ // Stop the GLB's own built-in clip (a baked idle) so it can't fight our+ // retargeted locomotion on the shared skeleton.+ this.scene.mixer?.stopAllAction?.();++ // Zero the feet to the ground plane so the avatar reads as standing on the+ // floor / grid rather than floating, then seed the orbit start.+ const box = new Box3().setFromObject(this.scene.root);+ this.feetY = -box.min.y;+ this.pos.set(CIRCLE_RADIUS, 0, 0);+ this.heading = Math.PI; // face along the initial tangent+ this._motion = null;+ this._camReady = false;++ // Hand the camera off from OrbitControls to our follow rig. Nulling the+ // scene's controls makes the render loop's `controls?.update()` a no-op so+ // it can't fight the per-frame camera writes below; restored on exit.+ this._savedControls = this.scene.controls;+ this.scene.controls = null;++ this.scene.setFpsCap?.(FPS_CAP);++ // Default environment: the void grid (task 18). Honours a previously chosen+ // env if enter() is re-run after the creator picked one.+ await this._applyEnvironment(this.envName).catch((err) =>+ log.warn('[avatar-edit-walk] env load failed:', err?.message),+ );++ window.addEventListener('keydown', this._onKeyDown);+ window.addEventListener('keyup', this._onKeyUp);+ this._installHint();++ this._tickDispose = this.scene.addOnTick((dt) => this._tick(dt));++ this._status(+ this.supported()+ ? 'Walking. WASD / arrows to drive.'+ : 'This rig can’t be skeleton-driven — showing it in motion without a leg cycle.',+ );+ }++ async exit() {+ if (!this.active) return;+ this.active = false;++ this._tickDispose?.();+ this._tickDispose = null;++ window.removeEventListener('keydown', this._onKeyDown);+ window.removeEventListener('keyup', this._onKeyUp);+ this.keys = { forward: false, back: false, left: false, right: false };+ this._removeHint();++ this.scene.setFpsCap?.(0);++ // Settle the avatar back to its origin pose for the static editor view.+ if (this.scene.root) {+ this.scene.root.position.set(0, 0, 0);+ this.scene.root.rotation.y = 0;+ }+ this.anim?.crossfadeTo(CLIP_IDLE, 0.0).catch(() => {});++ // Tear down the environment and restore the editor's neutral lighting/sky.+ await this._clearEnvironment();++ // Restore camera control.+ if (this._savedControls) {+ this.scene.controls = this._savedControls;+ this._savedControls = null;+ }+ this.scene.setCameraPreset?.(this.scene.getCameraPreset?.() || 'full');++ this.resumeAmbient();+ this._status('');+ }++ dispose() {+ this.exit();+ this.anim?.dispose();+ this.anim = null;+ this._clearEnvironment();+ }++ // ── Environment ────────────────────────────────────────────────────────++ availableEnvironments() {+ if (!this.envManifest) return [{ name: 'void', label: 'Void' }];+ return this.envManifest.environments.map((e) => ({ name: e.name, label: e.label || e.name }));+ }++ async setEnvironment(name) {+ this.envName = name;+ if (this.active) await this._applyEnvironment(name);+ }++ async _applyEnvironment(name) {+ const token = ++this._envToken;+ if (!this.envManifest) {+ this.envManifest = await fetchEnvironmentManifest().catch(() => ({+ default: 'void',+ environments: [{ name: 'void', label: 'Void', grid: {} }],+ }));+ }+ const resolved = resolveEnvName(this.envManifest, name);+ this.envName = resolved;+ const meta = getEnvironment(this.envManifest, resolved);+ if (!meta) return;++ await this._clearEnvironment(/* keepName */ true);+ if (token !== this._envToken) return;++ const { group, dispose } = await loadEnvironmentScenery(meta);+ if (token !== this._envToken) {+ dispose();+ return;+ }+ this.scene.scene.add(group);+ this._envGroup = group;+ this._envDispose = dispose;++ // Swap in the environment's IBL for believable reflections; stash the+ // editor's RoomEnvironment so exit() can put it back.+ if (this._origEnvironment === undefined) this._origEnvironment = this.scene.scene.environment;+ const hdr = await loadEnvironmentHDR(meta, this.scene.renderer).catch(() => null);+ if (token !== this._envToken) {+ hdr?.dispose();+ return;+ }+ if (hdr) {+ this.scene.scene.environment = hdr.texture;+ this._hdrDispose = hdr.dispose;+ } else {+ this.scene.scene.environment = this._origEnvironment;+ }++ // Paint the stage backdrop to the env sky (void has none → keep editor bg).+ if (this.stageEl) {+ if (!this._savedSky) this._savedSky = this.stageEl.style.background || '';+ if (meta.sky) applySky(meta, this.stageEl);+ else this.stageEl.style.background = this._savedSky;+ }+ }++ async _clearEnvironment(keepName = false) {+ if (this._envGroup) {+ this.scene.scene.remove(this._envGroup);+ this._envDispose?.();+ this._envGroup = null;+ this._envDispose = null;+ }+ if (this._hdrDispose) {+ this._hdrDispose();+ this._hdrDispose = null;+ }+ if (this._origEnvironment !== undefined && this.scene?.scene) {+ this.scene.scene.environment = this._origEnvironment;+ if (!keepName) this._origEnvironment = undefined;+ }+ if (!keepName && this.stageEl && this._savedSky) {+ this.stageEl.style.background = this._savedSky;+ this._savedSky = '';+ }+ }++ // ── Input ──────────────────────────────────────────────────────────────++ _isTypingTarget(t) {+ if (!t) return false;+ const tag = t.tagName;+ return tag === 'INPUT' || tag === 'TEXTAREA' || tag === 'SELECT' || t.isContentEditable;+ }++ _onKeyDown(e) {+ if (!this.active || this._isTypingTarget(e.target)) return;+ if (this._applyKey(e.code, true)) e.preventDefault();+ }++ _onKeyUp(e) {+ if (!this.active) return;+ if (this._applyKey(e.code, false)) e.preventDefault();+ }++ _applyKey(code, down) {+ switch (code) {+ case 'KeyW':+ case 'ArrowUp':+ this.keys.forward = down;+ return true;+ case 'KeyS':+ case 'ArrowDown':+ this.keys.back = down;+ return true;+ case 'KeyA':+ case 'ArrowLeft':+ this.keys.left = down;+ return true;+ case 'KeyD':+ case 'ArrowRight':+ this.keys.right = down;+ return true;+ default:+ return false;+ }+ }++ _hasManualInput() {+ return this.keys.forward || this.keys.back || this.keys.left || this.keys.right;+ }++ // ── Per-frame ────────────────────────────────────────────────────────────++ _tick(dt) {+ if (!this.active || !this.scene.root) return;+ // Clamp dt so a tab-switch stall can't teleport the avatar across the stage.+ const step = Math.min(dt, 0.1);++ let speed = 0;+ if (this._hasManualInput()) {+ speed = this._driveManual(step);+ } else {+ speed = this._driveAutopilot(step);+ }++ // Commit transform to the shared root.+ this.scene.root.position.set(this.pos.x, this.feetY, this.pos.z);+ this.scene.root.rotation.y = this.heading;++ this._updateAnimation(speed, step);+ this._updateCamera(step);+ }++ _driveManual(dt) {+ // Tank-style controls: A/D yaw, W/S translate along facing.+ if (this.keys.left) this.heading += TURN_RATE * dt;+ if (this.keys.right) this.heading -= TURN_RATE * dt;+ const fwd = (this.keys.forward ? 1 : 0) - (this.keys.back ? 1 : 0);+ if (!fwd) return 0;+ const dir = fwd * WALK_SPEED;+ this.pos.x += Math.sin(this.heading) * dir * dt;+ this.pos.z += Math.cos(this.heading) * dir * dt;+ return Math.abs(dir);+ }++ _driveAutopilot(dt) {+ // Steer toward a point a little further along the radius-1.5 circle,+ // gently correcting back to the ring if a prior manual drive left it off.+ const curAngle = Math.atan2(this.pos.z, this.pos.x);+ const aheadAngle = curAngle + 0.35;+ const target = new Vector3(+ Math.cos(aheadAngle) * CIRCLE_RADIUS,+ 0,+ Math.sin(aheadAngle) * CIRCLE_RADIUS,+ );+ const desired = Math.atan2(target.x - this.pos.x, target.z - this.pos.z);+ this.heading = lerpAngle(this.heading, desired, TURN_LERP);+ this.pos.x += Math.sin(this.heading) * WALK_SPEED * dt;+ this.pos.z += Math.cos(this.heading) * WALK_SPEED * dt;+ return WALK_SPEED;+ }++ _updateAnimation(speed, dt) {+ if (!this.anim) return;+ const moving = speed > 0.05;+ const want = moving ? 'walk' : 'idle';+ if (this._motion !== want) {+ this._motion = want;+ this.anim.crossfadeTo(want === 'walk' ? CLIP_WALK : CLIP_IDLE, 0.2).catch(() => {});+ }+ if (this.anim.mixer) {+ this.anim.mixer.timeScale = moving+ ? MathUtils.clamp(speed / NATURAL_WALK_SPEED, 0.5, 1.7)+ : 1;+ }+ this.anim.update(dt);+ }++ _updateCamera(dt) {+ const cam = this.scene.camera;+ if (!cam) return;+ const ax = this.pos.x;+ const az = this.pos.z;+ // Sit behind the avatar along its facing, raised to eye-ish height.+ const desiredPos = this._camPos.set(+ ax - Math.sin(this.heading) * CAM_DISTANCE,+ this.feetY + CAM_HEIGHT,+ az - Math.cos(this.heading) * CAM_DISTANCE,+ );+ const desiredLook = this._camLook.set(ax, this.feetY + CAM_LOOK_HEIGHT, az);++ if (!this._camReady) {+ cam.position.copy(desiredPos);+ this._lookCurrent = desiredLook.clone();+ this._camReady = true;+ } else {+ const lerp = 1 - Math.pow(1 - CAM_LERP, dt * 60); // frame-rate independent+ cam.position.lerp(desiredPos, lerp);+ this._lookCurrent.lerp(desiredLook, lerp);+ }+ cam.lookAt(this._lookCurrent);+ }+}++/** Shortest-path angular lerp so facing never spins the long way round. */+function lerpAngle(a, b, t) {+ let d = (b - a) % (Math.PI * 2);+ if (d > Math.PI) d -= Math.PI * 2;+ if (d < -Math.PI) d += Math.PI * 2;+ return a + d * t;+}diff --git a/src/irl.js b/src/irl.jsindex ce0531fc0..8dafe38cf 100644--- a/src/irl.js+++ b/src/irl.js@@ -1771,8 +1771,14 @@ function discoveryOrigin() {// so the exact standing spot is never recorded. The first-placement consent sheet// (maybeConfirmPlacement) sets it; the choice is remembered across sessions.const PLACEMENT_KIND_KEY = 'irl_placement_kind';+const PLACEMENT_FUZZ_KEY = 'irl_placement_fuzz_m';const PLACEMENT_CONSENT_KEY = 'irl_placement_consented_v1';-const PLACEMENT_FUZZ_RADIUS_M = 30;+// The blur radii the consent sheet offers, and the default. ~30 m drops the agent+// on the same block, ~100 m anywhere on the street, ~250 m somewhere in the+// neighbourhood — all comfortably above GPS error and below the point it stops+// meaning "near here". These mirror the server's FUZZ_MIN_M / FUZZ_MAX_M band.+const PLACEMENT_FUZZ_OPTIONS = [30, 100, 250];+const PLACEMENT_FUZZ_DEFAULT = 100;function getPlacementKind() {try { return localStorage.getItem(PLACEMENT_KIND_KEY) === 'approximate' ? 'approximate' : 'precise'; }@@ -1781,6 +1787,16 @@ function getPlacementKind() {function setPlacementKind(v) {try { localStorage.setItem(PLACEMENT_KIND_KEY, v === 'approximate' ? 'approximate' : 'precise'); } catch {}}+function getPlacementFuzzRadius() {+ try {+ const v = Number(localStorage.getItem(PLACEMENT_FUZZ_KEY));+ return PLACEMENT_FUZZ_OPTIONS.includes(v) ? v : PLACEMENT_FUZZ_DEFAULT;+ } catch { return PLACEMENT_FUZZ_DEFAULT; }+}+function setPlacementFuzzRadius(v) {+ const r = PLACEMENT_FUZZ_OPTIONS.includes(Number(v)) ? Number(v) : PLACEMENT_FUZZ_DEFAULT;+ try { localStorage.setItem(PLACEMENT_FUZZ_KEY, String(r)); } catch {}+}function hasPlacementConsent() {try { return localStorage.getItem(PLACEMENT_CONSENT_KEY) === '1'; } catch { return false; }}@@ -1788,6 +1804,17 @@ function markPlacementConsented() {try { localStorage.setItem(PLACEMENT_CONSENT_KEY, '1'); } catch {}}+// Human-readable badge for a placement choice — shared by the caption chip, the+// My-pins rows, and the inspect sheet so the wording never drifts. An approximate+// pin shows its blur radius; a precise (or legacy/unknown) pin shows the exact pin.+function placementBadgeText(kind, radiusM) {+ if (kind === 'approximate') {+ const r = Number.isFinite(radiusM) ? Math.round(radiusM) : getPlacementFuzzRadius();+ return `≈ Approximate · ~${r} m`;+ }+ return '📍 Exact';+}+// Offset a coordinate by a uniformly-distributed random point inside a disc of// `radiusM` metres (not a square — a square biases the corners). sqrt(rand) gives a// uniform areal distribution; the bearing is uniform. Returns a fresh {lat,lng} so a@@ -1809,8 +1836,9 @@ function applyPlacementKind(lat, lng) {if (getPlacementKind() !== 'approximate') {return { lat, lng, placementKind: 'precise', fuzzRadiusM: 0 };}- const fuzzed = fuzzCoord(lat, lng, PLACEMENT_FUZZ_RADIUS_M);- return { lat: fuzzed.lat, lng: fuzzed.lng, placementKind: 'approximate', fuzzRadiusM: PLACEMENT_FUZZ_RADIUS_M };+ const radiusM = getPlacementFuzzRadius();+ const fuzzed = fuzzCoord(lat, lng, radiusM);+ return { lat: fuzzed.lat, lng: fuzzed.lng, placementKind: 'approximate', fuzzRadiusM: radiusM };}// H3 — Proof-of-presence. The nearby read is bound to a genuine fix: we mint a@@ -2437,12 +2465,104 @@ function focusCaptionWhenOpen() {const safety = setTimeout(focusNow, 360);}-function openCaptionPanel(pinLat, pinLng, headingDeg, source = 'gyro-gps') {+// ── Placement consent sheet (H4) ──────────────────────────────────────────+// The single most consequential moment in /irl is placement: the chosen spot IS+// a real-world location that persists and that anyone nearby can read. Before the+// first placement we make that legible and offer a safer default — drop the agent+// "approximately" (a deliberately fuzzed point) instead of at the exact spot. The+// two choices are equally weighted (no dark pattern); "don't show every time"+// suppresses the sheet on later placements (the remembered kind still applies),+// and the caption-panel "ⓘ" chip re-opens it so the choice is always changeable.+const consentSheet = document.getElementById('irl-consent-sheet');++// Paint the radius segmented control + the heading to reflect the stored choice.+function syncConsentRadius() {+ if (!consentSheet) return;+ const radius = getPlacementFuzzRadius();+ consentSheet.querySelectorAll('[data-fuzz]').forEach((b) => {+ const on = Number(b.dataset.fuzz) === radius;+ b.classList.toggle('on', on);+ b.setAttribute('aria-pressed', String(on));+ });+}++// Open the consent sheet. Resolves true if the user picked a placement kind+// (exact or approximate) — both persist the choice — or false if they cancelled.+// When the markup is missing (degraded DOM) we fail safe to 'precise' and proceed,+// never dead-ending a placement (Rule 9).+function showPlacementConsentSheet() {+ return new Promise((resolve) => {+ if (!consentSheet) { setPlacementKind('precise'); resolve(true); return; }+ const exactBtn = document.getElementById('irl-consent-exact');+ const approxBtn = document.getElementById('irl-consent-approx');+ const cancelBtn = document.getElementById('irl-consent-cancel');+ const dontShow = document.getElementById('irl-consent-dontshow');+ if (dontShow) dontShow.checked = false;+ syncConsentRadius();++ let settled = false;+ const finish = (proceed) => {+ if (settled) return;+ settled = true;+ consentSheet.classList.remove('is-open');+ releaseSheet(consentSheet);+ resolve(proceed);+ };+ const choose = (kind) => {+ setPlacementKind(kind);+ if (dontShow?.checked) markPlacementConsented();+ refreshCaptionPlacementChip();+ finish(true);+ };++ consentSheet.querySelectorAll('[data-fuzz]').forEach((b) => {+ b.onclick = () => { setPlacementFuzzRadius(Number(b.dataset.fuzz)); syncConsentRadius(); };+ });+ if (exactBtn) exactBtn.onclick = () => choose('precise');+ if (approxBtn) approxBtn.onclick = () => choose('approximate');+ if (cancelBtn) cancelBtn.onclick = () => finish(false);++ consentSheet.classList.add('is-open');+ trapSheet(consentSheet, () => finish(false));+ });+}++// Gate a placement on consent. After the user has ticked "don't show every time"+// the sheet is skipped and the remembered kind is used; otherwise it appears and+// the user makes the choice explicitly per placement. Returns whether to proceed.+async function maybeConfirmPlacement() {+ if (hasPlacementConsent()) return true;+ return showPlacementConsentSheet();+}++// The caption panel always shows how THIS pin will be stored (exact vs approximate)+// as a tappable chip — both a clear disclosure and the "ⓘ" re-opener for the+// consent sheet, so the choice is changeable right up to the moment of saving.+const captionPlacementBtn = document.getElementById('irl-caption-placement');+function refreshCaptionPlacementChip() {+ if (!captionPlacementBtn) return;+ const kind = getPlacementKind();+ const badge = captionPlacementBtn.querySelector('.irl-caption-place-badge');+ if (badge) badge.textContent = placementBadgeText(kind, getPlacementFuzzRadius());+ captionPlacementBtn.classList.toggle('is-approx', kind === 'approximate');+ captionPlacementBtn.setAttribute('aria-label',+ `Placement: ${kind === 'approximate' ? `approximate, within about ${getPlacementFuzzRadius()} metres` : 'exact spot'}. Tap to change how this agent's location is stored.`);+}+if (captionPlacementBtn) {+ captionPlacementBtn.onclick = () => { showPlacementConsentSheet(); };+}++async function openCaptionPanel(pinLat, pinLng, headingDeg, source = 'gyro-gps') {+ // Consent gate (H4) — disclose what placing means and let the user choose exact+ // vs approximate before the agent is written. Cancelling here releases the AR+ // lock instead of leaving the user stuck in a locked, half-placed state.+ if (!(await maybeConfirmPlacement())) { setLocked(false); return; }if (!captionPanel) {commitPin(pinLat, pinLng, headingDeg, '', source);return;}captionInput.value = '';+ refreshCaptionPlacementChip();captionPanel.classList.add('is-open');focusCaptionWhenOpen();const cancel = () => {