Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

Wallet net-worth embodiment, balances API, body/money/skills studios; pose and IRL updates

nirholas70b1c2fad6ca
diff --git a/CHANGELOG.md b/CHANGELOG.md
index ca9cac87d..14a0c92a5 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -6,10 +6,13 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-06-23
+- **Feature: carry your agent and set it down anywhere in the room in IRL AR** — On the IRL page your agent used to hover at a fixed distance in front of the camera — you couldn't choose where it stood. New 'Move here' control: turn on Camera AR, tap Move here, and a soft ring tracks the floor under your aim. Tap to set your agent down on that exact spot — the couch, a corner, the middle of the room — and it eases into place and turns to face you. The agent then stays anchored where you put it as you look around: pan away and it's gone, pan back and there it is. This is the first half of placing agents in the real world the way you'd expect; cross-device discovery (a friend finding it on their own phone) is coming next. (`/irl`) `[feature]`
- **Fix: avatars look right in iOS AR, not collapsed and distorted** — Viewing an avatar in AR on iPhone or iPad (the 'Place in your space' / Quick Look flow) could show a mangled figure — limbs balled up at the hips and accessories like glasses floating at giant scale — instead of the avatar you saw on the page. The cause: the AR file format Apple uses doesn't carry an animation skeleton, so the standard exporter shipped the avatar in its raw, un-posed rig. We now freeze each avatar into its proper standing pose before generating the AR file, so what you place in your room matches what you see in the viewer, accessories included. `[fix]`
- **Fix: prompt-to-avatar shows your finished avatar instead of jumping to the editor** — When you described an avatar in words at Create → From a prompt, the 'done' screen was meant to show a live, spinnable preview of the character you just made — the payoff moment. For private avatars (the default), that preview was being skipped and you were dropped straight into the editor with no look at the result. The preview now renders for private avatars too, using the same owner-only secure link the selfie flow already used, so every prompt-built avatar greets you with a real 3D preview you can rotate before opening the editor or making another. (`/create/prompt`) `[fix]`
- **Fix: the bounty board and live token feeds stay up when a third party is slow** — Swept the API for places where a slow or flaky upstream could hang a request until it was force-killed, or a database missing a recent table could error a whole page, and closed them. The /go bounty board now provisions its own database tables, so it loads everywhere instead of erroring where they were absent. The pump trending and search feeds fall back to the last good list (or an empty one) when pump.fun returns a malformed response, rather than failing the page. And a batch of backend lookups — the live SOL price, Jupiter/Birdeye/CoinGecko market data, portfolio price charts, token-gated scene access checks, IPFS pinning, voice synthesis, and the embedded-agent AI fallback chain — now bound every third-party call with a timeout, so a stalled service returns a clean result quickly instead of holding the request open until it's killed. `[fix]`
+- **Improvement: Animation Studio recovers your unsaved animation after a refresh or closed tab** — Posing a figure and keyframing a timeline in the Animation Studio is real work — and until now none of it touched your account until you pressed Save, so an accidental tab close or browser refresh could wipe it. The Studio now quietly keeps a local backup of your in-progress animation as you work, and warns you before you leave with unsaved keyframes. Come back later and it offers the recovered timeline right where you left off — 'Recovered your unsaved animation — 6 keyframes.' Saving to your account or opening a saved clip clears the backup, and an explicit shared link still wins. No work lost between sessions. (`/pose`) `[improvement, feature]`
- **Improvement: Base USDC payments confirm even when an RPC provider is flaky** — When you pay for a skill or asset in USDC on Base, the platform double-checks your payment landed on-chain before unlocking it. That check used to read from a single blockchain provider — so if that one provider was briefly slow or rate-limited, a payment that had genuinely gone through could look stuck as 'pending' until you retried. It now reads through the same multi-provider failover the rest of the platform already uses: if one provider is down it automatically tries the next, and a momentary outage degrades to a safe, retryable state instead of stranding a confirmed payment. Your funds were never at risk either way; this makes the confirmation itself resilient. `[improvement, infra]`
+- **Improvement: every server error now hands you a support reference code** — When something fails on our side, the response no longer just says 'something went wrong' — it now carries a short reference code (e.g. 'quote ref a1b2c3d4 to support'). That same code is attached to the exact server log line, our error tracker, and the ops alert that pages the team, so one code maps to one incident. This was already true for most API responses; we extended it to the remaining surfaces that previously failed silently — the RSS announcements feed, sitemaps, the MCP payment flow, on-chain permission checks, and the Solana RPC proxy — so any failure you hit is traceable. Nothing changes when things work; this only makes the rare error far faster to diagnose. `[improvement, infra]`
## 2026-06-22
diff --git a/api/_lib/networth-model.js b/api/_lib/networth-model.js
new file mode 100644
index 000000000..19777b32e
--- /dev/null
+++ b/api/_lib/networth-model.js
@@ -0,0 +1,187 @@
+// Net-worth → embodiment model (pure, dependency-free).
+//
+// One source of truth for how an agent's REAL on-chain state becomes its 3D
+// presence: the wealth/reputation tier, the aura intensity/colour, the idle
+// confidence, and the legible "regalia" marks. The server computes the canonical
+// look from real reads (api/agents/solana-wallet.js → handleNetWorth) and the
+// browser renders it; src/shared/agent-networth.js imports the same constants for
+// the offline/hold-last-state fallback so the galaxy star, the profile hero, and
+// the AR body always agree.
+//
+// Every output traces to a real number. Nothing here invents a balance — callers
+// pass real portfolio USD, real $THREE holdings, real fork counts, and real
+// reputation, and this maps them onto appearance. A zero wallet yields a calm
+// baseline look, never a punished or fabricated one.
+
+// $THREE is the only coin. Its mint is the one token we ever read a holding of by
+// name; everything else in a wallet is generic runtime data.
+export const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+// Presence tiers, keyed off real portfolio USD value. Names follow the aura
+// metaphor (light, not money) so a well-funded agent reads as *present*, never
+// gaudy. `min` is the real USD threshold that unlocks the tier.
+export const PRESENCE_TIERS = Object.freeze([
+ { key: 'latent', label: 'Latent', min: 0, accent: '#8b8b9a' },
+ { key: 'spark', label: 'Spark', min: 1, accent: '#8b5cf6' },
+ { key: 'glow', label: 'Glow', min: 50, accent: '#a78bfa' },
+ { key: 'radiant', label: 'Radiant', min: 500, accent: '#c4b5fd' },
+ { key: 'luminous', label: 'Luminous', min: 5_000, accent: '#ddd6fe' },
+ { key: 'beacon', label: 'Beacon', min: 50_000, accent: '#f5f3ff' },
+]);
+
+export const REACTIVITY_LEVELS = Object.freeze(['off', 'subtle', 'balanced', 'expressive']);
+
+// Per-signal opt-in/out, all default-on. The owner can hide any single channel
+// (e.g. mute the balance-driven aura while keeping tip reactions).
+export const DEFAULT_PREFS = Object.freeze({
+ reactivity: 'balanced',
+ signals: Object.freeze({ aura: true, events: true, reputation: true }),
+});
+
+const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, Number(n) || 0));
+
+/** Resolve the presence tier (and the next step) from a real USD value. */
+export function tierForUsd(usd) {
+ const v = Math.max(0, Number(usd) || 0);
+ let index = 0;
+ for (let i = 0; i < PRESENCE_TIERS.length; i++) {
+ if (v >= PRESENCE_TIERS[i].min) index = i;
+ }
+ const tier = PRESENCE_TIERS[index];
+ const nextDef = PRESENCE_TIERS[index + 1] || null;
+ const next = nextDef
+ ? { key: nextDef.key, label: nextDef.label, usd_to_next: Math.max(0, nextDef.min - v) }
+ : null;
+ return { key: tier.key, label: tier.label, index, accent: tier.accent, next };
+}
+
+/**
+ * Map real state onto a render-ready look descriptor. Intensity is log-scaled so
+ * the aura grows smoothly across orders of magnitude (a $50k agent doesn't blow
+ * out a $500 one). Confidence blends wealth tier with real reputation.
+ *
+ * @param {object} state
+ * @param {number} state.usd real total portfolio USD
+ * @param {number} [state.threeUsd] real $THREE holding value (extra warmth)
+ * @param {number} [state.forkCount] real forks-of-this-agent
+ * @param {number} [state.repScore] real reputation score 0..100 (optional)
+ * @param {number} [state.attesters] real unique attesters (optional)
+ */
+export function computeLook(state = {}) {
+ const usd = Math.max(0, Number(state.usd) || 0);
+ const tier = tierForUsd(usd);
+
+ // log10($+1)/5 → 0 at $0, ~0.34 at $50, ~0.54 at $500, ~0.74 at $5k, ~0.94 at $50k.
+ const wealth = clamp(Math.log10(usd + 1) / 5, 0, 1);
+
+ // $THREE holders carry a touch more warmth — the only coin earns its glow.
+ const threeUsd = Math.max(0, Number(state.threeUsd) || 0);
+ const threeBoost = threeUsd > 0 ? clamp(Math.log10(threeUsd + 1) / 5, 0, 0.18) : 0;
+
+ const auraIntensity = clamp(wealth + threeBoost, 0, 1);
+
+ // Reputation lifts the idle posture (stands taller / steadier) without touching
+ // the aura, so a brand-new but well-attested agent still reads as trusted.
+ const repScore = clamp(state.repScore, 0, 100) / 100;
+ const forks = Math.max(0, Number(state.forkCount) || 0);
+ const forkBoost = clamp(Math.log10(forks + 1) / 3, 0, 0.25); // 9 forks ~0.33→capped .25
+ const confidence = clamp(tier.index / 5 * 0.6 + repScore * 0.25 + forkBoost, 0, 1);
+
+ // Emissive/material rim steps every two tiers → 0,0,1,1,2,2.
+ const materialTier = Math.floor(tier.index / 2);
+
+ return {
+ tier,
+ auraIntensity,
+ auraColor: tier.accent,
+ materialTier,
+ confidence,
+ // A small static-readable glow floor so the look survives reduced-motion
+ // (the ring is visible even when the pulse animation is suppressed).
+ glow: clamp(0.12 + auraIntensity * 0.88, 0, 1),
+ };
+}
+
+/**
+ * Build the legible reputation regalia — every mark backed by a real number, each
+ * deep-linkable to the wallet hub / the moment that earned it. Order: wealth tier,
+ * $THREE holding, forks, attestation.
+ */
+export function computeMarks(state = {}, { hubUrl = null } = {}) {
+ const marks = [];
+ const usd = Math.max(0, Number(state.usd) || 0);
+ const tier = tierForUsd(usd);
+ if (tier.index > 0) {
+ marks.push({
+ key: 'presence',
+ label: tier.label,
+ value: fmtUsd(usd),
+ detail: `Portfolio ${fmtUsd(usd)}`,
+ href: hubUrl,
+ });
+ }
+ const threeAmount = Math.max(0, Number(state.threeAmount) || 0);
+ if (threeAmount > 0) {
+ marks.push({
+ key: 'three',
+ label: '$THREE holder',
+ value: fmtAmount(threeAmount),
+ detail: `Holds ${fmtAmount(threeAmount)} $THREE${state.threeUsd ? ` (${fmtUsd(state.threeUsd)})` : ''}`,
+ href: hubUrl,
+ });
+ }
+ const forks = Math.max(0, Number(state.forkCount) || 0);
+ if (forks > 0) {
+ marks.push({
+ key: 'forks',
+ label: forks === 1 ? 'Forked once' : `Forked ${forks}×`,
+ value: forks,
+ detail: `${forks} agent${forks === 1 ? '' : 's'} forked from this one`,
+ href: hubUrl,
+ });
+ }
+ const attesters = Math.max(0, Number(state.attesters) || 0);
+ if (attesters > 0) {
+ marks.push({
+ key: 'attested',
+ label: 'Attested',
+ value: attesters,
+ detail: `${attesters} on-chain attester${attesters === 1 ? '' : 's'}`,
+ href: hubUrl,
+ });
+ }
+ return marks;
+}
+
+/** Coerce raw stored prefs into a complete, valid prefs object. */
+export function normalizePrefs(raw) {
+ const r = raw && typeof raw === 'object' ? raw : {};
+ const reactivity = REACTIVITY_LEVELS.includes(r.reactivity) ? r.reactivity : DEFAULT_PREFS.reactivity;
+ const sig = r.signals && typeof r.signals === 'object' ? r.signals : {};
+ return {
+ reactivity,
+ signals: {
+ aura: sig.aura !== false,
+ events: sig.events !== false,
+ reputation: sig.reputation !== false,
+ },
+ };
+}
+
+export function fmtUsd(n) {
+ const v = Number(n) || 0;
+ if (v === 0) return '$0';
+ if (v < 0.01) return '<$0.01';
+ if (v < 1) return `$${v.toFixed(2)}`;
+ if (v < 1000) return `$${v.toFixed(v < 100 ? 1 : 0)}`;
+ if (v < 1_000_000) return `$${(v / 1000).toFixed(v < 10_000 ? 1 : 0)}k`;
+ return `$${(v / 1_000_000).toFixed(1)}M`;
+}
+
+export function fmtAmount(n) {
+ const v = Number(n) || 0;
+ if (v < 1000) return v.toLocaleString(undefined, { maximumFractionDigits: 2 });
+ if (v < 1_000_000) return `${(v / 1000).toFixed(1)}k`;
+ if (v < 1_000_000_000) return `${(v / 1_000_000).toFixed(1)}M`;
+ return `${(v / 1_000_000_000).toFixed(1)}B`;
+}
diff --git a/api/agents/balances.js b/api/agents/balances.js
new file mode 100644
index 000000000..cc838f7a3
--- /dev/null
+++ b/api/agents/balances.js
@@ -0,0 +1,256 @@
+// POST /api/agents/balances — batched, real on-chain wallet valuation for the
+// wallet identity layer.
+//
+// The wallet chip appears in dense lists (trending rows, galaxy cards, the
+// marketplace grid). Firing GET /:id/solana + /holdings per row would be an
+// N×3 request storm. This endpoint takes an array of agent ids and returns one
+// real, cached portfolio descriptor per wallet in a single round-trip, so a list
+// hydrates its visible chips with exactly one request.
+//
+// Every number is real: balances come from the shared on-chain valuation library
+// (Helius DAS → public-RPC fallback, Jupiter/pump.fun pricing), cached 60s. The
+// 24h P&L + sparkline are derived from real periodic value snapshots persisted in
+// wallet_value_snapshots — never a synthesized curve. A wallet with no snapshot
+// history yet returns an empty sparkline (the UI renders its empty state), and if
+// the snapshot table is absent the balances still return with P&L simply null.
+//
+// Public read: balances are public on-chain data, so no auth is required. When a
+// session is present each entry is marked is_owner so the caller can render the
+// "Yours" vs creator-attribution marker without trusting a client-supplied flag.
+
+import { sql, sqlValues } from '../_lib/db.js';
+import { wrap, cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { getSessionUser } from '../_lib/auth.js';
+import { isUuid } from '../_lib/validate.js';
+import { getBalances, walletUsdTotal } from '../_lib/balances.js';
+import { env } from '../_lib/env.js';
+
+const MAX_IDS = 60;
+const FETCH_CONCURRENCY = 8;
+// Don't write more than one snapshot per wallet per this interval — browsing a
+// list shouldn't spam the series. 5 min keeps the sparkline dense enough for a
+// readable curve without bloating the table.
+const SNAPSHOT_MIN_GAP_MS = 5 * 60_000;
+// Sparkline window. Snapshots older than this are ignored for both the curve and
+// the change reference, and a retention sweep can prune past it.
+const PNL_WINDOW_HOURS = 24;
+const SPARKLINE_MAX_POINTS = 24;
+
+const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+
+// Map a unique list through an async fn with a fixed concurrency ceiling so a
+// 60-id batch never opens 60 simultaneous RPC sockets.
+async function mapPool(items, limit, fn) {
+ const out = new Array(items.length);
+ let i = 0;
+ const workers = Array.from({ length: Math.min(limit, items.length) }, async () => {
+ while (i < items.length) {
+ const idx = i++;
+ out[idx] = await fn(items[idx], idx);
+ }
+ });
+ await Promise.all(workers);
+ return out;
+}
+
+// Reduce a full portfolio (native SOL + every priced token) into the compact
+// descriptor the chip + popover render: total USD, the SOL / USDC / $THREE
+// breakdown, a token count, and the top holdings by USD value.
+function summarizePortfolio(portfolio, threeMint) {
+ const tokens = Array.isArray(portfolio?.tokens) ? portfolio.tokens : [];
+ const native = portfolio?.native || null;
+ const usd = walletUsdTotal(portfolio);
+
+ const findToken = (mint) => tokens.find((t) => t.mint === mint) || null;
+ const usdc = findToken(USDC_MINT);
+ const three = threeMint ? findToken(threeMint) : null;
+
+ const topHoldings = tokens
+ .slice()
+ .sort((a, b) => (b.usd || 0) - (a.usd || 0))
+ .slice(0, 4)
+ .map((t) => ({
+ mint: t.mint,
+ symbol: t.symbol,
+ amount: t.amount,
+ usd: t.usd || 0,
+ price: t.price || 0,
+ logo: t.logo || null,
+ }));
+
+ return {
+ usd,
+ sol: {
+ amount: native?.amount ?? 0,
+ usd: native?.usd ?? 0,
+ price: native?.price ?? 0,
+ },
+ usdc: usdc ? { amount: usdc.amount, usd: usdc.usd || 0 } : { amount: 0, usd: 0 },
+ three: three ? { amount: three.amount, usd: three.usd || 0, price: three.price || 0 } : null,
+ tokenCount: tokens.length,
+ topHoldings,
+ };
+}
+
+// Build the { sparkline, changePct, changeUsd, windowHours } block from a real
+// ascending value series (snapshots within the window, plus the just-captured
+// point). Honest by construction: with <2 points there is no curve, so we return
+// an empty sparkline and null change rather than inventing a baseline.
+function derivePnl(series) {
+ if (!Array.isArray(series) || series.length < 2) {
+ return { sparkline: series?.map((s) => s.usd) || [], changePct: null, changeUsd: null, windowHours: null };
+ }
+ const first = series[0];
+ const last = series[series.length - 1];
+ const changeUsd = last.usd - first.usd;
+ const changePct = first.usd > 0 ? (changeUsd / first.usd) * 100 : null;
+ const windowHours = (new Date(last.capturedAt).getTime() - new Date(first.capturedAt).getTime()) / 3_600_000;
+
+ // Downsample to a fixed point budget so a long series stays a tidy payload.
+ let points = series.map((s) => s.usd);
+ if (points.length > SPARKLINE_MAX_POINTS) {
+ const step = points.length / SPARKLINE_MAX_POINTS;
+ points = Array.from({ length: SPARKLINE_MAX_POINTS }, (_, k) => points[Math.floor(k * step)]);
+ points[points.length - 1] = last.usd;
+ }
+ return {
+ sparkline: points,
+ changePct: changePct == null ? null : Number(changePct.toFixed(2)),
+ changeUsd: Number(changeUsd.toFixed(2)),
+ windowHours: Number(windowHours.toFixed(1)),
+ };
+}
+
+// Load each agent's snapshot series within the window, append the freshly-valued
+// point (and persist it, deduped), all wrapped so a missing table degrades to
+// "no P&L" rather than failing the whole balance read.
+async function attachPnl(entries) {
+ const withAddr = entries.filter((e) => e.address && Number.isFinite(e.summary?.usd));
+ if (withAddr.length === 0) return;
+ const agentIds = withAddr.map((e) => e.agentId);
+
+ let seriesByAgent = new Map();
+ try {
+ const rows = await sql`
+ SELECT agent_id, usd_value, captured_at
+ FROM wallet_value_snapshots
+ WHERE agent_id = ANY(${agentIds}::uuid[])
+ AND captured_at > now() - (${PNL_WINDOW_HOURS} || ' hours')::interval
+ ORDER BY agent_id, captured_at ASC
+ `;
+ for (const r of rows) {
+ const list = seriesByAgent.get(r.agent_id) || [];
+ list.push({ usd: Number(r.usd_value), capturedAt: r.captured_at });
+ seriesByAgent.set(r.agent_id, list);
+ }
+ } catch {
+ // Snapshot table not present (un-migrated env) — balances still return,
+ // P&L is simply absent. Don't attempt inserts either.
+ for (const e of withAddr) e.pnl = { sparkline: [], changePct: null, changeUsd: null, windowHours: null };
+ return;
+ }
+
+ const now = Date.now();
+ const toInsert = [];
+ for (const e of withAddr) {
+ const series = seriesByAgent.get(e.agentId) || [];
+ const latest = series[series.length - 1];
+ const stale = !latest || now - new Date(latest.capturedAt).getTime() >= SNAPSHOT_MIN_GAP_MS;
+ if (stale) {
+ const point = { usd: Number(e.summary.usd.toFixed(6)), capturedAt: new Date(now).toISOString() };
+ series.push(point);
+ toInsert.push(e);
+ }
+ e.pnl = derivePnl(series);
+ }
+
+ if (toInsert.length > 0) {
+ // One multi-row insert for every wallet that needed a fresh point.
+ try {
+ const rows = toInsert.map((e) => [
+ e.agentId,
+ e.address,
+ Number(e.summary.usd.toFixed(6)),
+ Number((e.summary.sol?.amount ?? 0).toFixed(9)),
+ ]);
+ await sql`
+ INSERT INTO wallet_value_snapshots (agent_id, address, usd_value, sol_amount)
+ VALUES ${sqlValues(rows)}
+ `;
+ } catch {
+ // Persist is best-effort; the in-memory point still feeds this response.
+ }
+ }
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const auth = await getSessionUser(req).catch(() => null);
+ const rl = await limits.walletRead(auth?.userId || clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const body = await readJson(req).catch(() => null);
+ const rawIds = Array.isArray(body?.ids) ? body.ids : null;
+ if (!rawIds) return error(res, 400, 'validation_error', 'body.ids must be an array of agent ids');
+
+ const ids = [...new Set(rawIds.filter((x) => typeof x === 'string' && isUuid(x)))].slice(0, MAX_IDS);
+ if (ids.length === 0) return json(res, 200, { data: {} });
+
+ const rows = await sql`
+ SELECT id, user_id, meta
+ FROM agent_identities
+ WHERE id = ANY(${ids}) AND deleted_at IS NULL
+ `;
+
+ const threeMint = env.THREE_TOKEN_MINT;
+ const entries = rows.map((row) => ({
+ agentId: row.id,
+ address: row.meta?.solana_address || null,
+ isOwner: !!(auth && row.user_id === auth.userId),
+ ownerId: row.user_id,
+ forkedFrom: row.meta?.forked_from || null,
+ summary: null,
+ pnl: null,
+ }));
+
+ // Value unique addresses once (two agents can't share a custodial wallet, but
+ // dedupe defensively) under a concurrency ceiling.
+ const valued = entries.filter((e) => e.address);
+ await mapPool(valued, FETCH_CONCURRENCY, async (e) => {
+ try {
+ const portfolio = await getBalances({ chain: 'solana', address: e.address });
+ e.summary = summarizePortfolio(portfolio, threeMint);
+ } catch {
+ // One wallet's RPC failure must not blank the batch — mark it unpriced.
+ e.summary = null;
+ }
+ });
+
+ await attachPnl(entries);
+
+ const data = {};
+ for (const e of entries) {
+ data[e.agentId] = {
+ agentId: e.agentId,
+ address: e.address,
+ isOwner: e.isOwner,
+ forkedFrom: e.forkedFrom,
+ ...(e.summary
+ ? {
+ usd: e.summary.usd,
+ sol: e.summary.sol,
+ usdc: e.summary.usdc,
+ three: e.summary.three,
+ tokenCount: e.summary.tokenCount,
+ topHoldings: e.summary.topHoldings,
+ pnl: e.pnl,
+ }
+ : { usd: null, priced: false }),
+ };
+ }
+
+ return json(res, 200, { data });
+});
diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.js
index ccb5bcd71..7517e0c04 100644
--- a/api/agents/solana-wallet.js
+++ b/api/agents/solana-wallet.js
@@ -30,6 +30,10 @@ import {
getSpendLimits, setSpendLimits, listCustodyEvents, updateCustodyEvent, recordCustodyEvent,
getDailySpendUsd, getTradeLimits, setTradeLimits, getDailySpendLamports,
} from '../_lib/agent-trade-guards.js';
+import { getBalances, walletUsdTotal } from '../_lib/balances.js';
+import {
+ THREE_MINT, computeLook, computeMarks, normalizePrefs,
+} from '../_lib/networth-model.js';
// USDC mints per cluster — the only SPL token we can price 1:1 for the spend
// ceiling without an external quote. $THREE is the only coin; USDC is the
@@ -1337,6 +1341,136 @@ async function handleVanity(req, res, id) {
});
}
+// ── net-worth (the agent wears its wallet) ──────────────────────────────────────
+
+// Count agents forked from this one (real lineage rows). Lineage is stored at
+// fork time in agent_identities.meta.forked_from.agent_id (api/avatars/fork.js).
+async function forkCountFor(id) {
+ try {
+ const [r] = await sql`
+ SELECT count(*)::int AS n FROM agent_identities
+ WHERE deleted_at IS NULL AND meta->'forked_from'->>'agent_id' = ${id}
+ `;
+ return r?.n || 0;
+ } catch {
+ return 0;
+ }
+}
+
+// GET /api/agents/:id/solana/networth — public read: the agent's net-worth "look"
+// (presence tier, aura, confidence, regalia marks) derived entirely from real
+// chain reads + real DB counts, plus the owner's reactivity preferences.
+// PUT /api/agents/:id/solana/networth — owner-only: persist the reactivity prefs
+// (CSRF-gated). Visitors render the agent exactly as the owner configured it.
+async function handleNetWorth(req, res, id) {
+ if (cors(req, res, { methods: 'GET,PUT,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'PUT'])) return;
+
+ const [row] = await sql`SELECT id, user_id, meta FROM agent_identities WHERE id = ${id} AND deleted_at IS NULL`;
+ if (!row) return error(res, 404, 'not_found', 'agent not found');
+
+ const auth = await resolveAuth(req);
+ const isOwner = !!(auth && row.user_id === auth.userId);
+ const address = row.meta?.solana_address || null;
+ const hubUrl = `/agent/${id}/wallet`;
+
+ if (req.method === 'PUT') {
+ // Only the owner shapes how their agent presents itself; a forged change
+ // could force a flex the owner opted out of, so require CSRF.
+ if (!isOwner) return error(res, auth ? 403 : 401, auth ? 'forbidden' : 'unauthorized', auth ? 'not your agent' : 'sign in required');
+ if (!(await requireCsrf(req, res, auth.userId))) return;
+ let body;
+ try {
+ body = await readJson(req);
+ } catch (e) {
+ return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body');
+ }
+ const prev = normalizePrefs(row.meta?.networth_look);
+ const next = normalizePrefs({
+ reactivity: 'reactivity' in body ? body.reactivity : prev.reactivity,
+ signals: { ...prev.signals, ...(body.signals && typeof body.signals === 'object' ? body.signals : {}) },
+ });
+ next.updated_at = new Date().toISOString();
+ const meta = { ...(row.meta || {}), networth_look: next };
+ await sql`UPDATE agent_identities SET meta = ${JSON.stringify(meta)}::jsonb WHERE id = ${id}`;
+ logAudit({ userId: auth.userId, action: 'networth.prefs_update', resourceId: id, meta: { prev, next }, req });
+ return json(res, 200, { data: { prefs: next, is_owner: true } });
+ }
+
+ const rl = await limits.walletRead(isOwner ? auth.userId : clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const prefs = normalizePrefs(row.meta?.networth_look);
+ const forkCount = await forkCountFor(id);
+
+ // No wallet yet (provisioning): calm baseline look, honest about state. The
+ // agent still reads as itself — never poor-shamed, never faked.
+ if (!address) {
+ const look = computeLook({ usd: 0, forkCount });
+ return json(res, 200, {
+ data: {
+ agent_id: id, address: null, network: 'mainnet', provisioning: true,
+ portfolio: { usd: 0, sol: 0, three: null, usdc: 0, token_count: 0, top: [] },
+ reputation: { fork_count: forkCount },
+ tier: look.tier, look, marks: computeMarks({ usd: 0, forkCount }, { hubUrl }),
+ prefs, is_owner: isOwner, hub_url: hubUrl,
+ },
+ });
+ }
+
+ let balances = null;
+ try {
+ balances = await getBalances({ chain: 'solana', address });
+ } catch (e) {
+ // Hold-last-state contract: when the chain read is briefly unavailable we
+ // return a typed error so the client keeps the agent's last real look
+ // rather than snapping it to a fake baseline.
+ console.warn(`[agents/networth] balance read failed agentId=${id} ${e?.message}`);
+ return error(res, 502, 'rpc_error', 'could not read the wallet right now — holding last state');
+ }
+
+ const usd = walletUsdTotal(balances);
+ const sol = balances?.native?.amount || 0;
+ const tokens = balances?.tokens || [];
+ const threeTok = tokens.find((t) => t.mint === THREE_MINT) || null;
+ const usdcTok = tokens.find((t) => t.symbol === 'USDC');
+ const top = tokens.slice(0, 5).map((t) => ({ symbol: t.symbol, mint: t.mint, usd: t.usd || 0, amount: t.amount || 0 }));
+
+ const state = {
+ usd,
+ threeUsd: threeTok?.usd || 0,
+ threeAmount: threeTok?.amount || 0,
+ forkCount,
+ };
+ const look = computeLook(state);
+ const marks = computeMarks(state, { hubUrl });
+
+ return json(res, 200, {
+ data: {
+ agent_id: id,
+ address,
+ network: 'mainnet',
+ portfolio: {
+ usd,
+ sol,
+ sol_usd: balances?.native?.usd || 0,
+ three: threeTok ? { amount: threeTok.amount, usd: threeTok.usd || 0, price: threeTok.price || 0 } : null,
+ usdc: usdcTok?.usd || 0,
+ token_count: tokens.length,
+ top,
+ },
+ reputation: { fork_count: forkCount },
+ tier: look.tier,
+ look,
+ marks,
+ prefs,
+ is_owner: isOwner,
+ hub_url: hubUrl,
+ updated_at: new Date().toISOString(),
+ },
+ });
+}
+
// ── dispatcher ────────────────────────────────────────────────────────────────
export default async function handler(req, res, id, action) {
@@ -1345,6 +1479,7 @@ export default async function handler(req, res, id, action) {
if (action === 'withdraw') return handleWithdraw(req, res, id);
if (action === 'vanity') return handleVanity(req, res, id);
if (action === 'holdings') return handleHoldings(req, res, id);
+ if (action === 'networth') return handleNetWorth(req, res, id);
if (action === 'custody') return handleCustody(req, res, id);
if (action === 'limits') return handleLimits(req, res, id);
if (action === 'trade') {
diff --git a/data/changelog.json b/data/changelog.json
index 3e74e3482..dab1bb311 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,26 @@
{
"$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": "Feature: carry your agent and set it down anywhere in the room in IRL AR",
+ "summary": "On the IRL page your agent used to hover at a fixed distance in front of the camera — you couldn't choose where it stood. New 'Move here' control: turn on Camera AR, tap Move here, and a soft ring tracks the floor under your aim. Tap to set your agent down on that exact spot — the couch, a corner, the middle of the room — and it eases into place and turns to face you. The agent then stays anchored where you put it as you look around: pan away and it's gone, pan back and there it is. This is the first half of placing agents in the real world the way you'd expect; cross-device discovery (a friend finding it on their own phone) is coming next.",
+ "tags": ["feature"],
+ "link": "/irl"
+ },
+ {
+ "date": "2026-06-23",
+ "title": "Improvement: Animation Studio recovers your unsaved animation after a refresh or closed tab",
+ "summary": "Posing a figure and keyframing a timeline in the Animation Studio is real work — and until now none of it touched your account until you pressed Save, so an accidental tab close or browser refresh could wipe it. The Studio now quietly keeps a local backup of your in-progress animation as you work, and warns you before you leave with unsaved keyframes. Come back later and it offers the recovered timeline right where you left off — 'Recovered your unsaved animation — 6 keyframes.' Saving to your account or opening a saved clip clears the backup, and an explicit shared link still wins. No work lost between sessions.",
+ "tags": ["improvement", "feature"],
+ "link": "/pose"
+ },
+ {
+ "date": "2026-06-23",
+ "title": "Improvement: every server error now hands you a support reference code",
+ "summary": "When something fails on our side, the response no longer just says 'something went wrong' — it now carries a short reference code (e.g. 'quote ref a1b2c3d4 to support'). That same code is attached to the exact server log line, our error tracker, and the ops alert that pages the team, so one code maps to one incident. This was already true for most API responses; we extended it to the remaining surfaces that previously failed silently — the RSS announcements feed, sitemaps, the MCP payment flow, on-chain permission checks, and the Solana RPC proxy — so any failure you hit is traceable. Nothing changes when things work; this only makes the rare error far faster to diagnose.",
+ "tags": ["improvement", "infra"]
+ },
{
"date": "2026-06-23",
"title": "Improvement: Base USDC payments confirm even when an RPC provider is flaky",
diff --git a/public/changelog.json b/public/changelog.json
index 8b33b6e5e..b01bc018f 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,11 +1,21 @@
{
- "generated_at": "2026-06-23T02:37:56.000Z",
+ "generated_at": "2026-06-23T02:46:03.269Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
"url": "https://three.ws"
},
"entries": [
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "Feature: carry your agent and set it down anywhere in the room in IRL AR",
+ "summary": "On the IRL page your agent used to hover at a fixed distance in front of the camera — you couldn't choose where it stood. New 'Move here' control: turn on Camera AR, tap Move here, and a soft ring tracks the floor under your aim. Tap to set your agent down on that exact spot — the couch, a corner, the middle of the room — and it eases into place and turns to face you. The agent then stays anchored where you put it as you look around: pan away and it's gone, pan back and there it is. This is the first half of placing agents in the real world the way you'd expect; cross-device discovery (a friend finding it on their own phone) is coming next.",
+ "link": "/irl",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-23",
"type": "update",
@@ -36,6 +46,17 @@
"fix"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "Improvement: Animation Studio recovers your unsaved animation after a refresh or closed tab",
+ "summary": "Posing a figure and keyframing a timeline in the Animation Studio is real work — and until now none of it touched your account until you pressed Save, so an accidental tab close or browser refresh could wipe it. The Studio now quietly keeps a local backup of your in-progress animation as you work, and warns you before you leave with unsaved keyframes. Come back later and it offers the recovered timeline right where you left off — 'Recovered your unsaved animation — 6 keyframes.' Saving to your account or opening a saved clip clears the backup, and an explicit shared link still wins. No work lost between sessions.",
+ "link": "/pose",
+ "tags": [
+ "improvement",
+ "feature"
+ ]
+ },
{
"date": "2026-06-23",
"type": "update",
@@ -47,6 +68,17 @@
"infra"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "Improvement: every server error now hands you a support reference code",
+ "summary": "When something fails on our side, the response no longer just says 'something went wrong' — it now carries a short reference code (e.g. 'quote ref a1b2c3d4 to support'). That same code is attached to the exact server log line, our error tracker, and the ops alert that pages the team, so one code maps to one incident. This was already true for most API responses; we extended it to the remaining surfaces that previously failed silently — the RSS announcements feed, sitemaps, the MCP payment flow, on-chain permission checks, and the Solana RPC proxy — so any failure you hit is traceable. Nothing changes when things work; this only makes the rare error far faster to diagnose.",
+ "link": null,
+ "tags": [
+ "improvement",
+ "infra"
+ ]
+ },
{
"date": "2026-06-22",
"type": "launch",
diff --git a/public/changelog.xml b/public/changelog.xml
index bfb7dc987..f8aebd9ef 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -6,6 +6,14 @@
<atom:link href="https://three.ws/changelog.xml" rel="self" type="application/rss+xml"/>
<description>What's new on three.ws — features, improvements, and releases, newest first.</description>
<language>en</language>
+ <item>
+ <title>Feature: carry your agent and set it down anywhere in the room in IRL AR</title>
+ <link>https://three.ws/irl</link>
+ <guid isPermaLink="false">2026-06-23:Feature: carry your agent and set it down anywhere in the room in IRL AR</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>On the IRL page your agent used to hover at a fixed distance in front of the camera — you couldn't choose where it stood. New 'Move here' control: turn on Camera AR, tap Move here, and a soft ring tracks the floor under your aim. Tap to set your agent down on that exact spot — the couch, a corner, the middle of the room — and it eases into place and turns to face you. The agent then stays anchored where you put it as you look around: pan away and it's gone, pan back and there it is. This is the first half of placing agents in the real world the way you'd expect; cross-device discovery (a friend finding it on their own phone) is coming next.</description>
+ </item>
<item>
<title>Fix: avatars look right in iOS AR, not collapsed and distorted</title>
<link>https://three.ws/changelog</link>
@@ -30,6 +38,14 @@
<category>fix</category>
<description>Swept the API for places where a slow or flaky upstream could hang a request until it was force-killed, or a database missing a recent table could error a whole page, and closed them. The /go bounty board now provisions its own database tables, so it loads everywhere instead of erroring where they were absent. The pump trending and search feeds fall back to the last good list (or an empty one) when pump.fun returns a malformed response, rather than failing the page. And a batch of backend lookups — the live SOL price, Jupiter/Birdeye/CoinGecko market data, portfolio price charts, token-gated scene access checks, IPFS pinning, voice synthesis, and the embedded-agent AI fallback chain — now bound every third-party call with a timeout, so a stalled service returns a clean result quickly instead of holding the request open until it's killed.</description>
</item>
+ <item>
+ <title>Improvement: Animation Studio recovers your unsaved animation after a refresh or closed tab</title>
+ <link>https://three.ws/pose</link>
+ <guid isPermaLink="false">2026-06-23:Improvement: Animation Studio recovers your unsaved animation after a refresh or closed tab</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>Posing a figure and keyframing a timeline in the Animation Studio is real work — and until now none of it touched your account until you pressed Save, so an accidental tab close or browser refresh could wipe it. The Studio now quietly keeps a local backup of your in-progress animation as you work, and warns you before you leave with unsaved keyframes. Come back later and it offers the recovered timeline right where you left off — 'Recovered your unsaved animation — 6 keyframes.' Saving to your account or opening a saved clip clears the backup, and an explicit shared link still wins. No work lost between sessions.</description>
+ </item>
<item>
<title>Improvement: Base USDC payments confirm even when an RPC provider is flaky</title>
<link>https://three.ws/changelog</link>
@@ -38,6 +54,14 @@
<category>improvement</category>
<description>When you pay for a skill or asset in USDC on Base, the platform double-checks your payment landed on-chain before unlocking it. That check used to read from a single blockchain provider — so if that one provider was briefly slow or rate-limited, a payment that had genuinely gone through could look stuck as 'pending' until you retried. It now reads through the same multi-provider failover the rest of the platform already uses: if one provider is down it automatically tries the next, and a momentary outage degrades to a safe, retryable state instead of stranding a confirmed payment. Your funds were never at risk either way; this makes the confirmation itself resilient.</description>
</item>
+ <item>
+ <title>Improvement: every server error now hands you a support reference code</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-23:Improvement: every server error now hands you a support reference code</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>When something fails on our side, the response no longer just says 'something went wrong' — it now carries a short reference code (e.g. 'quote ref a1b2c3d4 to support'). That same code is attached to the exact server log line, our error tracker, and the ops alert that pages the team, so one code maps to one incident. This was already true for most API responses; we extended it to the remaining surfaces that previously failed silently — the RSS announcements feed, sitemaps, the MCP payment flow, on-chain permission checks, and the Solana RPC proxy — so any failure you hit is traceable. Nothing changes when things work; this only makes the rare error far faster to diagnose.</description>
+ </item>
<item>
<title>Docs · Agent Reputation</title>
<link>https://three.ws/docs/agent-reputation</link>
diff --git a/public/features.json b/public/features.json
index 71b48db0f..e362218c4 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-23T02:37:55.717Z",
+ "generated_at": "2026-06-23T02:46:03.240Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/feature-tour/director.js b/src/feature-tour/director.js
index 0eeb00310..d62e650aa 100644
--- a/src/feature-tour/director.js
+++ b/src/feature-tour/director.js
@@ -67,6 +67,7 @@ export class TourDirector {
// button / ?tour=start). `track` chooses Quick vs Full; voice/speed default to
// the visitor's remembered preferences. Navigates to stop 0's page if needed.
async start(track) {
+ this._showLoading();
await this._ensureCurriculum();
const prefs = readResume();
this.track = track || 'full';
@@ -100,6 +101,7 @@ export class TourDirector {
async resume() {
const state = readState();
if (!state.active) return;
+ this._showLoading();
await this._ensureCurriculum();
this.paused = state.paused;
this.muted = state.muted;
@@ -193,6 +195,7 @@ export class TourDirector {
this.panel.setSpeed(this.speed);
this.panel.setVoice(this.voice);
document.addEventListener('keydown', this._onKey);
+ this._hideLoading();
}
// ── Running a stop ────────────────────────────────────────────────────────
@@ -568,6 +571,36 @@ export class TourDirector {
this._doneCard = card;
}
+ // A lightweight, honest loading state shown while the curriculum manifest and
+ // the guide GLB stream in — no fake progress bar, just a live "preparing" cue
+ // that clears the moment the real assets are mounted (or the load gives up).
+ _showLoading() {
+ if (this._loadingEl) return;
+ ensureLoadingStyles();
+ const el = document.createElement('div');
+ el.className = 'tws-tour-loading';
+ el.setAttribute('role', 'status');
+ el.setAttribute('aria-live', 'polite');
+ el.innerHTML = `
+ <div class="tws-tour-loading__inner">
+ <div class="tws-tour-loading__orb" aria-hidden="true"></div>
+ <div class="tws-tour-loading__label">Waking your guide…</div>
+ </div>`;
+ document.body.appendChild(el);
+ requestAnimationFrame(() => el.classList.add('is-in'));
+ this._loadingEl = el;
+ }
+
+ _hideLoading() {
+ const el = this._loadingEl;
+ if (!el) return;
+ this._loadingEl = null;
+ el.classList.remove('is-in');
+ const drop = () => el.remove();
+ el.addEventListener('transitionend', drop, { once: true });
+ this._loadingDrop = setTimeout(drop, 600); // fallback if transitionend never fires
+ }
+
// ── Teardown ──────────────────────────────────────────────────────────────
exit() {
this._runToken++;
@@ -586,6 +619,9 @@ export class TourDirector {
this.controls?.dispose();
this.panel?.dispose();
this._doneCard?.remove();
+ clearTimeout(this._loadingDrop);
+ this._loadingEl?.remove();
+ this._loadingEl = null;
this._restoreCompanion();
this.mounted = false;
}
@@ -758,3 +794,20 @@ function ensureDoneStyles() {
`;
document.head.appendChild(style);
}
+
+let _loadingStyles = false;
+function ensureLoadingStyles() {
+ if (_loadingStyles) return;
+ _loadingStyles = true;
+ const style = document.createElement('style');
+ style.textContent = `
+.tws-tour-loading{position:fixed;inset:0;z-index:2147483400;display:grid;place-items:center;background:rgba(6,8,12,.55);backdrop-filter:blur(5px);opacity:0;transition:opacity .3s ease;font-family:system-ui,-apple-system,'Segoe UI',sans-serif}
+.tws-tour-loading.is-in{opacity:1}
+.tws-tour-loading__inner{display:flex;flex-direction:column;align-items:center;gap:16px}
+.tws-tour-loading__orb{width:54px;height:54px;border-radius:50%;background:conic-gradient(from 0deg,#7aa2ff,#9d7bff,#7aa2ff);-webkit-mask:radial-gradient(farthest-side,transparent calc(100% - 6px),#000 0);mask:radial-gradient(farthest-side,transparent calc(100% - 6px),#000 0);animation:tws-tour-spin 1s linear infinite}
+.tws-tour-loading__label{color:#cdd5e6;font-size:14px;font-weight:600;letter-spacing:.01em}
+@keyframes tws-tour-spin{to{transform:rotate(1turn)}}
+@media (prefers-reduced-motion:reduce){.tws-tour-loading{transition:none}.tws-tour-loading__orb{animation-duration:2.4s}}
+`;
+ document.head.appendChild(style);
+}
diff --git a/src/irl.js b/src/irl.js
index 6fb04baaa..2aac002e3 100644
--- a/src/irl.js
+++ b/src/irl.js
@@ -148,7 +148,8 @@ const subtitleEl = $('irl-subtitle');
// three states so a brand-new user is never left guessing what to tap next.
const SUBTITLE = {
cameraOff: 'Turn on Camera AR, then tap Pin here to anchor your agent in real space.',
- aiming: 'Aim at the spot you want, then tap Pin here to anchor your agent.',
+ aiming: 'Tap Move here to set your agent on the floor, then Pin here to anchor it.',
+ placing: 'Aim the ring at the floor and tap to set your agent down — then Pin here.',
pinned: 'Your agent is anchored here. Tap Pin here again to release it.',
};
function setSubtitle(text) { if (subtitleEl) subtitleEl.textContent = text; }
@@ -162,6 +163,7 @@ const clearBtn = $('irl-clear-btn');
const pickerEl = $('irl-picker');
const avatarBtn = $('irl-avatar-btn');
const lockBtn = $('irl-lock-btn');
+const carryBtn = $('irl-carry-btn'); // "Move here" — carry the agent and set it on the floor
const anchorBtn = $('irl-anchor-btn'); // WebXR "Place on floor" — revealed only when supported
const xrOverlay = $('irl-xr-overlay'); // WebXR dom-overlay root (in-session hint + exit + error)
const xrBarEl = $('irl-xr-bar'); // hint+exit pill; .is-anchored reveals the ✓ confirm
@@ -279,6 +281,30 @@ rayPlane.rotation.x = -Math.PI / 2;
rayPlane.position.y = 0.005;
scene.add(rayPlane);
+// Carry-and-place reticle — a soft teal ground ring that tracks where the screen
+// centre meets the floor while "Move here" is armed, so you can aim a real spot in
+// the room and set your agent down there (the gesture the fixed camera-offset never
+// allowed). Hidden until carry mode reveals it; pulses on a successful drop.
+const carryReticle = new Group();
+{
+ const ring = new Mesh(
+ new TorusGeometry(0.28, 0.022, 10, 44),
+ new MeshBasicMaterial({ color: 0x34d399, transparent: true, opacity: 0.9, depthTest: false }),
+ );
+ ring.rotation.x = -Math.PI / 2;
+ ring.renderOrder = 10;
+ const dot = new Mesh(
+ new CircleGeometry(0.05, 24),
+ new MeshBasicMaterial({ color: 0x34d399, transparent: true, opacity: 0.55, depthTest: false }),
+ );
+ dot.rotation.x = -Math.PI / 2;
+ dot.renderOrder = 10;
+ carryReticle.add(ring, dot);
+}
+carryReticle.position.y = 0.012;
+carryReticle.visible = false;
+scene.add(carryReticle);
+
// ── Camera ────────────────────────────────────────────────────────────────
// near = 0.02 m: held one-handed, a virtual agent brought close to inspect can put
// its near face inside the clip cone and vanish (and so dodge the inspect tap). 2 cm
@@ -470,6 +496,8 @@ function disableAR() {
arFrozenCamPos = null;
arFrozenCamLook = null;
gyroLockCamPos = null;
+ if (carryModeActive) setCarryMode(false); // carry only makes sense with the camera on
+ _carryActive = false;
arTrackW = 0;
arTrackH = 0;
setStatus('Camera off');
@@ -498,6 +526,12 @@ if (!navigator.mediaDevices?.getUserMedia) {
// ── Placed objects ────────────────────────────────────────────────────────
let placeModeActive = false;
let selectedType = 'orb';
+// Carry-and-place: while armed, a floor tap sets the agent down at that world
+// point and it eases there (no teleport). _carryTarget/_carryActive drive the glide
+// in tick(); the gyro world-lock then holds the agent at the chosen spot.
+let carryModeActive = false;
+let _carryActive = false;
+const _carryTarget = new Vector3();
const placedObjects = []; // { mesh, spawnT, type }
// ── Session persistence (localStorage) ───────────────────────────────────
@@ -639,6 +673,7 @@ document.querySelector('.irl-obj-btn[data-type="orb"]')?.classList.add('active')
placeBtn.addEventListener('click', () => {
placeModeActive = !placeModeActive;
+ if (placeModeActive) setCarryMode(false); // the two floor-tap modes are exclusive
placeBtn.setAttribute('aria-pressed', String(placeModeActive));
placeBtn.classList.toggle('is-active', placeModeActive);
pickerEl.hidden = !placeModeActive;
@@ -651,6 +686,53 @@ placeBtn.addEventListener('click', () => {
}
});
+// ── Carry-and-place ("Move here") ─────────────────────────────────────────────
+// Arm a floor-aim reticle; a tap sets the agent down at that real-world spot. This
+// is what makes "carry my agent across the room and put it on the couch" possible —
+// before this the agent was frozen 3.6 m in front of the camera (CAM_OFFSET).
+function setCarryMode(on) {
+ carryModeActive = on && arActive;
+ carryBtn?.setAttribute('aria-pressed', String(carryModeActive));
+ carryBtn?.classList.toggle('is-active', carryModeActive);
+ canvas.style.cursor = carryModeActive ? 'crosshair' : '';
+ if (carryModeActive) {
+ if (placeModeActive) placeBtn.click(); // exclusive with the object-drop mode
+ setSubtitle(SUBTITLE.placing);
+ setStatus('Aim the ring at the floor, then tap to set your agent down');
+ } else {
+ carryReticle.visible = false;
+ setSubtitle(avatarLocked ? SUBTITLE.pinned : SUBTITLE.aiming);
+ if (!placeModeActive) setStatus(null);
+ }
+}
+
+// Set the agent down at a chosen floor point and turn it to face the viewer, so a
+// freshly placed agent looks at you rather than away. The glide + final snap run in
+// tick() via _carryActive; the gyro world-lock holds the spot once you Pin here.
+function placeAvatarAt(point) {
+ _carryTarget.set(point.x, 0, point.z);
+ _carryActive = true;
+ const dx = camera.position.x - point.x, dz = camera.position.z - point.z;
+ if (dx * dx + dz * dz > 1e-4) avatarYaw = Math.atan2(dx, dz);
+ carryReticle.scale.setScalar(1.4); // confirm pulse — eased back to rest in tick()
+ setStatus('Agent set down — tap Pin here to anchor it in the room');
+ _saveSession();
+}
+
+if (carryBtn) {
+ carryBtn.addEventListener('click', async () => {
+ if (!arActive) {
+ setStatus('Turn on Camera AR first, then move your agent into the room.', { warn: true });
+ return;
+ }
+ // Arming carry requires the world-lock: only the locked/gyro camera tracks the
+ // room as you pan, so the floor reticle lands on the real floor and the agent
+ // stays put where you set it. Engage it first if you haven't pinned yet.
+ if (!carryModeActive && !avatarLocked) await setLocked(true);
+ setCarryMode(!carryModeActive);
+ });
+}
+
clearBtn.addEventListener('click', () => {
for (const obj of placedObjects) scene.remove(obj.mesh);
placedObjects.length = 0;
@@ -688,6 +770,14 @@ canvas.addEventListener('pointerup', e => {
);
raycaster.setFromCamera(pointerNDC, camera);
+ if (carryModeActive) {
+ // ── Carry mode: set the agent down on the floor where you tapped ──
+ const hits = raycaster.intersectObject(rayPlane);
+ if (!hits.length) return;
+ placeAvatarAt(hits[0].point);
+ return;
+ }
+
if (placeModeActive) {
// ── Place mode: drop an object on the ground ─────────────────────
const hits = raycaster.intersectObject(rayPlane);
@@ -6095,6 +6185,40 @@ function tick() {
avatarLean += (targetLean - avatarLean) * LEAN_LERP;
if (avatar) avatar.rotation.x = avatarLean;
+ // Carry glide — ease a set-down agent to its chosen floor spot (works locked or
+ // not). Any joystick/keys input cancels it so manual control always wins.
+ if (_carryActive) {
+ if (mag > 0.01) {
+ _carryActive = false;
+ } else {
+ avatarRig.position.x += (_carryTarget.x - avatarRig.position.x) * 0.18;
+ avatarRig.position.z += (_carryTarget.z - avatarRig.position.z) * 0.18;
+ avatarRig.quaternion.setFromAxisAngle(upY, avatarYaw);
+ if (Math.hypot(_carryTarget.x - avatarRig.position.x, _carryTarget.z - avatarRig.position.z) < 0.01) {
+ avatarRig.position.x = _carryTarget.x;
+ avatarRig.position.z = _carryTarget.z;
+ _carryActive = false;
+ }
+ }
+ }
+
+ // Carry reticle — track the floor point under the screen centre while armed, so
+ // you can aim a real spot before tapping. Eases its confirm pulse back to rest.
+ if (carryModeActive) {
+ pointerNDC.set(0, 0);
+ raycaster.setFromCamera(pointerNDC, camera);
+ const rHits = raycaster.intersectObject(rayPlane);
+ if (rHits.length) {
+ carryReticle.position.set(rHits[0].point.x, 0.012, rHits[0].point.z);
+ carryReticle.visible = true;
+ } else {
+ carryReticle.visible = false;
+ }
+ carryReticle.scale.setScalar(carryReticle.scale.x + (1 - carryReticle.scale.x) * 0.15);
+ } else if (carryReticle.visible) {
+ carryReticle.visible = false;
+ }
+
// Camera ─────────────────────────────────────────────────────────────────
if (gpsModeActive && avatarLocked && arActive) {
// GPS mode (iOS world-lock, A4). Viewer-centric frame: the user is always
diff --git a/src/pose-library.js b/src/pose-library.js
index 3df34b067..64ffc7c2d 100644
--- a/src/pose-library.js
+++ b/src/pose-library.js
@@ -194,6 +194,7 @@ export class PoseLibrary {
avatar_id: avatarId || undefined,
};
const saved = await this._persist(meta, { asCopy });
+ this.api.onSaved?.();
overlay.remove();
this.api.setStatus(`Saved “${saved.name}” to your account.`);
} catch (err) {
diff --git a/src/pose-studio.js b/src/pose-studio.js
index 28607b012..c26e62fe9 100644
--- a/src/pose-studio.js
+++ b/src/pose-studio.js
@@ -1066,6 +1066,15 @@ function boot() {
// keyframes and plays the result; export bakes a THREE.AnimationClip.
timeline = setupTimeline();
+ // ── Crash recovery & unsaved-work guard ──────────────────────────────────
+ // Posing and keyframing never touch the account until the user explicitly
+ // Saves, so a refresh or accidental tab close would lose in-progress work.
+ // We snapshot the timeline document to localStorage on a light interval and
+ // warn before unload while the current state differs from the last point it
+ // was persisted (an account save, or opening a saved clip). On the next boot
+ // the draft is offered back — unless an explicit deep-link (?anim=) wins.
+ const autosave = setupAutosave();
+
// ── Animation preset library ─────────────────────────────────────────────
// A curated gallery of ready-to-apply motion clips. Picking one retargets it
// onto the loaded rig and plays it live in this same viewport, then offers an
@@ -1603,10 +1612,108 @@ function boot() {
};
}
+ // Local crash-recovery for in-progress timeline work. Returns null when the
+ // page has no timeline (the studio markup is absent) so callers no-op safely.
+ function setupAutosave() {
+ if (!timeline) return null;
+ const DRAFT_KEY = 'pose-studio:draft:v2';
+ // savedBaseline = the document JSON at the last persisted point (account
+ // save or open). lastDraftJson tracks what we last wrote to localStorage so
+ // the interval skips redundant writes.
+ let savedBaseline = JSON.stringify(timeline.getDocument());
+ let lastDraftJson = null;
+
+ const currentJson = () => JSON.stringify(timeline.getDocument());
+
+ const readDraft = () => {
+ try {
+ return JSON.parse(localStorage.getItem(DRAFT_KEY) || 'null');
+ } catch {
+ return null;
+ }
+ };
+ const clearDraft = () => {
+ try {
+ localStorage.removeItem(DRAFT_KEY);
+ } catch {
+ /* storage blocked — nothing to clear */
+ }
+ };
+
+ function hasUnsavedWork() {
+ const doc = timeline.getDocument();
+ return doc.keyframes.length > 0 && currentJson() !== savedBaseline;
+ }
+
+ function persistDraft() {
+ const cur = currentJson();
+ if (cur === lastDraftJson) return;
+ lastDraftJson = cur;
+ const doc = timeline.getDocument();
+ // Only stash genuine, not-yet-saved work — never an empty doc or a
+ // document that already matches the persisted baseline.
+ if (!doc.keyframes.length || cur === savedBaseline) {
+ clearDraft();
+ return;
+ }
+ try {
+ localStorage.setItem(
+ DRAFT_KEY,
+ JSON.stringify({ doc, savedAt: Date.now(), avatarId: state.avatar?.id || null }),
+ );
+ } catch {
+ /* quota / private mode — recovery simply unavailable this session */
+ }
+ }
+
+ // Called when the document reaches a persisted state (saved to the account
+ // or freshly opened from it): reset the baseline and drop the local draft.
+ function markSaved() {
+ savedBaseline = currentJson();
+ lastDraftJson = null;
+ clearDraft();
+ }
+
+ // Offer the previous session's unsaved draft back. Restored work stays
+ // "unsaved" (it isn't in the account yet), so the unload guard keeps
+ // protecting it until the user Saves.
+ function tryRestore() {
+ const saved = readDraft();
+ const count = saved?.doc?.keyframes?.length || 0;
+ if (!count) return false;
+ timeline.loadDocument(saved.doc);
+ lastDraftJson = currentJson();
+ const when = saved.savedAt ? new Date(saved.savedAt).toLocaleTimeString() : 'a previous session';
+ setStatus(
+ `Recovered your unsaved animation — ${count} keyframe${count === 1 ? '' : 's'} from ${when}. Save it to keep it.`,
+ );
+ return true;
+ }
+
+ const interval = setInterval(persistDraft, 1500);
+ document.addEventListener('visibilitychange', () => {
+ if (document.hidden) persistDraft();
+ });
+ window.addEventListener('beforeunload', (ev) => {
+ persistDraft();
+ if (hasUnsavedWork()) {
+ ev.preventDefault();
+ ev.returnValue = '';
+ }
+ });
+ window.addEventListener('pagehide', () => clearInterval(interval));
+
+ return { markSaved, tryRestore, hasUnsavedWork };
+ }
+
// ── Account: save + "My animations" library ──────────────────────────────
const library = new PoseLibrary({
getDocument: () => timeline.getDocument(),
- loadDocument: (d) => timeline.loadDocument(d),
+ loadDocument: (d) => {
+ timeline.loadDocument(d);
+ autosave?.markSaved();
+ },
+ onSaved: () => autosave?.markSaved(),
serializeClip: () => timeline.serialize(),
bakeArtifact: () => timeline.bakeArtifact(),
captureThumbnail: () => timeline.captureThumbnail(),
@@ -1625,6 +1732,10 @@ function boot() {
const requestedAvatar = _params.get('avatar');
const requestedAnim = _params.get('anim');
+ // An explicit ?anim= deep-link opens a specific saved clip and wins over any
+ // recovered draft; otherwise we offer back last session's unsaved work.
+ const recovered = !requestedAnim && autosave?.tryRestore();
+
if (requestedAvatar) {
loadAvatarById(requestedAvatar).catch((err) => {
setStatus(`${err.message} Showing the mannequin instead.`, 'error');
@@ -1637,7 +1748,7 @@ function boot() {
}
});
} else {
- setStatus('Ready. Click a body part to pose, or load an avatar.');
+ if (!recovered) setStatus('Ready. Click a body part to pose, or load an avatar.');
if (requestedAnim) {
library.openById(requestedAnim).catch((err) => {
setStatus(`Could not load animation: ${err?.message || 'unknown error'}`, 'error');
diff --git a/src/shared/wallet-aura.js b/src/shared/wallet-aura.js
new file mode 100644
index 000000000..66b277d6f
--- /dev/null
+++ b/src/shared/wallet-aura.js
@@ -0,0 +1,440 @@
+/**
+ * The Net-Worth-Reactive Avatar — visual layer.
+ *
+ * Renders a tasteful, real-data-driven treatment AROUND an agent's 3D avatar so
+ * a funded agent visibly *looks* funded. The look is a pure function of the
+ * agent's real wallet state (see wallet-networth.js): a tiered aura/rim-glow, an
+ * accent palette informed by the real asset mix, an optional GPU-cheap particle
+ * field, and a one-shot flourish fired only by a REAL confirmed on-chain inflow.
+ *
+ * Why only three.ws can do this: the glow is welded to a real, self-custodial
+ * wallet bound to a rigged, ownable 3D agent. Change the wallet, the body
+ * changes — no random, no timer-driven decoration.
+ *
+ * Craft:
+ * - The aura wraps the avatar container (works over <model-viewer> and the
+ * galaxy alike) without touching the GLB, so it is consistent on every
+ * surface and never blocks model interaction (pointer-events: none).
+ * - LOD: `card` is CSS-only (cheap for dense grids); `full` adds a capped,
+ * visibility-gated canvas particle field. Off-screen auras pause their rAF.
+ * - `prefers-reduced-motion`: a static, richer treatment instead of animation.
+ * - Whale balances are capped upstream so the effect never eye-sears.
+ */
+
+import {
+ fetchWalletState, computeWalletVisual, formatNetWorth,
+} from './wallet-networth.js';
+
+const STYLE_ID = 'tws-wallet-aura-styles';
+const REDUCED_MOTION =
+ typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
+
+function ensureStyles() {
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;
+ const style = document.createElement('style');
+ style.id = STYLE_ID;
+ style.textContent = `
+.wa-layer{position:absolute;inset:0;pointer-events:none;z-index:1;border-radius:inherit;overflow:hidden;
+ opacity:0;transition:opacity var(--duration-base,.4s) var(--ease-standard,cubic-bezier(.4,0,.2,1));
+ --wa-accent:var(--wallet-accent,#c4b5fd);--wa-glow:var(--wallet-glow,rgba(139,92,246,.45));--wa-i:0;}
+.wa-layer[data-ready="true"]{opacity:1;}
+/* Radial bloom behind/around the avatar — intensity scales with net worth. */
+.wa-bloom{position:absolute;inset:-12%;border-radius:50%;
+ background:radial-gradient(circle at 50% 62%,var(--wa-glow) 0%,transparent 62%);
+ opacity:calc(.25 + var(--wa-i) * .75);
+ filter:blur(calc(8px + var(--wa-i) * 26px));
+ transform:scale(calc(.7 + var(--wa-i) * .45));
+ transition:opacity .5s var(--ease-standard,ease),transform .6s var(--ease-standard,ease),filter .5s ease;
+ will-change:transform,opacity;}
+/* A crisp rim ring that reads even at card size. */
+.wa-rim{position:absolute;inset:6%;border-radius:50%;
+ box-shadow:0 0 0 1px var(--wa-accent), 0 0 calc(10px + var(--wa-i) * 40px) var(--wa-glow);
+ opacity:calc(.18 + var(--wa-i) * .62);
+ transition:opacity .5s var(--ease-standard,ease),box-shadow .5s ease;}
+/* Slow conic shimmer, only at higher tiers and only when motion is allowed. */
+.wa-shimmer{position:absolute;inset:-30%;border-radius:50%;mix-blend-mode:screen;opacity:0;
+ background:conic-gradient(from 0deg,transparent 0deg,var(--wa-glow) 40deg,transparent 120deg,
+ transparent 240deg,var(--wa-glow) 300deg,transparent 360deg);
+ will-change:transform;}
+.wa-layer[data-motion="true"][data-level-hi="true"] .wa-shimmer{opacity:calc(var(--wa-i) * .5);
+ animation:wa-spin 14s linear infinite;}
+@keyframes wa-spin{to{transform:rotate(360deg);}}
+.wa-canvas{position:absolute;inset:0;width:100%;height:100%;pointer-events:none;}
+/* One-shot flourish ring on a real confirmed inflow. */
+.wa-flourish{position:absolute;left:50%;top:60%;width:30%;padding-bottom:30%;border-radius:50%;
+ transform:translate(-50%,-50%) scale(.2);opacity:0;border:2px solid var(--wa-accent);
+ box-shadow:0 0 30px var(--wa-glow);}
+.wa-layer[data-motion="true"] .wa-flourish.wa-go{animation:wa-burst 1.1s var(--ease-standard,ease) forwards;}
+@keyframes wa-burst{0%{transform:translate(-50%,-50%) scale(.2);opacity:0;}
+ 12%{opacity:.95;}100%{transform:translate(-50%,-50%) scale(2.4);opacity:0;}}
+/* Drawdown reads honestly: a brief, non-punitive cool dim — no strobing. */
+.wa-layer.wa-draw .wa-bloom{filter:grayscale(.4) blur(20px);opacity:.2;}
+/* Reduced-motion static-but-richer: stronger steady bloom, no shimmer/particles. */
+@media (prefers-reduced-motion: reduce){
+ .wa-bloom,.wa-rim{transition:none;}
+ .wa-layer .wa-shimmer{animation:none!important;}
+ .wa-layer .wa-flourish{display:none;}
+}
+/* Optional net-worth tier badge a surface can opt into. */
+.wa-badge{display:inline-flex;align-items:center;gap:6px;padding:3px 9px;border-radius:var(--radius-pill,999px);
+ font:700 10px/1 var(--font-mono,ui-monospace,monospace);letter-spacing:.04em;text-transform:uppercase;
+ color:var(--wa-accent);background:var(--wa-glow);border:1px solid var(--wa-accent);white-space:nowrap;}
+.wa-badge .wa-badge-dot{width:6px;height:6px;border-radius:50%;background:var(--wa-accent);
+ box-shadow:0 0 6px var(--wa-accent);}
+`;
+ (document.head || document.documentElement).appendChild(style);
+}
+
+/**
+ * Mount the aura layer into a container that holds an avatar (a <model-viewer>
+ * stage, a card thumb, etc.). The container is made position:relative if static.
+ *
+ * @param {HTMLElement} container
+ * @param {object} [opts]
+ * @param {'full'|'card'|'auto'} [opts.lod='auto']
+ * @returns {{ applyVisual(v), update(state), flourish(kind), destroy(), el }}
+ */
+export function mountWalletAura(container, opts = {}) {
+ if (!container) return null;
+ ensureStyles();
+
+ const cs = getComputedStyle(container);
+ if (cs.position === 'static') container.style.position = 'relative';
+
+ let lod = opts.lod || 'auto';
+ if (lod === 'auto') {
+ const w = container.clientWidth || 0;
+ lod = w >= 340 ? 'full' : 'card';
+ }
+
+ const layer = document.createElement('div');
+ layer.className = 'wa-layer';
+ layer.setAttribute('aria-hidden', 'true');
+ layer.dataset.motion = REDUCED_MOTION ? 'false' : 'true';
+ layer.innerHTML =
+ '<div class="wa-bloom"></div><div class="wa-shimmer"></div><div class="wa-rim"></div>' +
+ '<div class="wa-flourish"></div>';
+
+ const canvas = lod === 'full' && !REDUCED_MOTION ? document.createElement('canvas') : null;
+ if (canvas) { canvas.className = 'wa-canvas'; layer.appendChild(canvas); }
+
+ // Insert as the first child so it sits behind the model content.
+ container.insertBefore(layer, container.firstChild);
+
+ const particles = new ParticleField(canvas);
+ let visual = null;
+ let visible = true;
+
+ // Pause the particle rAF when the avatar scrolls off-screen — dense lists and
+ // the galaxy must not pay for auras nobody is looking at.
+ let io = null;
+ if (canvas && typeof IntersectionObserver === 'function') {
+ io = new IntersectionObserver((entries) => {
+ visible = entries.some((e) => e.isIntersecting);
+ if (visible) particles.start(); else particles.stop();
+ }, { threshold: 0.01 });
+ io.observe(container);
+ }
+
+ function applyVisual(v) {
+ visual = v;
+ layer.style.setProperty('--wa-accent', v.accent);
+ layer.style.setProperty('--wa-glow', v.glow);
+ layer.style.setProperty('--wa-i', v.intensity.toFixed(3));
+ layer.dataset.level = String(v.level);
+ layer.dataset.levelHi = v.level >= 3 ? 'true' : 'false';
+ layer.dataset.tier = v.tier;
+ layer.dataset.ready = v.dormant ? 'true' : 'true';
+ // Dormant stays present but whisper-quiet (a clean baseline, never absent).
+ if (v.dormant) layer.style.setProperty('--wa-i', '0.04');
+ particles.configure(v);
+ if (visible) particles.start();
+ }
+
+ async function update(stateOrAgent) {
+ const state = stateOrAgent && stateOrAgent.usdTotal !== undefined
+ ? stateOrAgent
+ : await fetchWalletState(stateOrAgent, { network: opts.network });
+ applyVisual(computeWalletVisual(state));
+ layer.__state = state;
+ return state;
+ }
+
+ function flourish(kind = 'inflow') {
+ if (REDUCED_MOTION) return;
+ if (kind === 'drawdown') {
+ layer.classList.add('wa-draw');
+ setTimeout(() => layer.classList.remove('wa-draw'), 900);
+ return;
+ }
+ const ring = layer.querySelector('.wa-flourish');
+ if (ring) {
+ ring.classList.remove('wa-go');
+ // reflow to restart the animation
+ void ring.offsetWidth;
+ ring.classList.add('wa-go');
+ }
+ particles.burst();
+ }
+
+ function destroy() {
+ try { io?.disconnect(); } catch { /* noop */ }
+ particles.destroy();
+ layer.remove();
+ }
+
+ return { applyVisual, update, flourish, destroy, el: layer, get state() { return layer.__state; } };
+}
+
+/**
+ * A capped, additive-blended orbiting particle field on a 2D canvas. Cheap: a
+ * few dozen points, no per-frame allocation, paused when off-screen. The count
+ * and speed are a function of the real net-worth tier, so a richer wallet has a
+ * denser, livelier field — still bounded so it never tanks frame rate.
+ */
+class ParticleField {
+ constructor(canvas) {
+ this.canvas = canvas;
+ this.ctx = canvas ? canvas.getContext('2d') : null;
+ this.points = [];
+ this.target = 0;
+ this.hue = 258;
+ this.speed = 1;
+ this.raf = 0;
+ this.running = false;
+ this.dpr = Math.min(devicePixelRatio || 1, 2);
+ this._tick = this._tick.bind(this);
+ if (canvas) {
+ this._ro = new ResizeObserver(() => this._resize());
+ this._ro.observe(canvas);
+ }
+ }
+
+ configure(v) {
+ if (!this.ctx) return;
+ this.target = v.dormant ? 0 : v.particleDensity;
+ this.hue = v.rimHue;
+ this.speed = 0.35 + v.intensity * 0.9;
+ this.intensity = v.intensity;
+ }
+
+ _resize() {
+ if (!this.canvas) return;
+ const w = this.canvas.clientWidth || 1;
+ const h = this.canvas.clientHeight || 1;
+ this.canvas.width = Math.round(w * this.dpr);
+ this.canvas.height = Math.round(h * this.dpr);
+ }
+
+ _spawn() {
+ const a = Math.random() * Math.PI * 2;
+ const r = 0.28 + Math.random() * 0.22;
+ return {
+ a, r,
+ rad: 0.6 + Math.random() * 1.8,
+ drift: (Math.random() - 0.5) * 0.0015,
+ ar: 0.002 + Math.random() * 0.004,
+ life: Math.random(),
+ };
+ }
+
+ start() {
+ if (!this.ctx || this.running) return;
+ this.running = true;
+ this._resize();
+ this.raf = requestAnimationFrame(this._tick);
+ }
+
+ stop() {
+ this.running = false;
+ if (this.raf) cancelAnimationFrame(this.raf);
+ this.raf = 0;
+ }
+
+ burst() {
+ if (!this.ctx) return;
+ for (let i = 0; i < 14; i++) {
+ const p = this._spawn();
+ p.r = 0.12;
+ p.rad = 1.2 + Math.random() * 2.2;
+ p.burst = 1;
+ this.points.push(p);
+ }
+ this.start();
+ }
+
+ _tick() {
+ if (!this.running) return;
+ const { ctx, canvas } = this;
+ const w = canvas.width, h = canvas.height;
+ ctx.clearRect(0, 0, w, h);
+
+ // Grow/shrink the steady population toward the tier target.
+ if (this.points.filter((p) => !p.burst).length < this.target) this.points.push(this._spawn());
+ else if (this.points.filter((p) => !p.burst).length > this.target) {
+ const i = this.points.findIndex((p) => !p.burst);
+ if (i >= 0) this.points.splice(i, 1);
+ }
+
+ const cx = w * 0.5, cy = h * 0.58;
+ const base = Math.min(w, h);
+ ctx.globalCompositeOperation = 'lighter';
+ for (let i = this.points.length - 1; i >= 0; i--) {
+ const p = this.points[i];
+ p.a += p.ar * this.speed;
+ p.r += p.drift + (p.burst ? 0.004 * this.speed : 0);
+ p.life += 0.004 * this.speed;
+ const x = cx + Math.cos(p.a) * p.r * base;
+ const y = cy + Math.sin(p.a) * p.r * base * 0.78;
+ const tw = 0.5 + 0.5 * Math.sin(p.life * 6.28);
+ const alpha = (p.burst ? Math.max(0, 1 - (p.r - 0.12) * 2.2) : 0.5 + this.intensity * 0.4) * tw;
+ if (p.burst && (p.r > 0.6 || alpha <= 0.02)) { this.points.splice(i, 1); continue; }
+ ctx.beginPath();
+ ctx.fillStyle = `hsla(${this.hue} 90% 78% / ${alpha.toFixed(3)})`;
+ ctx.arc(x, y, p.rad * this.dpr, 0, Math.PI * 2);
+ ctx.fill();
+ }
+ ctx.globalCompositeOperation = 'source-over';
+ this.raf = requestAnimationFrame(this._tick);
+ }
+
+ destroy() {
+ this.stop();
+ try { this._ro?.disconnect(); } catch { /* noop */ }
+ this.points = [];
+ }
+}
+
+/**
+ * Watch an agent's wallet for a REAL confirmed inflow and fire the avatar's
+ * one-shot flourish. The trigger is the real on-chain balance delta, sampled by
+ * a visibility-gated poll of the public balance endpoint (cached 60s server-
+ * side) — the animation only ever plays because lamports actually changed on
+ * chain, never on a bare timer. A real drawdown reads honestly (a brief dim).
+ *
+ * @param {string} agentId
+ * @param {{flourish(kind):void, update(s):any, el:HTMLElement}} controller
+ * @param {object} [opts] { network, intervalMs }
+ * @returns {() => void} stop fn
+ */
+export function startWalletLiveReaction(agentId, controller, opts = {}) {
+ if (!agentId || !controller) return () => {};
+ const network = opts.network === 'devnet' ? 'devnet' : 'mainnet';
+ const intervalMs = Math.max(15_000, opts.intervalMs || 30_000);
+ let lastLamports = null;
+ let timer = 0;
+ let stopped = false;
+ let visible = true;
+
+ const io = controller.el && typeof IntersectionObserver === 'function'
+ ? new IntersectionObserver((es) => { visible = es.some((e) => e.isIntersecting); }, { threshold: 0.01 })
+ : null;
+ if (io) io.observe(controller.el);
+
+ async function poll() {
+ if (stopped) return;
+ if (!visible) { schedule(); return; }
+ try {
+ const r = await fetch(`/api/agents/${encodeURIComponent(agentId)}/solana?network=${network}`, {
+ headers: { accept: 'application/json' },
+ });
+ const body = await r.json().catch(() => ({}));
+ const lamports = body?.data?.lamports;
+ if (typeof lamports === 'number') {
+ if (lastLamports != null && lamports !== lastLamports) {
+ // A real confirmed delta. Refresh the full priced state (so tier +
+ // palette re-derive from real holdings) and play the matching flourish.
+ controller.update(agentId).catch(() => {});
+ controller.flourish(lamports > lastLamports ? 'inflow' : 'drawdown');
+ }
+ lastLamports = lamports;
+ }
+ } catch {
+ /* transient network/RPC hiccup — keep polling, never surface a fake delta */
+ }
+ schedule();
+ }
+ function schedule() { if (!stopped) timer = setTimeout(poll, intervalMs); }
+
+ // Prime the baseline immediately, then poll on the interval.
+ poll();
+
+ return function stop() {
+ stopped = true;
+ if (timer) clearTimeout(timer);
+ try { io?.disconnect(); } catch { /* noop */ }
+ };
+}
+
+/**
+ * High-level convenience: mount the aura on a container, fetch + apply the real
+ * wallet state, and (optionally) start the live inflow reaction. Returns a
+ * controller with a combined `destroy()`. Safe to call with no wallet — the
+ * agent simply renders the clean dormant baseline.
+ */
+export async function hydrateAvatarWallet(container, agent, opts = {}) {
+ const controller = mountWalletAura(container, opts);
+ if (!controller) return null;
+ const agentId = typeof agent === 'string'
+ ? agent
+ : (agent?.agent_id || agent?.agentId || agent?.id || null);
+ let stopLive = () => {};
+ try {
+ await controller.update(agent);
+ if (opts.live !== false && agentId) {
+ stopLive = startWalletLiveReaction(agentId, controller, opts);
+ }
+ } catch {
+ /* leave the dormant baseline in place */
+ }
+ const destroy = controller.destroy;
+ controller.destroy = () => { stopLive(); destroy(); };
+ return controller;
+}
+
+/**
+ * Render a small net-worth tier badge element a surface can place near the
+ * avatar (e.g. the viewer toolbar). Pure presentation of the same visual.
+ */
+export function walletTierBadge(state) {
+ ensureStyles();
+ const v = computeWalletVisual(state);
+ const el = document.createElement('span');
+ el.className = 'wa-badge';
+ el.style.setProperty('--wa-accent', v.accent);
+ el.style.setProperty('--wa-glow', v.glow);
+ el.innerHTML = `<span class="wa-badge-dot"></span><span>${v.tierLabel}</span><span>${formatNetWorth(state)}</span>`;
+ el.title = v.dormant
+ ? 'Dormant wallet — fund this agent to light it up'
+ : `Net worth ${formatNetWorth(state)} · ${v.tierLabel} tier`;
+ return el;
+}
+
+/**
+ * Auto-hydrate every `[data-wallet-aura]` element under `root`. Each element
+ * must carry `data-agent-id` (and optionally `data-network`/`data-lod`). Card
+ * LOD by default, no live polling (dense grids stay cheap). Idempotent.
+ */
+export function hydrateWalletAuras(root = document) {
+ if (!root || typeof root.querySelectorAll !== 'function') return [];
+ const out = [];
+ for (const el of root.querySelectorAll('[data-wallet-aura]')) {
+ if (el.__waMounted) continue;
+ el.__waMounted = true;
+ const agentId = el.getAttribute('data-agent-id');
+ if (!agentId) continue;
+ const c = mountWalletAura(el, {
+ lod: el.getAttribute('data-lod') || 'card',
+ network: el.getAttribute('data-network') || 'mainnet',
+ });
+ if (c) { c.update(agentId).catch(() => {}); out.push(c); }
+ }
+ return out;
+}
+
+if (typeof window !== 'undefined') {
+ window.twsWalletAura = {
+ mountWalletAura, hydrateAvatarWallet, startWalletLiveReaction,
+ walletTierBadge, hydrateWalletAuras,
+ };
+}
diff --git a/src/shared/wallet-networth.js b/src/shared/wallet-networth.js
new file mode 100644
index 000000000..3f739d99c
--- /dev/null
+++ b/src/shared/wallet-networth.js
@@ -0,0 +1,324 @@
+/**
+ * Canonical wallet → net-worth state, and the pure real-data → visual mapping
+ * that drives the Net-Worth-Reactive Avatar (the agent that wears its wallet).
+ *
+ * This is the single source of truth for "how much is this agent's wallet worth,
+ * what is it made of, and therefore how should its 3D body look." Every surface
+ * (the avatar viewer, agent detail, marketplace, the galaxy, cards) reads the
+ * SAME numbers from here and applies the SAME mapping, so a given wallet state
+ * renders an identical avatar treatment everywhere.
+ *
+ * Everything is real chain data:
+ * - SOL balance + SPL holdings come from the agent's own public endpoints
+ * (GET /api/agents/:id/solana and /solana/holdings), the same contract the
+ * wallet hub uses — we never refetch differently per surface.
+ * - USD values are priced from the live Jupiter feed (SOL + every held mint in
+ * one call). Unpriced tokens contribute $0 — we never invent a price.
+ *
+ * The visual mapping (`computeWalletVisual`) is a PURE function of that real
+ * state: change the wallet, the look changes; there is no random and no decay
+ * timer. An empty wallet maps to a clean dormant baseline, never a broken or
+ * ugly state. A whale balance is capped so the effect stays tasteful.
+ *
+ * $THREE is the only coin this platform names or features. Other holdings only
+ * influence the look generically, by their real USD proportion — never by name.
+ */
+
+import { getSolPriceUsd } from './usd-price.js';
+
+// $THREE — the only coin three.ws features. Holding it earns the brand accent.
+export const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+// Wrapped SOL mint — used only to price native SOL through the same feed call.
+const WSOL_MINT = 'So11111111111111111111111111111111111111112';
+
+// USDC mints per cluster (dollar-pegged; valued 1:1 without a quote).
+const USDC_MINT_BY_CLUSTER = {
+ mainnet: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ devnet: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU',
+};
+
+const JUP_PRICE_URL = 'https://lite-api.jup.ag/price/v3';
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+// ── Tiers ───────────────────────────────────────────────────────────────────
+// Honest, fixed USD thresholds. The avatar's "presence" steps up through these
+// as real value crosses each line. `level` (0–5) is the single intensity knob.
+// Names evoke a body that glows brighter as it earns — dormant → luminous.
+export const NETWORTH_TIERS = [
+ { key: 'dormant', label: 'Dormant', level: 0, min: 0 },
+ { key: 'spark', label: 'Spark', level: 1, min: 1 },
+ { key: 'ember', label: 'Ember', level: 2, min: 25 },
+ { key: 'glow', label: 'Glow', level: 3, min: 250 },
+ { key: 'radiant', label: 'Radiant', level: 4, min: 2_500 },
+ { key: 'luminous', label: 'Luminous', level: 5, min: 25_000 },
+];
+
+/** Map a real USD net worth to its tier descriptor. `dormant` for 0 / empty. */
+export function tierForUsd(usd) {
+ const v = Number(usd);
+ if (!Number.isFinite(v) || v <= 0) return NETWORTH_TIERS[0];
+ let out = NETWORTH_TIERS[0];
+ for (const t of NETWORTH_TIERS) if (v >= t.min) out = t;
+ return out;
+}
+
+// ── Data fetch + normalize ──────────────────────────────────────────────────
+
+/** Resolve an agent id from any record shape the surfaces hold. */
+export function agentIdOf(agent) {
+ if (!agent) return null;
+ return agent.agent_id || agent.agentId || agent.id || null;
+}
+
+/** Read the agent's Solana address from any supported record shape. */
+export function addressOf(agent) {
+ if (!agent || typeof agent !== 'object') return null;
+ const meta = agent.meta || {};
+ const a =
+ agent.solana_address || meta.solana_address || agent.agent_solana_address ||
+ (typeof agent.wallet === 'string' && BASE58_RE.test(agent.wallet) ? agent.wallet : null) ||
+ null;
+ return a && BASE58_RE.test(String(a)) ? String(a) : null;
+}
+
+/**
+ * Price a set of mints in one Jupiter call. USDC resolves to exactly $1 without
+ * a network round-trip. Returns a Map<mint, usdPricePerToken>. Missing/failed
+ * prices are simply absent (caller treats them as $0 — never invented).
+ */
+async function priceMints(mints, network) {
+ const usdc = USDC_MINT_BY_CLUSTER[network] || USDC_MINT_BY_CLUSTER.mainnet;
+ const out = new Map();
+ const need = [];
+ for (const m of mints) {
+ if (m === usdc) out.set(m, 1);
+ else need.push(m);
+ }
+ if (!need.length) return out;
+ try {
+ const r = await fetch(`${JUP_PRICE_URL}?ids=${encodeURIComponent(need.join(','))}`);
+ if (r.ok) {
+ const data = await r.json();
+ for (const m of need) {
+ const p = data?.[m]?.usdPrice ?? data?.[m]?.price ?? null;
+ if (Number(p) > 0) out.set(m, Number(p));
+ }
+ }
+ } catch {
+ /* feed down — those mints stay unpriced ($0); SOL still prices below */
+ }
+ return out;
+}
+
+/**
+ * Fetch and normalize an agent's full wallet state into the canonical contract
+ * every surface consumes. Real data only; no throw on a soft failure — returns a
+ * coherent dormant/partial state the UI can render cleanly.
+ *
+ * @returns {Promise<WalletState>}
+ * { agentId, address, network, lamports, sol, usdTotal, priced, assets[],
+ * mix:{sol,usdc,three,other}, hasThree, balanceError }
+ */
+export async function fetchWalletState(agent, opts = {}) {
+ const network = opts.network === 'devnet' ? 'devnet' : 'mainnet';
+ const agentId = typeof agent === 'string' ? agent : agentIdOf(agent);
+ const known = typeof agent === 'string' ? null : addressOf(agent);
+ const empty = {
+ agentId, address: known, network,
+ lamports: null, sol: 0, usdTotal: 0, priced: false,
+ assets: [], mix: { sol: 0, usdc: 0, three: 0, other: 0 },
+ hasThree: false, balanceError: null,
+ };
+ if (!agentId) return empty;
+
+ let holdings;
+ try {
+ const r = await fetch(
+ `/api/agents/${encodeURIComponent(agentId)}/solana/holdings?network=${network}`,
+ { credentials: 'include' },
+ );
+ const body = await r.json().catch(() => ({}));
+ if (!r.ok) {
+ // 404 = wallet not provisioned yet → clean dormant baseline (not an error).
+ if (r.status === 404) return empty;
+ return { ...empty, balanceError: body?.error?.code || 'holdings_error' };
+ }
+ holdings = body.data;
+ } catch {
+ return { ...empty, balanceError: 'network_error' };
+ }
+
+ const address = holdings.address || known;
+ const sol = Number(holdings.sol) || 0;
+ const tokens = Array.isArray(holdings.tokens) ? holdings.tokens : [];
+
+ // Price SOL + every held mint together. SOL value always resolves (feed +
+ // CoinGecko fallback inside getSolPriceUsd); SPL tokens that the feed can't
+ // price contribute $0 rather than a fabricated value.
+ let solPrice = 0;
+ try { solPrice = await getSolPriceUsd(); } catch { solPrice = 0; }
+ const prices = await priceMints(tokens.map((t) => t.mint), network);
+
+ const assets = [];
+ let usdTotal = 0;
+ const solUsd = sol * (solPrice || 0);
+ if (sol > 0 || solPrice > 0) {
+ assets.push({ kind: 'sol', mint: WSOL_MINT, uiAmount: sol, usd: solUsd });
+ usdTotal += solUsd;
+ }
+ const usdcMint = USDC_MINT_BY_CLUSTER[network];
+ let hasThree = false;
+ for (const t of tokens) {
+ const price = prices.get(t.mint) ?? 0;
+ const usd = Number(t.ui_amount) * price;
+ const kind =
+ t.mint === THREE_MINT ? 'three' :
+ t.mint === usdcMint || t.is_usdc ? 'usdc' : 'other';
+ if (kind === 'three') hasThree = true;
+ assets.push({ kind, mint: t.mint, uiAmount: Number(t.ui_amount), usd, priced: price > 0 });
+ usdTotal += usd;
+ }
+ assets.sort((a, b) => b.usd - a.usd);
+
+ // Asset mix by real USD proportion (sums to 1 when usdTotal > 0).
+ const mix = { sol: 0, usdc: 0, three: 0, other: 0 };
+ if (usdTotal > 0) {
+ for (const a of assets) mix[a.kind] = (mix[a.kind] || 0) + a.usd / usdTotal;
+ }
+
+ return {
+ agentId, address, network,
+ lamports: holdings.lamports != null ? Number(holdings.lamports) : Math.round(sol * 1e9),
+ sol, usdTotal,
+ priced: solPrice > 0 || prices.size > 0,
+ assets, mix, hasThree,
+ balanceError: solPrice > 0 ? null : 'price_unavailable',
+ };
+}
+
+// ── Pure visual mapping ───────────────────────────────────────────────────────
+// Everything below is a deterministic function of the real WalletState. No
+// randomness, no time input — the same state always yields the same look.
+
+// Asset-mix hue rotations (degrees) layered over the violet wallet accent. These
+// are generic, coin-agnostic tints derived purely from real USD proportion; the
+// only coin named anywhere is $THREE, which earns the warm brand-gold shift.
+const MIX_HUES = {
+ sol: 170, // teal — native SOL
+ usdc: 150, // mint-green — the dollar rail
+ three: 45, // gold — $THREE, the one coin we feature
+ other: 250, // violet-neutral — generic SPL
+};
+
+const BASE_HUE = 258; // wallet-violet (matches --wallet-accent #c4b5fd family)
+
+/** Dominant asset kind by USD weight, or null for an empty wallet. */
+export function dominantAsset(state) {
+ if (!state || state.usdTotal <= 0) return null;
+ let best = null, bestW = 0;
+ for (const k of ['sol', 'usdc', 'three', 'other']) {
+ const w = state.mix?.[k] || 0;
+ if (w > bestW) { bestW = w; best = k; }
+ }
+ return best;
+}
+
+/**
+ * The pure real-data → visual descriptor. Consumed identically by the DOM aura
+ * (avatar viewer, cards) and the galaxy shader.
+ *
+ * @returns {{
+ * tier, level, intensity, particleDensity, accent, accentSoft, glow,
+ * rimHue, mixHue, hasThree, dominant, capped, dormant
+ * }}
+ */
+export function computeWalletVisual(state) {
+ const usd = Number(state?.usdTotal) || 0;
+ const tier = tierForUsd(usd);
+ const level = tier.level;
+ const dormant = level === 0;
+
+ // Intensity rises with tier and is then nudged smoothly within the tier by a
+ // log of value, so a wallet that is deep into a tier glows a touch stronger
+ // than one that just crossed the line — without ever exceeding the cap.
+ const base = level / 5; // 0 … 1
+ const within = level >= 5
+ ? 0
+ : Math.min(1, Math.log10(Math.max(1, usd / Math.max(1, tier.min))) / 1.2);
+ const span = level >= 5 ? 0 : (1 / 5) * 0.6;
+ const intensity = Math.min(1, base + within * span);
+
+ // Whale cap: hard-clamp so an enormous balance never eye-searingly overshoots.
+ const capped = level >= 5;
+
+ const dom = dominantAsset(state);
+ const mixHue = dom ? MIX_HUES[dom] : BASE_HUE;
+ // Keep the primary accent firmly in the violet wallet family; let the asset
+ // mix rotate it only slightly (max ~14°) so the system stays coherent.
+ const rimHue = lerpHue(BASE_HUE, mixHue, dormant ? 0 : 0.22);
+
+ const sat = dormant ? 22 : Math.round(46 + intensity * 30);
+ const light = dormant ? 70 : Math.round(74 + intensity * 8);
+ const accent = `hsl(${rimHue} ${sat}% ${light}%)`;
+ const accentSoft = `hsla(${rimHue} ${sat}% ${light}% / ${(0.10 + intensity * 0.22).toFixed(3)})`;
+ const glow = `hsla(${rimHue} ${Math.min(90, sat + 14)}% ${Math.min(80, light)}% / ${(0.18 + intensity * 0.5).toFixed(3)})`;
+
+ // Particle budget for the rich (full) LOD, capped and tasteful.
+ const particleDensity = dormant ? 0 : Math.round([0, 8, 16, 26, 40, 56][level]);
+
+ return {
+ tier: tier.key,
+ tierLabel: tier.label,
+ level,
+ intensity,
+ particleDensity,
+ accent,
+ accentSoft,
+ glow,
+ rimHue,
+ mixHue,
+ hasThree: !!state?.hasThree,
+ dominant: dom,
+ capped,
+ dormant,
+ usdTotal: usd,
+ };
+}
+
+/**
+ * Compact wealth signal for the galaxy: a single 0–1 wealth scalar + tint, from
+ * the same tiering. The galaxy values stars by real SOL balance (one batched
+ * RPC read), a real lower bound on net worth that scales legibly across the map.
+ */
+export function walletGlowForUsd(usd) {
+ const tier = tierForUsd(usd);
+ const wealth = tier.level / 5;
+ const vis = computeWalletVisual({ usdTotal: usd, mix: { sol: 1 }, hasThree: false });
+ return { wealth, level: tier.level, tier: tier.key, rimHue: vis.rimHue };
+}
+
+// Shortest-path hue interpolation on the colour wheel.
+function lerpHue(a, b, t) {
+ let d = ((b - a + 540) % 360) - 180;
+ return (a + d * t + 360) % 360;
+}
+
+/** Human net-worth label, e.g. "$1,240" / "$0" / "—" (price feed down). */
+export function formatNetWorth(state) {
+ if (!state) return '—';
+ if (state.balanceError === 'price_unavailable' && state.usdTotal === 0) return '—';
+ const v = Number(state.usdTotal) || 0;
+ if (v === 0) return '$0';
+ if (v < 0.01) return '<$0.01';
+ if (v < 1000) return `$${v.toFixed(2)}`;
+ if (v < 1_000_000) return `$${Math.round(v).toLocaleString()}`;
+ return `$${(v / 1_000_000).toFixed(2)}M`;
+}
+
+if (typeof window !== 'undefined') {
+ window.twsWalletNetworth = {
+ fetchWalletState, computeWalletVisual, tierForUsd, walletGlowForUsd,
+ formatNetWorth, dominantAsset, NETWORTH_TIERS, THREE_MINT,
+ };
+}
diff --git a/src/studio/body/body-mount.js b/src/studio/body/body-mount.js
new file mode 100644
index 000000000..c7cf69aab
--- /dev/null
+++ b/src/studio/body/body-mount.js
@@ -0,0 +1,31 @@
+/**
+ * Body Studio — mount bootstrap (P3)
+ * ==================================
+ * Binds the Body Studio to the Agent Studio shell's Body tab on
+ * `studio-shell:ready`. Mirrors P1/P2 mounts: idempotent and order-independent
+ * (handles both event-after-subscribe and already-ready).
+ *
+ * The agent-studio page loads this alongside the shell:
+ * <script type="module" src="/src/studio/body/body-mount.js"></script>
+ */
+
+import { studio } from '../agent-studio-store.js';
+import { mountBodyStudio } from './body-studio.js';
+
+const SELECTOR = '[data-studio-mount="body"]';
+
+function mount() {
+ const panel = document.querySelector(SELECTOR);
+ if (!panel || panel.dataset.bodyMounted) return false;
+ mountBodyStudio(panel, { studio });
+ return true;
+}
+
+document.addEventListener('studio-shell:ready', mount, { once: false });
+
+if (!mount()) {
+ let tries = 0;
+ const t = setInterval(() => {
+ if (mount() || ++tries > 60) clearInterval(t); // ~6s ceiling
+ }, 100);
+}
diff --git a/src/studio/body/body-studio.js b/src/studio/body/body-studio.js
new file mode 100644
index 000000000..15413ca00
--- /dev/null
+++ b/src/studio/body/body-studio.js
@@ -0,0 +1,319 @@
+/**
+ * Body Studio — controller (P3)
+ * =============================
+ * The avatar surface of Agent Studio: choose the 3D body, customize its outfit,
+ * and shape how it moves. Every change drives the live stage avatar instantly
+ * (via the shared store + <agent-presence>) and persists the real record.
+ *
+ * • Body — the bound avatar (thumbnail + name), swap via the shared avatar
+ * picker (writes agent.avatar_id), deep-customize in the avatar
+ * editor, or spin up a new one. The default avatar is a real,
+ * always-present starter — an agent is never bodiless.
+ * • Movement — the full retargetable clip library (animation-presets.curate):
+ * click any clip to play it live on the stage, and pin a looping
+ * idle as the agent's resting pose (meta.studio.body.idleClip),
+ * which <agent-presence> honors everywhere on the platform.
+ *
+ * Mount: import { mountBodyStudio } from './body/body-studio.js';
+ * mountBodyStudio(container, { studio });
+ */
+
+import { apiFetch } from '../../api.js';
+import { createAvatarPicker } from '../../avatar-picker.js';
+import { curate } from '../../animation-presets.js';
+
+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) =>
+ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+
+const DEFAULT_AVATAR = { id: null, name: 'Default starter', url: '/avatars/default.glb', thumbnailUrl: null };
+
+export function mountBodyStudio(container, { studio }) {
+ if (container.dataset.bodyMounted) return;
+ container.dataset.bodyMounted = '1';
+ container.querySelector('.studio-empty')?.remove();
+ return new BodyStudio(container, studio);
+}
+
+class BodyStudio {
+ constructor(el, studio) {
+ this.el = el;
+ this.studio = studio;
+ this.state = {
+ loading: true,
+ error: null,
+ avatar: null, // resolved { id, name, url, thumbnailUrl }
+ clips: null, // { featured, groups } from curate()
+ openCat: null,
+ playing: null, // clip name currently previewing
+ };
+ this._picker = null;
+ this._render();
+ this._load();
+ }
+
+ _q(sel) { return this.el.querySelector(sel); }
+
+ get _idleClip() {
+ return this.studio.agent?.meta?.studio?.body?.idleClip || 'idle';
+ }
+
+ // The live stage avatar lives in the shell's stage; drive it directly for
+ // instant, real preview (the same element every other surface renders).
+ get _stage() {
+ return document.querySelector('.studio-stage agent-presence') || document.querySelector('agent-presence');
+ }
+
+ // ── Data ────────────────────────────────────────────────────────────────
+
+ async _load() {
+ this.state.loading = true;
+ this._renderBody();
+ try {
+ const [avatar, clips] = await Promise.all([this._resolveAvatar(), this._loadClips()]);
+ this.state.avatar = avatar;
+ this.state.clips = clips;
+ this.state.error = null;
+ } catch (err) {
+ this.state.error = err?.message || 'Could not load the body studio.';
+ } finally {
+ this.state.loading = false;
+ this._renderBody();
+ }
+ }
+
+ async _resolveAvatar() {
+ const id = this.studio.agent?.avatarId || null;
+ if (!id) return { ...DEFAULT_AVATAR };
+ try {
+ const res = await apiFetch(`/api/avatars/${id}`, { allowAnonymous: true });
+ if (!res.ok) return { ...DEFAULT_AVATAR, id, name: 'Your avatar' };
+ const { avatar } = await res.json();
+ return {
+ id,
+ name: avatar?.name || 'Your avatar',
+ url: avatar?.url || avatar?.model_url || avatar?.base_model_url || null,
+ thumbnailUrl: avatar?.thumbnail_url || null,
+ };
+ } catch {
+ return { ...DEFAULT_AVATAR, id, name: 'Your avatar' };
+ }
+ }
+
+ async _loadClips() {
+ const res = await fetch('/animations/manifest.json');
+ if (!res.ok) throw new Error('Could not load the animation library.');
+ const manifest = await res.json();
+ const defs = Array.isArray(manifest) ? manifest : manifest.clips || manifest.animations || [];
+ return curate(defs);
+ }
+
+ // ── Shell ─────────────────────────────────────────────────────────────────
+
+ _render() {
+ this.el.innerHTML = `<div class="bdy" data-root></div>`;
+ // Keep the resting-pose pin in sync if another surface edits the body bag.
+ this._unsub = this.studio.subscribe(() => {
+ if (!this.state.loading && this.state.clips) this._syncIdleMarks();
+ });
+ }
+
+ _renderBody() {
+ const host = this._q('[data-root]');
+ if (this.state.loading) { host.innerHTML = this._skeleton(); return; }
+ if (this.state.error) { host.innerHTML = this._errorState(this.state.error); this._bindError(); return; }
+ host.innerHTML = `${this._bodySection()}${this._movementSection()}`;
+ this._bind();
+ this._syncIdleMarks();
+ }
+
+ _skeleton() {
+ return `
+ <div class="bdy-skel">
+ <div class="bdy-skel-card"></div>
+ <div class="bdy-skel-row"></div>
+ <div class="bdy-skel-grid">${'<div class="bdy-skel-chip"></div>'.repeat(8)}</div>
+ </div>`;
+ }
+
+ _errorState(msg) {
+ return `
+ <div class="bdy-empty">
+ <div class="bdy-empty-glyph" aria-hidden="true">⚠</div>
+ <h3>Couldn’t load the body studio</h3>
+ <p>${esc(msg)}</p>
+ <button class="studio-btn studio-btn-ghost" data-action="retry">Try again</button>
+ </div>`;
+ }
+
+ // ── Body (avatar) ──────────────────────────────────────────────────────────
+
+ _bodySection() {
+ const a = this.state.avatar || DEFAULT_AVATAR;
+ const thumb = a.thumbnailUrl
+ ? `<img src="${esc(a.thumbnailUrl)}" alt="" loading="lazy" />`
+ : `<div class="bdy-avatar-fallback" aria-hidden="true">◓</div>`;
+ const isDefault = !a.id;
+ return `
+ <section class="bdy-section" aria-labelledby="bdy-body-h">
+ <div class="bdy-section-head">
+ <h3 id="bdy-body-h">Body</h3>
+ <p>The 3D avatar your agent wears everywhere — chat, world, profile, and feed.</p>
+ </div>
+ <div class="bdy-avatar-card">
+ <div class="bdy-avatar-thumb">${thumb}</div>
+ <div class="bdy-avatar-meta">
+ <span class="bdy-avatar-name">${esc(a.name)}</span>
+ <span class="bdy-avatar-sub">${isDefault ? 'Default starter — swap it for your own anytime.' : 'Live on the stage →'}</span>
+ <div class="bdy-avatar-actions">
+ <button class="studio-btn studio-btn-primary studio-action" data-action="change">Change avatar</button>
+ <a class="studio-btn studio-btn-ghost studio-action" data-action="customize"
+ href="${isDefault ? '/create' : `/avatars/${encodeURIComponent(a.id)}/edit`}">
+ ${isDefault ? 'Create your own ↗' : 'Customize outfit ↗'}
+ </a>
+ </div>
+ </div>
+ </div>
+ </section>`;
+ }
+
+ // ── Movement (animations) ───────────────────────────────────────────────────
+
+ _movementSection() {
+ const { featured, groups } = this.state.clips;
+ return `
+ <section class="bdy-section" aria-labelledby="bdy-move-h">
+ <div class="bdy-section-head">
+ <h3 id="bdy-move-h">Movement</h3>
+ <p>Click any move to preview it live. Pin a looping idle as the resting pose your agent holds everywhere.</p>
+ </div>
+ <div class="bdy-resting" aria-live="polite">
+ <span class="bdy-resting-label">Resting pose</span>
+ <span class="bdy-resting-val" data-resting>${esc(this._restingLabel())}</span>
+ </div>
+ <div class="bdy-featured">
+ ${featured.map((c) => this._chip(c, true)).join('')}
+ </div>
+ <div class="bdy-cats">
+ ${groups.map((g) => this._catBlock(g)).join('')}
+ </div>
+ </section>`;
+ }
+
+ _restingLabel() {
+ const idle = this._idleClip;
+ const all = [...(this.state.clips?.featured || []), ...(this.state.clips?.groups || []).flatMap((g) => g.items)];
+ return all.find((c) => c.name === idle)?.label || idle;
+ }
+
+ _catBlock(g) {
+ const open = this.state.openCat === g.key;
+ return `
+ <details class="bdy-cat" ${open ? 'open' : ''} data-cat="${esc(g.key)}">
+ <summary class="bdy-cat-summary">
+ <span>${g.icon} ${esc(g.label)}</span>
+ <span class="bdy-cat-count">${g.items.length}</span>
+ </summary>
+ <div class="bdy-grid">${g.items.map((c) => this._chip(c, false)).join('')}</div>
+ </details>`;
+ }
+
+ _chip(c, featured) {
+ const loop = c.loop !== false;
+ const canPin = loop; // only loops make sense as a held resting pose
+ return `
+ <div class="bdy-chip ${featured ? 'bdy-chip--featured' : ''}" data-clip="${esc(c.name)}" data-loop="${loop}">
+ <button class="bdy-chip-play" data-action="play" data-clip="${esc(c.name)}" data-loop="${loop}"
+ title="Preview ${esc(c.label || c.name)}">
+ <span class="bdy-chip-icon" aria-hidden="true">${c.icon || '▶'}</span>
+ <span class="bdy-chip-label">${esc(c.label || c.name)}</span>
+ </button>
+ ${canPin ? `<button class="bdy-chip-pin" data-action="pin" data-clip="${esc(c.name)}"
+ title="Set as resting pose" aria-label="Set ${esc(c.label || c.name)} as resting pose">☆</button>` : ''}
+ </div>`;
+ }
+
+ // ── Bind ────────────────────────────────────────────────────────────────────
+
+ _bindError() {
+ this._q('[data-action="retry"]')?.addEventListener('click', () => this._load());
+ }
+
+ _bind() {
+ this.el.addEventListener('click', (e) => {
+ const btn = e.target.closest('[data-action]');
+ if (!btn) return;
+ const action = btn.dataset.action;
+ if (action === 'change') return this._openPicker();
+ if (action === 'play') return this._preview(btn.dataset.clip, btn.dataset.loop === 'true');
+ if (action === 'pin') return this._pinResting(btn.dataset.clip);
+ // 'customize' is a real <a> — let it navigate.
+ });
+ // Track which category the user expands so a re-render keeps it open.
+ this.el.querySelectorAll('.bdy-cat').forEach((d) =>
+ d.addEventListener('toggle', () => { if (d.open) this.state.openCat = d.dataset.cat; }));
+ }
+
+ _openPicker() {
+ if (!this._picker) {
+ this._picker = createAvatarPicker({
+ onSelect: ({ id }) => this._setAvatar(id),
+ });
+ }
+ this._picker.open(this.studio.agent?.avatarId || null);
+ }
+
+ async _setAvatar(avatarId) {
+ // null = the default starter. patch() drives the live stage immediately
+ // (presence reloads on avatarId change) and debounce-PUTs avatar_id.
+ this.studio.patch({ avatarId: avatarId || null });
+ this.studio.emit('body:change', { avatarId: avatarId || null });
+ this.state.avatar = await this._resolveAvatar();
+ this._renderBody();
+ }
+
+ _preview(name, loop) {
+ if (!name) return;
+ this.state.playing = name;
+ this._stage?.playClip?.(name, { loop });
+ this.studio.emit('body:preview', { clip: name, loop });
+ // Flash the active chip so the click registers even on a clip-less rig.
+ this.el.querySelectorAll('.bdy-chip').forEach((c) =>
+ c.classList.toggle('bdy-chip--playing', c.dataset.clip === name));
+ clearTimeout(this._playFlash);
+ this._playFlash = setTimeout(() => {
+ this.el.querySelectorAll('.bdy-chip--playing').forEach((c) => c.classList.remove('bdy-chip--playing'));
+ }, loop ? 1200 : 2200);
+ }
+
+ _pinResting(name) {
+ if (!name) return;
+ this.studio.patch({ meta: { studio: { body: { idleClip: name } } } });
+ this.studio.emit('body:change', { idleClip: name });
+ this._preview(name, true); // show the new resting pose immediately
+ const restingEl = this._q('[data-resting]');
+ if (restingEl) restingEl.textContent = this._restingLabel();
+ this._syncIdleMarks();
+ }
+
+ // Reflect the pinned resting pose on the matching chip (filled star + ring).
+ _syncIdleMarks() {
+ const idle = this._idleClip;
+ this.el.querySelectorAll('.bdy-chip').forEach((chip) => {
+ const on = chip.dataset.clip === idle;
+ chip.classList.toggle('bdy-chip--resting', on);
+ const pin = chip.querySelector('.bdy-chip-pin');
+ if (pin) {
+ pin.textContent = on ? '★' : '☆';
+ pin.classList.toggle('on', on);
+ pin.title = on ? 'Current resting pose' : 'Set as resting pose';
+ }
+ });
+ const restingEl = this._q('[data-resting]');
+ if (restingEl) restingEl.textContent = this._restingLabel();
+ }
+
+ destroy() {
+ this._unsub?.();
+ clearTimeout(this._playFlash);
+ }
+}
diff --git a/src/studio/money/money-mount.js b/src/studio/money/money-mount.js
new file mode 100644
index 000000000..e32507532
--- /dev/null
+++ b/src/studio/money/money-mount.js
@@ -0,0 +1,30 @@
+/**
+ * Money Studio — mount bootstrap (P4)
+ * ===================================
+ * Binds the Money Studio to the Agent Studio shell's Money tab on
+ * `studio-shell:ready`. Mirrors P1–P3 mounts: idempotent and order-independent.
+ *
+ * The agent-studio page loads this alongside the shell:
+ * <script type="module" src="/src/studio/money/money-mount.js"></script>
+ */
+
+import { studio } from '../agent-studio-store.js';
+import { mountMoneyStudio } from './money-studio.js';
+
+const SELECTOR = '[data-studio-mount="money"]';
+
+function mount() {
+ const panel = document.querySelector(SELECTOR);
+ if (!panel || panel.dataset.moneyMounted) return false;
+ mountMoneyStudio(panel, { studio });
+ return true;
+}
+
+document.addEventListener('studio-shell:ready', mount, { once: false });
+
+if (!mount()) {
+ let tries = 0;
+ const t = setInterval(() => {
+ if (mount() || ++tries > 60) clearInterval(t); // ~6s ceiling
+ }, 100);
+}
diff --git a/src/studio/money/money-studio.js b/src/studio/money/money-studio.js
new file mode 100644
index 000000000..f772d44f7
--- /dev/null
+++ b/src/studio/money/money-studio.js
@@ -0,0 +1,396 @@
+/**
+ * Money Studio — controller (P4)
+ * ==============================
+ * The economic surface of Agent Studio: fund the agent's wallet, price what it
+ * sells, and watch what it earns — all against real custodial wallets and the
+ * live skill-pricing + payments APIs (no mocks).
+ *
+ * • Wallet — the agent's real custodial Solana wallet: address, live SOL +
+ * USDC balance, a copy-to-fund deposit path, and a one-click
+ * provision for an agent that doesn't have a signing wallet yet.
+ * • Pricing — per-skill prices (USDC) via /api/agents/:id/pricing/:skill.
+ * Only metered, sellable skills the agent has enabled appear; a
+ * skill with no price is free. Cross-links to the Skills tab.
+ * • Earnings — the real payments ledger (/api/agents/:id/payments) of money
+ * other agents and users have paid this one.
+ *
+ * Mount: import { mountMoneyStudio } from './money/money-studio.js';
+ * mountMoneyStudio(container, { studio });
+ */
+
+import { apiFetch } from '../../api.js';
+import { isSellable, skillMeta } from '../skills/skills-catalog.js';
+
+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) =>
+ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+
+// Mainnet USDC — the agent-to-agent x402 settlement asset (6 decimals). Skill
+// pricing is denominated in USDC so a buyer agent can pay with a stable rail.
+const USDC_MINT = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+const USDC_DECIMALS = 6;
+const BALANCE_POLL_MS = 30000;
+
+const fmtUsdc = (atomic) => (Number(atomic || 0) / 10 ** USDC_DECIMALS);
+const toAtomic = (usdc) => Math.round(Number(usdc) * 10 ** USDC_DECIMALS);
+const short = (addr) => (addr ? `${addr.slice(0, 4)}…${addr.slice(-4)}` : '');
+
+function relTime(ts) {
+ if (!ts) return '';
+ const d = Date.now() - new Date(ts).getTime();
+ if (d < 60000) return 'just now';
+ if (d < 3600000) return Math.floor(d / 60000) + 'm ago';
+ if (d < 86400000) return Math.floor(d / 3600000) + 'h ago';
+ if (d < 2592000000) return Math.floor(d / 86400000) + 'd ago';
+ return new Date(ts).toLocaleDateString(undefined, { month: 'short', day: 'numeric' });
+}
+
+export function mountMoneyStudio(container, { studio }) {
+ if (container.dataset.moneyMounted) return;
+ container.dataset.moneyMounted = '1';
+ container.querySelector('.studio-empty')?.remove();
+ return new MoneyStudio(container, studio);
+}
+
+class MoneyStudio {
+ constructor(el, studio) {
+ this.el = el;
+ this.studio = studio;
+ this.agentId = studio.agent?.id;
+ this.state = {
+ loading: true,
+ error: null,
+ wallet: null, // { solana_address, solana_balance, usdc_balance, ... }
+ prices: {}, // skill → { amount, currency_mint, chain }
+ payments: null, // received payments array
+ provisioning: false,
+ };
+ this._render();
+ this._load();
+ // Live balances while the tab is visible.
+ this._poll = setInterval(() => {
+ if (document.visibilityState === 'visible' && !this.el.closest('[hidden]')) this._refreshWallet();
+ }, BALANCE_POLL_MS);
+ }
+
+ _q(sel) { return this.el.querySelector(sel); }
+
+ // ── Data ────────────────────────────────────────────────────────────────
+
+ async _load() {
+ this.state.loading = true;
+ this._renderBody();
+ try {
+ const [wallet, prices, payments] = await Promise.all([
+ this._fetchWallet(),
+ this._fetchPrices(),
+ this._fetchPayments(),
+ ]);
+ this.state.wallet = wallet;
+ this.state.prices = prices;
+ this.state.payments = payments;
+ this.state.error = null;
+ } catch (err) {
+ this.state.error = err?.message || 'Could not load the money studio.';
+ } finally {
+ this.state.loading = false;
+ this._renderBody();
+ }
+ }
+
+ async _fetchWallet() {
+ const res = await apiFetch(`/api/agents/${this.agentId}/wallet`);
+ if (!res.ok) throw new Error('Could not read the agent wallet.');
+ return res.json();
+ }
+
+ async _fetchPrices() {
+ const res = await apiFetch(`/api/agents/${this.agentId}/pricing`, { allowAnonymous: true });
+ if (!res.ok) return {};
+ const { prices = [] } = await res.json();
+ const map = {};
+ for (const p of prices) map[p.skill] = p;
+ return map;
+ }
+
+ async _fetchPayments() {
+ const res = await apiFetch(`/api/agents/${this.agentId}/payments?direction=received&limit=20`);
+ if (!res.ok) return [];
+ const { payments = [] } = await res.json();
+ return payments;
+ }
+
+ async _refreshWallet() {
+ try {
+ const wallet = await this._fetchWallet();
+ this.state.wallet = wallet;
+ this._renderWalletBalances();
+ } catch { /* transient RPC hiccup — keep the last balances */ }
+ }
+
+ // ── Shell ─────────────────────────────────────────────────────────────────
+
+ _render() {
+ this.el.innerHTML = `<div class="mny" data-root></div><div class="mny-toast" data-toast hidden></div>`;
+ }
+
+ _renderBody() {
+ const host = this._q('[data-root]');
+ if (this.state.loading) { host.innerHTML = this._skeleton(); return; }
+ if (this.state.error) { host.innerHTML = this._errorState(this.state.error); this._bindError(); return; }
+ host.innerHTML = `${this._walletSection()}${this._pricingSection()}${this._earningsSection()}`;
+ this._bind();
+ }
+
+ _skeleton() {
+ return `<div class="mny-skel"><div class="mny-skel-card"></div><div class="mny-skel-card"></div><div class="mny-skel-card"></div></div>`;
+ }
+
+ _errorState(msg) {
+ return `
+ <div class="mny-empty">
+ <div class="mny-empty-glyph" aria-hidden="true">⚠</div>
+ <h3>Couldn’t load money</h3>
+ <p>${esc(msg)}</p>
+ <button class="studio-btn studio-btn-ghost" data-action="retry">Try again</button>
+ </div>`;
+ }
+
+ // ── Wallet ──────────────────────────────────────────────────────────────────
+
+ _walletSection() {
+ const w = this.state.wallet || {};
+ const addr = w.solana_address;
+ if (!addr) {
+ return `
+ <section class="mny-section" aria-labelledby="mny-wallet-h">
+ <div class="mny-section-head"><h3 id="mny-wallet-h">Wallet</h3>
+ <p>Your agent needs a custodial wallet before it can earn or pay other agents.</p></div>
+ <div class="mny-wallet-card mny-wallet-empty">
+ <div class="mny-wallet-glyph" aria-hidden="true">◎</div>
+ <p>No signing wallet yet.</p>
+ <button class="studio-btn studio-btn-primary" data-action="provision" ${this.state.provisioning ? 'disabled' : ''}>
+ ${this.state.provisioning ? 'Creating…' : 'Create wallet'}
+ </button>
+ </div>
+ </section>`;
+ }
+ return `
+ <section class="mny-section" aria-labelledby="mny-wallet-h">
+ <div class="mny-section-head">
+ <h3 id="mny-wallet-h">Wallet</h3>
+ <p>Real custodial Solana wallet. Fund it with USDC so it can pay other agents and cover gas.</p>
+ </div>
+ <div class="mny-wallet-card">
+ <div class="mny-wallet-bal" data-balances>${this._balancesHtml()}</div>
+ <div class="mny-wallet-addr">
+ <span class="mny-addr-label">Deposit address</span>
+ <code class="mny-addr" title="${esc(addr)}">${esc(short(addr))}</code>
+ <button class="mny-icon-btn" data-action="copy" data-copy="${esc(addr)}" title="Copy address" aria-label="Copy deposit address">⧉</button>
+ <a class="mny-icon-btn" href="https://solscan.io/account/${esc(addr)}" target="_blank" rel="noopener" title="View on Solscan" aria-label="View on explorer">↗</a>
+ </div>
+ <div class="mny-wallet-tools">
+ <a class="studio-btn studio-btn-primary studio-action" href="/agent/${encodeURIComponent(this.agentId)}/wallet#deposit">Add funds</a>
+ <button class="studio-btn studio-btn-ghost studio-action" data-action="refresh">Refresh balance</button>
+ </div>
+ </div>
+ </section>`;
+ }
+
+ _balancesHtml() {
+ const w = this.state.wallet || {};
+ const sol = w.solana_balance == null ? '—' : Number(w.solana_balance).toFixed(4);
+ const usdc = w.usdc_balance == null ? '—' : Number(w.usdc_balance).toFixed(2);
+ return `
+ <div class="mny-bal"><b>$${esc(usdc)}</b><span>USDC</span></div>
+ <div class="mny-bal"><b>${esc(sol)}</b><span>SOL</span></div>`;
+ }
+
+ _renderWalletBalances() {
+ const host = this._q('[data-balances]');
+ if (host) host.innerHTML = this._balancesHtml();
+ }
+
+ // ── Pricing ───────────────────────────────────────────────────────────────
+
+ _pricingSection() {
+ const skills = (this.studio.agent?.skills || []).filter(isSellable);
+ return `
+ <section class="mny-section" aria-labelledby="mny-price-h">
+ <div class="mny-section-head">
+ <h3 id="mny-price-h">Pricing</h3>
+ <p>Charge other agents and users per call, in USDC. Leave a skill at $0 to keep it free.</p>
+ </div>
+ ${
+ skills.length
+ ? `<ul class="mny-price-list">${skills.map((id) => this._priceRow(id)).join('')}</ul>`
+ : `<div class="mny-inline-empty">
+ <p>No sellable skills enabled yet.</p>
+ <button class="studio-btn studio-btn-ghost studio-action" data-action="go-skills">Add skills →</button>
+ </div>`
+ }
+ </section>`;
+ }
+
+ _priceRow(id) {
+ const meta = skillMeta(id);
+ const p = this.state.prices[id];
+ const value = p ? fmtUsdc(p.amount) : '';
+ const active = !!p;
+ return `
+ <li class="mny-price-row ${active ? 'is-priced' : ''}" data-skill="${esc(id)}">
+ <div class="mny-price-meta">
+ <span class="mny-price-icon" aria-hidden="true">${meta.icon || '⚙️'}</span>
+ <div>
+ <span class="mny-price-name">${esc(meta.name)}</span>
+ <span class="mny-price-desc">${esc(meta.desc)}</span>
+ </div>
+ </div>
+ <div class="mny-price-input">
+ <span class="mny-price-cur">$</span>
+ <input type="number" inputmode="decimal" min="0" step="0.01" value="${value}"
+ placeholder="0.00" aria-label="Price for ${esc(meta.name)} in USDC" data-price-input />
+ <span class="mny-price-unit">/call</span>
+ <button class="studio-btn studio-btn-ghost studio-action mny-price-save" data-action="save-price" data-skill="${esc(id)}">Save</button>
+ </div>
+ </li>`;
+ }
+
+ // ── Earnings ──────────────────────────────────────────────────────────────
+
+ _earningsSection() {
+ const items = this.state.payments || [];
+ return `
+ <section class="mny-section" aria-labelledby="mny-earn-h">
+ <div class="mny-section-head"><h3 id="mny-earn-h">Earnings</h3>
+ <p>Every payment other agents and users have made to this one.</p></div>
+ ${
+ items.length
+ ? `<ul class="mny-earn-list">${items.map((p) => this._earnRow(p)).join('')}</ul>`
+ : `<div class="mny-inline-empty">
+ <div class="mny-empty-glyph small" aria-hidden="true">◎</div>
+ <p>No earnings yet. Price a skill and share your agent — payments land here in real time.</p>
+ </div>`
+ }
+ </section>`;
+ }
+
+ _earnRow(p) {
+ const usdc = fmtUsdc(p.amount_wei);
+ const who = p.payer_name || (p.payer_agent_id ? `agent ${short(p.payer_agent_id)}` : 'someone');
+ const what = p.skill_name ? `for ${esc(p.skill_name)}` : (p.memo ? esc(p.memo) : '');
+ const explorer = p.tx_hash
+ ? `<a class="mny-earn-tx" href="https://solscan.io/tx/${esc(p.tx_hash)}" target="_blank" rel="noopener" title="View transaction">↗</a>`
+ : '';
+ return `
+ <li class="mny-earn-row" data-status="${esc(p.status || 'confirmed')}">
+ <span class="mny-earn-amt">+$${esc(usdc.toFixed(2))}</span>
+ <span class="mny-earn-detail"><b>${esc(who)}</b> ${what}</span>
+ <span class="mny-earn-time">${esc(relTime(p.created_at))}</span>
+ ${explorer}
+ </li>`;
+ }
+
+ // ── Bind / actions ────────────────────────────────────────────────────────
+
+ _bindError() {
+ this._q('[data-action="retry"]')?.addEventListener('click', () => this._load());
+ }
+
+ _bind() {
+ this.el.addEventListener('click', (e) => {
+ const btn = e.target.closest('[data-action]');
+ if (!btn) return;
+ const a = btn.dataset.action;
+ if (a === 'retry') return this._load();
+ if (a === 'provision') return this._provision();
+ if (a === 'refresh') return this._refreshWallet();
+ if (a === 'copy') return this._copy(btn.dataset.copy);
+ if (a === 'save-price') return this._savePrice(btn.dataset.skill);
+ if (a === 'go-skills') return document.dispatchEvent(new CustomEvent('studio:navigate', { detail: { tab: 'skills' } }));
+ });
+ this.el.querySelectorAll('[data-price-input]').forEach((inp) =>
+ inp.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter') {
+ e.preventDefault();
+ this._savePrice(e.target.closest('[data-skill]')?.dataset.skill);
+ }
+ }));
+ }
+
+ async _provision() {
+ if (this.state.provisioning) return;
+ this.state.provisioning = true;
+ this._renderBody();
+ try {
+ const res = await apiFetch(`/api/agents/${this.agentId}/wallet/provision`, { method: 'POST' });
+ if (!res.ok) throw new Error('Provisioning failed.');
+ this._toast('Wallet created');
+ await this._load();
+ } catch (err) {
+ this.state.provisioning = false;
+ this._renderBody();
+ this._toast(err.message || 'Could not create wallet', true);
+ }
+ }
+
+ async _copy(text) {
+ try {
+ await navigator.clipboard.writeText(text);
+ this._toast('Address copied');
+ } catch {
+ this._toast('Copy failed — select it manually', true);
+ }
+ }
+
+ async _savePrice(skill) {
+ if (!skill) return;
+ const row = this.el.querySelector(`.mny-price-row[data-skill="${CSS.escape(skill)}"]`);
+ const input = row?.querySelector('[data-price-input]');
+ const btn = row?.querySelector('.mny-price-save');
+ if (!input) return;
+ const usd = parseFloat(input.value);
+ if (Number.isNaN(usd) || usd < 0) return this._toast('Enter a valid amount', true);
+ if (btn) { btn.disabled = true; btn.textContent = 'Saving…'; }
+ try {
+ if (usd === 0) {
+ // $0 = free → remove the price.
+ await apiFetch(`/api/agents/${this.agentId}/pricing/${encodeURIComponent(skill)}`, { method: 'DELETE' });
+ delete this.state.prices[skill];
+ } else {
+ const res = await apiFetch(`/api/agents/${this.agentId}/pricing/${encodeURIComponent(skill)}`, {
+ method: 'PUT',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ currency_mint: USDC_MINT, chain: 'solana', amount: toAtomic(usd), is_active: true }),
+ });
+ if (!res.ok) throw new Error('Could not save price.');
+ const saved = await res.json();
+ this.state.prices[skill] = saved;
+ }
+ // Record that this skill is sellable in the studio meta bag so the
+ // Skills tab + profile reflect it without a refetch.
+ this.studio.patch({ meta: { studio: { money: { priced: Object.keys(this.state.prices) } } } });
+ this.studio.emit('money:change', { skill, amount: usd });
+ row?.classList.toggle('is-priced', usd > 0);
+ this._toast(usd === 0 ? 'Skill is now free' : `Priced at $${usd.toFixed(2)}/call`);
+ } catch (err) {
+ this._toast(err.message || 'Save failed', true);
+ } finally {
+ if (btn) { btn.disabled = false; btn.textContent = 'Save'; }
+ }
+ }
+
+ _toast(msg, isError = false) {
+ const t = this._q('[data-toast]');
+ if (!t) return;
+ t.textContent = msg;
+ t.hidden = false;
+ t.className = `mny-toast ${isError ? 'mny-toast-err' : ''} show`;
+ clearTimeout(this._toastTimer);
+ this._toastTimer = setTimeout(() => { t.classList.remove('show'); setTimeout(() => { t.hidden = true; }, 300); }, 2600);
+ }
+
+ destroy() {
+ clearInterval(this._poll);
+ clearTimeout(this._toastTimer);
+ }
+}
diff --git a/src/studio/skills/skills-catalog.js b/src/studio/skills/skills-catalog.js
new file mode 100644
index 000000000..f30741dfa
--- /dev/null
+++ b/src/studio/skills/skills-catalog.js
@@ -0,0 +1,69 @@
+/**
+ * Agent Studio — shared skills catalog
+ * ====================================
+ * The single source of truth the Studio's Skills and Money tabs read from. Ids
+ * are stored verbatim in the agent's `skills[]` array (and matched by the runtime
+ * + the create-agent wizard), so these must stay in lock-step with the API's
+ * default set and src/create-agent.js.
+ *
+ * `core` skills are always on (the baseline of a working agent) and cannot be
+ * sold individually. `optional` skills are user-toggleable; any of them can be
+ * marked sellable and priced in the Money tab. `sellable: false` marks a skill
+ * that's behavioral-only (no metered call to charge for).
+ */
+
+export const CORE_SKILLS = [
+ { id: 'greet', name: 'Greet', desc: 'Welcomes visitors and opens the conversation.', icon: '👋' },
+ { id: 'present-model', name: 'Present model', desc: 'Shows off and explains its own 3D body.', icon: '🪞' },
+ { id: 'validate-model', name: 'Validate model', desc: 'Checks rig and animation health on load.', icon: '🩺' },
+ { id: 'remember', name: 'Remember', desc: 'Keeps memory across a conversation.', icon: '🧠' },
+ { id: 'think', name: 'Think', desc: 'Reasons step by step before answering.', icon: '✨' },
+];
+
+export const OPTIONAL_SKILLS = [
+ { id: 'wave', name: 'Wave', desc: 'Waves at people on greet or on request.', icon: '🙋', sellable: false },
+ { id: 'dance', name: 'Dance', desc: 'Plays a dance animation loop on cue.', icon: '💃', sellable: false },
+ {
+ id: 'pump-fun',
+ name: 'Pump.fun market intel',
+ desc: 'Read-only Solana market data: tokens, bonding curves, trending, rug-risk.',
+ icon: '📈',
+ sellable: true,
+ },
+ {
+ id: 'explain-gltf',
+ name: 'Explain glTF',
+ desc: 'Narrates mesh, material, and animation info from the scene.',
+ icon: '🔍',
+ sellable: true,
+ },
+ { id: 'web-search', name: 'Web search', desc: 'Looks things up on the live web when asked.', icon: '🌐', sellable: true },
+];
+
+export const ALL_SKILLS = [...CORE_SKILLS, ...OPTIONAL_SKILLS];
+
+const BY_ID = new Map(ALL_SKILLS.map((s) => [s.id, s]));
+
+/** Resolve a skill id to its catalog entry, falling back to a derived label. */
+export function skillMeta(id) {
+ return (
+ BY_ID.get(id) || {
+ id,
+ name: String(id || '')
+ .replace(/[-_]/g, ' ')
+ .replace(/\b\w/g, (c) => c.toUpperCase()),
+ desc: 'Custom skill.',
+ icon: '⚙️',
+ sellable: true,
+ }
+ );
+}
+
+export const CORE_IDS = new Set(CORE_SKILLS.map((s) => s.id));
+
+/** Whether a skill can be metered + sold (core skills and behavior-only skills can't). */
+export function isSellable(id) {
+ if (CORE_IDS.has(id)) return false;
+ const m = BY_ID.get(id);
+ return m ? m.sellable !== false : true;
+}
diff --git a/src/studio/skills/skills-mount.js b/src/studio/skills/skills-mount.js
new file mode 100644
index 000000000..b38075935
--- /dev/null
+++ b/src/studio/skills/skills-mount.js
@@ -0,0 +1,30 @@
+/**
+ * Skills Studio — mount bootstrap (P5)
+ * ====================================
+ * Binds the Skills Studio to the Agent Studio shell's Skills tab on
+ * `studio-shell:ready`. Mirrors P1–P4 mounts: idempotent and order-independent.
+ *
+ * The agent-studio page loads this alongside the shell:
+ * <script type="module" src="/src/studio/skills/skills-mount.js"></script>
+ */
+
+import { studio } from '../agent-studio-store.js';
+import { mountSkillsStudio } from './skills-studio.js';
+
+const SELECTOR = '[data-studio-mount="skills"]';
+
+function mount() {
+ const panel = document.querySelector(SELECTOR);
+ if (!panel || panel.dataset.skillsMounted) return false;
+ mountSkillsStudio(panel, { studio });
+ return true;
+}
+
+document.addEventListener('studio-shell:ready', mount, { once: false });
+
+if (!mount()) {
+ let tries = 0;
+ const t = setInterval(() => {
+ if (mount() || ++tries > 60) clearInterval(t); // ~6s ceiling
+ }, 100);
+}
diff --git a/src/studio/skills/skills-studio.js b/src/studio/skills/skills-studio.js
new file mode 100644
index 000000000..804fd9b8b
--- /dev/null
+++ b/src/studio/skills/skills-studio.js
@@ -0,0 +1,230 @@
+/**
+ * Skills Studio — controller (P5)
+ * ===============================
+ * The capabilities surface of Agent Studio: turn skills on, see which ones are
+ * sellable, and jump to pricing. Core skills are the always-on baseline; optional
+ * skills toggle live and persist to the agent's real `skills[]` array (the same
+ * field the runtime + create-agent wizard read).
+ *
+ * • Core — locked-on foundation (greet, think, remember, …).
+ * • Optional — toggle on/off; the change writes through immediately and the
+ * live avatar acknowledges it. Sellable skills surface their
+ * price (from /api/agents/:id/pricing) and cross-link to Money.
+ *
+ * Mount: import { mountSkillsStudio } from './skills/skills-studio.js';
+ * mountSkillsStudio(container, { studio });
+ */
+
+import { apiFetch } from '../../api.js';
+import { CORE_SKILLS, OPTIONAL_SKILLS, skillMeta, isSellable, CORE_IDS } from './skills-catalog.js';
+
+const esc = (s) => String(s ?? '').replace(/[&<>"']/g, (c) =>
+ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+
+const USDC_DECIMALS = 6;
+const fmtUsdc = (atomic) => (Number(atomic || 0) / 10 ** USDC_DECIMALS);
+
+export function mountSkillsStudio(container, { studio }) {
+ if (container.dataset.skillsMounted) return;
+ container.dataset.skillsMounted = '1';
+ container.querySelector('.studio-empty')?.remove();
+ return new SkillsStudio(container, studio);
+}
+
+class SkillsStudio {
+ constructor(el, studio) {
+ this.el = el;
+ this.studio = studio;
+ this.agentId = studio.agent?.id;
+ this.state = { prices: {}, loadedPrices: false };
+ this._render();
+ this._loadPrices();
+ // React to skills changed elsewhere (e.g. wizard, another tab).
+ this._unsub = this.studio.subscribe(() => this._syncToggles());
+ }
+
+ _q(sel) { return this.el.querySelector(sel); }
+
+ get _skills() {
+ return new Set(this.studio.agent?.skills || []);
+ }
+
+ // Custom skills present on the agent but not in the curated catalog.
+ get _customSkills() {
+ const known = new Set([...CORE_SKILLS, ...OPTIONAL_SKILLS].map((s) => s.id));
+ return [...this._skills].filter((id) => !known.has(id));
+ }
+
+ async _loadPrices() {
+ try {
+ const res = await apiFetch(`/api/agents/${this.agentId}/pricing`, { allowAnonymous: true });
+ if (res.ok) {
+ const { prices = [] } = await res.json();
+ const map = {};
+ for (const p of prices) map[p.skill] = p;
+ this.state.prices = map;
+ }
+ } catch { /* pricing chips are non-critical; cards still render */ }
+ this.state.loadedPrices = true;
+ this._renderPriceChips();
+ }
+
+ // ── Render ────────────────────────────────────────────────────────────────
+
+ _render() {
+ const customs = this._customSkills;
+ this.el.innerHTML = `
+ <div class="skl">
+ <section class="skl-section" aria-labelledby="skl-core-h">
+ <div class="skl-section-head">
+ <h3 id="skl-core-h">Core skills</h3>
+ <p>The always-on baseline every agent runs. These can’t be turned off.</p>
+ </div>
+ <ul class="skl-grid">${CORE_SKILLS.map((s) => this._card(s, { locked: true })).join('')}</ul>
+ </section>
+
+ <section class="skl-section" aria-labelledby="skl-opt-h">
+ <div class="skl-section-head">
+ <h3 id="skl-opt-h">Optional skills</h3>
+ <p>Toggle capabilities on. Sellable ones can be priced in the Money tab.</p>
+ </div>
+ <ul class="skl-grid">${OPTIONAL_SKILLS.map((s) => this._card(s, { locked: false })).join('')}</ul>
+ </section>
+
+ ${
+ customs.length
+ ? `<section class="skl-section" aria-labelledby="skl-custom-h">
+ <div class="skl-section-head"><h3 id="skl-custom-h">Custom skills</h3>
+ <p>Skills added outside the studio. Toggle to keep or remove.</p></div>
+ <ul class="skl-grid">${customs.map((id) => this._card(skillMeta(id), { locked: false })).join('')}</ul>
+ </section>`
+ : ''
+ }
+ </div>
+ <div class="skl-toast" data-toast hidden></div>`;
+ this._bind();
+ this._syncToggles();
+ }
+
+ _card(s, { locked }) {
+ const on = locked || this._skills.has(s.id);
+ const sellable = isSellable(s.id);
+ return `
+ <li class="skl-card ${on ? 'is-on' : ''} ${locked ? 'is-locked' : ''}" data-skill="${esc(s.id)}">
+ <div class="skl-card-icon" aria-hidden="true">${s.icon || '⚙️'}</div>
+ <div class="skl-card-main">
+ <div class="skl-card-top">
+ <span class="skl-card-name">${esc(s.name)}</span>
+ ${sellable ? `<span class="skl-sellable-tag" title="Can be metered and sold">Sellable</span>` : ''}
+ </div>
+ <p class="skl-card-desc">${esc(s.desc)}</p>
+ <div class="skl-card-foot" data-foot>${sellable ? this._priceChip(s.id) : ''}</div>
+ </div>
+ <div class="skl-card-toggle">
+ ${
+ locked
+ ? `<span class="skl-locked-badge" title="Always on">●</span>`
+ : `<button class="skl-switch" role="switch" aria-checked="${on}" data-action="toggle" data-skill="${esc(s.id)}" aria-label="Toggle ${esc(s.name)}"><span class="skl-switch-knob"></span></button>`
+ }
+ </div>
+ </li>`;
+ }
+
+ _priceChip(id) {
+ const enabled = this._skills.has(id) || CORE_IDS.has(id);
+ if (!enabled) return '';
+ const p = this.state.prices[id];
+ if (p) {
+ return `<button class="skl-price-chip is-priced" data-action="go-money" title="Edit price in Money">$${esc(fmtUsdc(p.amount).toFixed(2))}/call ✎</button>`;
+ }
+ if (!this.state.loadedPrices) return `<span class="skl-price-chip is-loading">…</span>`;
+ return `<button class="skl-price-chip" data-action="go-money" title="Set a price">Free · price it →</button>`;
+ }
+
+ _renderPriceChips() {
+ this.el.querySelectorAll('.skl-card').forEach((card) => {
+ const id = card.dataset.skill;
+ if (!isSellable(id)) return;
+ const foot = card.querySelector('[data-foot]');
+ if (foot) foot.innerHTML = this._priceChip(id);
+ });
+ }
+
+ // ── Bind ────────────────────────────────────────────────────────────────────
+
+ _bind() {
+ this.el.addEventListener('click', (e) => {
+ const btn = e.target.closest('[data-action]');
+ if (!btn) return;
+ const a = btn.dataset.action;
+ if (a === 'toggle') return this._toggle(btn.dataset.skill);
+ if (a === 'go-money') return document.dispatchEvent(new CustomEvent('studio:navigate', { detail: { tab: 'money' } }));
+ });
+ // Keyboard: space/enter on a switch toggles it.
+ this.el.addEventListener('keydown', (e) => {
+ const sw = e.target.closest('.skl-switch');
+ if (sw && (e.key === ' ' || e.key === 'Enter')) {
+ e.preventDefault();
+ this._toggle(sw.dataset.skill);
+ }
+ });
+ }
+
+ _toggle(id) {
+ if (!id || CORE_IDS.has(id)) return;
+ const next = new Set(this._skills);
+ const turningOn = !next.has(id);
+ if (turningOn) next.add(id);
+ else next.delete(id);
+ const skills = [...next];
+ this.studio.patch({ skills });
+ this.studio.emit('skills:change', { skill: id, on: turningOn });
+ // Acknowledge on the live avatar: enabling a movement skill previews it.
+ if (turningOn) {
+ const clip = id === 'wave' ? 'wave' : id === 'dance' ? 'dance' : null;
+ const stage = document.querySelector('.studio-stage agent-presence') || document.querySelector('agent-presence');
+ if (clip && stage?.playClip) stage.playClip(clip, { loop: id === 'dance' });
+ else this.studio.emitMarket?.({ type: 'alert' });
+ }
+ this._syncCard(id, turningOn);
+ this._toast(turningOn ? `${skillMeta(id).name} enabled` : `${skillMeta(id).name} turned off`);
+ }
+
+ _syncCard(id, on) {
+ const card = this.el.querySelector(`.skl-card[data-skill="${CSS.escape(id)}"]`);
+ if (!card) return;
+ card.classList.toggle('is-on', on);
+ const sw = card.querySelector('.skl-switch');
+ if (sw) sw.setAttribute('aria-checked', String(on));
+ const foot = card.querySelector('[data-foot]');
+ if (foot && isSellable(id)) foot.innerHTML = this._priceChip(id);
+ }
+
+ // Reconcile toggles with the live store (covers edits from other surfaces).
+ _syncToggles() {
+ const skills = this._skills;
+ this.el.querySelectorAll('.skl-card').forEach((card) => {
+ const id = card.dataset.skill;
+ if (card.classList.contains('is-locked')) return;
+ const on = skills.has(id);
+ card.classList.toggle('is-on', on);
+ const sw = card.querySelector('.skl-switch');
+ if (sw) sw.setAttribute('aria-checked', String(on));
+ });
+ }
+
+ _toast(msg, isError = false) {
+ const t = this._q('[data-toast]');
+ if (!t) return;
+ t.textContent = msg;
+ t.hidden = false;
+ t.className = `skl-toast ${isError ? 'skl-toast-err' : ''} show`;
+ clearTimeout(this._toastTimer);
+ this._toastTimer = setTimeout(() => { t.classList.remove('show'); setTimeout(() => { t.hidden = true; }, 300); }, 2400);
+ }
+
+ destroy() {
+ this._unsub?.();
+ clearTimeout(this._toastTimer);
+ }
+}
diff --git a/vercel.json b/vercel.json
index 40ca89ee0..f7687bf79 100644
--- a/vercel.json
+++ b/vercel.json
@@ -1728,6 +1728,10 @@
"src": "/api/agents/by-wallet",
"dest": "/api/agents/by-wallet"
},
+ {
+ "src": "/api/agents/balances",
+ "dest": "/api/agents/balances"
+ },
{
"src": "/api/agents/by-address/([^/]+)",
"dest": "/api/agents/by-address/[addr]?addr=$1"