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.

Agent net-worth API and aura, money pulse, sniper close; studio shell and animation updates

nirholas1fa55add1eb7
diff --git a/api/agents/networth.js b/api/agents/networth.js
new file mode 100644
index 000000000..5d2c34c5d
--- /dev/null
+++ b/api/agents/networth.js
@@ -0,0 +1,106 @@
+// GET /api/agents/networth?ids=<uuid,uuid,…>&network=mainnet
+// -----------------------------------------------------------
+// Public, read-only batch net-worth lookup that powers wealth legibility in the
+// 3D galaxy (and anywhere a list of agents needs their tiers at once). For each
+// requested agent it resolves the custodial Solana address and returns the real
+// USD net worth of that wallet and the tier it maps to.
+//
+// All real on-chain data: net worth comes from api/_lib/balances.getBalances()
+// — the SAME priced-balance path the wallet uses elsewhere — so a star's tier in
+// the galaxy matches the avatar's aura on its detail page. Balances are cached
+// (Redis when configured), so a galaxy of N agents collapses to mostly cache
+// hits and at most one DAS read per address per cache window. Token balances are
+// public chain data, so no auth is required.
+//
+// Returns { data: { network, items: [{ id, address, usd, tier, level, wealth,
+// hasThree }] } } — agents without a wallet (or whose balance read fails) are
+// simply omitted, so the caller degrades to the clean baseline for them.
+
+import { sql } from '../_lib/db.js';
+import { cors, json, method, wrap, rateLimited, error } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { getBalances, walletUsdTotal } from '../_lib/balances.js';
+import { tierForUsd, THREE_MINT } from '../../src/shared/wallet-networth.js';
+
+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;
+const MAX_IDS = 150;
+const CONCURRENCY = 8;
+
+// Resolve net worth for one agent address, mapped to its tier. Never throws —
+// a failed balance read degrades to a null result the caller can skip.
+async function networthForAddress(address) {
+ try {
+ const balances = await getBalances({ chain: 'solana', address });
+ const usd = walletUsdTotal(balances);
+ const tier = tierForUsd(usd);
+ const hasThree = (balances?.tokens || []).some((t) => t.mint === THREE_MINT && (t.amount || 0) > 0);
+ return { usd, tier: tier.key, level: tier.level, wealth: tier.level / 5, hasThree };
+ } catch {
+ return null;
+ }
+}
+
+// Run `fn` over `items` with bounded concurrency so a large galaxy never opens
+// hundreds of RPC sockets at once.
+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;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, 'http://x');
+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+ const idsRaw = (url.searchParams.get('ids') || '').split(',').map((s) => s.trim()).filter(Boolean);
+ const ids = [...new Set(idsRaw)].filter((id) => UUID_RE.test(id)).slice(0, MAX_IDS);
+
+ if (!ids.length) return json(res, 200, { data: { network, items: [] } });
+
+ // Net worth is denominated in USD across every chain, but the wallet welded to
+ // each agent here is its Solana custodial wallet (the avatar's primary wallet),
+ // so we read Solana balances. Devnet has no priced market, so devnet requests
+ // return addresses with a dormant (0) tier rather than a misleading value.
+ let rows;
+ try {
+ rows = await sql`
+ SELECT id, meta->>'solana_address' AS address
+ FROM agent_identities
+ WHERE id = ANY(${ids}::uuid[]) AND deleted_at IS NULL
+ `;
+ } catch {
+ return error(res, 500, 'db_error', 'could not resolve agents');
+ }
+
+ const withWallets = rows.filter((r) => r.address);
+ if (network === 'devnet') {
+ // Honest: we don't price devnet. Surface the wallet but as dormant tier.
+ return json(res, 200, {
+ data: {
+ network,
+ items: withWallets.map((r) => ({
+ id: r.id, address: r.address, usd: 0, tier: 'dormant', level: 0, wealth: 0, hasThree: false,
+ })),
+ },
+ });
+ }
+
+ const results = await mapPool(withWallets, CONCURRENCY, async (r) => {
+ const nw = await networthForAddress(r.address);
+ return nw ? { id: r.id, address: r.address, ...nw } : null;
+ });
+
+ return json(res, 200, { data: { network, items: results.filter(Boolean) } });
+});
diff --git a/api/pulse.js b/api/pulse.js
new file mode 100644
index 000000000..12c8f81bb
--- /dev/null
+++ b/api/pulse.js
@@ -0,0 +1,460 @@
+// GET /api/pulse — the Money Pulse: a real, platform-wide stream of public
+// wallet activity across every three.ws agent.
+//
+// EVERY row is a real event with an explorer-verifiable signature (or a real
+// launch record). There are NO synthetic events — if the platform is quiet, the
+// feed is honestly empty.
+//
+// Sources (all real):
+// · agent_custody_events — tips received (event_type='tip'), trades + snipes
+// (event_type='spend', category in 'trade'/'snipe'), and agent-to-agent
+// payments (category='x402'). These are already-public, on-chain movements.
+// · pump_agent_mints — coins launched by an agent.
+//
+// Privacy is load-bearing (see prompts/agent-wallets/07): private withdrawals,
+// spend-limit changes, key-recovery and vanity-swap custody events are OWNER-ONLY
+// and NEVER appear here. The global feed also honours each agent's is_public flag
+// and the per-agent `meta.pulse_opt_out` toggle (owner-controlled, server-side).
+//
+// Views:
+// GET /api/pulse — global live feed (keyset paginated)
+// GET /api/pulse?since=<cursor> — delta poll: only events newer than cursor
+// GET /api/pulse?agent_id=<id> — one agent's public "wallet story"
+// GET /api/pulse?view=stats — aggregate money intelligence
+// GET /api/pulse?view=agent-summary&agent_id=<id> — one wallet's lifetime summary
+//
+// Filters: type=all|tips|launches|trades|payments, network=mainnet|devnet.
+
+import { sql } from './_lib/db.js';
+import { cors, json, method, error, serverError, rateLimited } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import { isUuid } from './_lib/validate.js';
+import { publicUrl as r2PublicUrl } from './_lib/r2.js';
+import { explorerTxUrl, explorerAccountUrl } from './_lib/avatar-wallet.js';
+import { cacheGet, cacheSet } from './_lib/cache.js';
+
+// The custody categories that are safe to surface publicly. Everything else
+// (withdraw, vanity_swap, limit_change, key_recover) is owner-private and is
+// excluded by the WHERE clauses below — never add those here.
+const PUBLIC_SPEND_CATEGORIES = ['trade', 'snipe', 'x402'];
+
+// type= query param → the set of `kind`s it admits.
+const TYPE_KINDS = {
+ all: ['tip', 'trade', 'snipe', 'payment', 'launch'],
+ tips: ['tip'],
+ trades: ['trade', 'snipe'],
+ payments: ['payment'],
+ launches: ['launch'],
+};
+
+const FEED_TTL_S = 12; // global feed page cache (short — it's a live feed)
+const STATS_TTL_S = 45; // aggregate stats cache
+const MAX_LIMIT = 60;
+
+// Keyset cursor = base64("<epoch_ms>|<row_id>"). row_id is the unified id of the
+// last row on a page; comparing (ts, row_id) gives a stable total order across
+// the UNION so pagination never skips or duplicates a row.
+function encodeCursor(tsIso, rowId) {
+ const ms = new Date(tsIso).getTime();
+ return Buffer.from(`${ms}|${rowId}`, 'utf8').toString('base64url');
+}
+function decodeCursor(raw) {
+ if (!raw || typeof raw !== 'string') return null;
+ try {
+ const [ms, rowId] = Buffer.from(raw, 'base64url').toString('utf8').split('|');
+ const n = Number(ms);
+ if (!Number.isFinite(n) || !rowId) return null;
+ return { ts: new Date(n).toISOString(), rowId };
+ } catch {
+ return null;
+ }
+}
+
+const r2Url = (key, visible) =>
+ key && visible ? r2PublicUrl(key) : null;
+
+// Shape one DB row into the public pulse event the client renders. Pure.
+function shapeEvent(r) {
+ const avatarPublic = r.avatar_vis === 'public' || r.avatar_vis === 'unlisted';
+ const amountLamports = r.amount_lamports != null ? String(r.amount_lamports) : null;
+ const amountRaw = r.amount_raw != null ? String(r.amount_raw) : null;
+ const sol = amountLamports != null ? Number(amountLamports) / 1e9 : null;
+ const usd = r.usd != null ? Number(r.usd) : null;
+ const sig = r.signature || null;
+ return {
+ id: r.row_id,
+ kind: r.kind, // tip | trade | snipe | payment | launch
+ ts: r.ts,
+ network: r.network,
+ agent: r.agent_id
+ ? {
+ id: r.agent_id,
+ name: r.agent_name || 'Agent',
+ url: `/agent/${r.agent_id}`,
+ avatar_thumbnail_url: r2Url(r.thumb_key, avatarPublic),
+ solana_address: r.agent_addr || null,
+ solana_vanity_prefix: r.vanity_prefix || null,
+ solana_vanity_suffix: r.vanity_suffix || null,
+ }
+ : null,
+ asset: r.asset || null,
+ amount_lamports: amountLamports,
+ amount_raw: amountRaw,
+ sol,
+ usd,
+ signature: sig,
+ explorer: sig ? explorerTxUrl(sig, r.network) : null,
+ // launch-only fields
+ mint: r.mint || null,
+ symbol: r.symbol || null,
+ coin_name: r.coin_name || null,
+ mint_explorer: r.mint ? explorerAccountUrl(r.mint, r.network) : null,
+ // the counterparty of a tip / payment, when public on-chain
+ counterparty: r.counterparty || null,
+ };
+}
+
+// ── feed view ───────────────────────────────────────────────────────────────
+async function handleFeed(req, res, { network, type, agentId, cursor, since }) {
+ const kinds = TYPE_KINDS[type] || TYPE_KINDS.all;
+ const limit = Math.min(MAX_LIMIT, Math.max(1, Number(new URL(req.url, 'http://x').searchParams.get('limit')) || 30));
+
+ // Global feed: gate by is_public + the per-agent opt-out. Agent-scoped feed
+ // (a specific wallet's public "story"): the events are all already public
+ // on-chain, so we show them regardless of the global-feed opt-out — that
+ // toggle governs inclusion in the aggregated discovery feed, not whether an
+ // agent's own page may show its public history. Deleted agents are always out.
+ const visGate = agentId
+ ? sql`ai.deleted_at IS NULL`
+ : sql`ai.deleted_at IS NULL AND ai.is_public = true AND COALESCE((ai.meta->>'pulse_opt_out')::boolean, false) = false`;
+
+ const agentFilterCe = agentId ? sql`AND ce.agent_id = ${agentId}` : sql``;
+ const agentFilterPam = agentId ? sql`AND pam.agent_id = ${agentId}` : sql``;
+
+ // One UNION ALL of identical columns. Casts on the launch side make the null
+ // columns type-compatible with the custody side.
+ const feedCte = sql`
+ SELECT
+ ce.created_at AS ts,
+ (CASE
+ WHEN ce.event_type = 'tip' THEN 'tip'
+ WHEN ce.category = 'x402' THEN 'payment'
+ WHEN ce.category = 'snipe' THEN 'snipe'
+ ELSE 'trade'
+ END) AS kind,
+ 'c' || ce.id::text AS row_id,
+ ce.network AS network,
+ ai.id AS agent_id,
+ ai.name AS agent_name,
+ ai.meta->>'solana_address' AS agent_addr,
+ ai.meta->>'solana_vanity_prefix' AS vanity_prefix,
+ ai.meta->>'solana_vanity_suffix' AS vanity_suffix,
+ av.thumbnail_key AS thumb_key,
+ av.visibility AS avatar_vis,
+ ce.asset AS asset,
+ ce.amount_lamports AS amount_lamports,
+ ce.amount_raw AS amount_raw,
+ ce.usd AS usd,
+ ce.signature AS signature,
+ NULL::text AS mint,
+ NULL::text AS symbol,
+ NULL::text AS coin_name,
+ NULLIF(ce.meta->>'from', '') AS counterparty
+ FROM agent_custody_events ce
+ JOIN agent_identities ai ON ai.id = ce.agent_id AND ${visGate}
+ LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL
+ WHERE ce.network = ${network}
+ AND ce.status IN ('ok', 'confirmed')
+ AND (
+ ce.event_type = 'tip'
+ OR (ce.event_type = 'spend' AND ce.category = ANY(${PUBLIC_SPEND_CATEGORIES}))
+ )
+ ${agentFilterCe}
+
+ UNION ALL
+
+ SELECT
+ pam.created_at AS ts,
+ 'launch' AS kind,
+ 'l' || pam.id::text AS row_id,
+ pam.network AS network,
+ ai.id AS agent_id,
+ ai.name AS agent_name,
+ ai.meta->>'solana_address' AS agent_addr,
+ ai.meta->>'solana_vanity_prefix' AS vanity_prefix,
+ ai.meta->>'solana_vanity_suffix' AS vanity_suffix,
+ av.thumbnail_key AS thumb_key,
+ av.visibility AS avatar_vis,
+ NULL::text AS asset,
+ NULL::bigint AS amount_lamports,
+ NULL::numeric AS amount_raw,
+ NULL::numeric AS usd,
+ NULL::text AS signature,
+ pam.mint AS mint,
+ pam.symbol AS symbol,
+ pam.name AS coin_name,
+ NULL::text AS counterparty
+ FROM pump_agent_mints pam
+ JOIN agent_identities ai ON ai.id = pam.agent_id AND ${visGate}
+ LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL
+ WHERE pam.network = ${network}
+ ${agentFilterPam}
+ `;
+
+ // Keyset bounds. `since` (delta poll) returns only rows strictly newer than
+ // the cursor; `cursor` (load-older) returns rows strictly older. Both compare
+ // on (ts, row_id) so ties at the same timestamp never skip a row.
+ const cur = decodeCursor(cursor);
+ const sinceCur = decodeCursor(since);
+ const olderBound = cur
+ ? sql`AND (feed.ts < ${cur.ts} OR (feed.ts = ${cur.ts} AND feed.row_id < ${cur.rowId}))`
+ : sql``;
+ const newerBound = sinceCur
+ ? sql`AND (feed.ts > ${sinceCur.ts} OR (feed.ts = ${sinceCur.ts} AND feed.row_id > ${sinceCur.rowId}))`
+ : sql``;
+
+ const rows = await sql`
+ WITH feed AS (${feedCte})
+ SELECT * FROM feed
+ WHERE feed.kind = ANY(${kinds})
+ ${olderBound}
+ ${newerBound}
+ ORDER BY feed.ts DESC, feed.row_id DESC
+ LIMIT ${limit + 1}
+ `;
+
+ const hasMore = rows.length > limit;
+ const page = rows.slice(0, limit).map(shapeEvent);
+ const last = page[page.length - 1];
+ const nextCursor = hasMore && last ? encodeCursor(last.ts, last.id) : null;
+ // The newest row's cursor — clients hand it back as `since` to poll the delta.
+ const headCursor = page[0] ? encodeCursor(page[0].ts, page[0].id) : (sinceCur ? since : null);
+
+ return {
+ events: page,
+ has_more: hasMore,
+ next_cursor: nextCursor,
+ head_cursor: headCursor,
+ network,
+ type,
+ agent_id: agentId || null,
+ };
+}
+
+// ── aggregate stats view ──────────────────────────────────────────────────────
+async function handleStats(network) {
+ // 24h tip flow (count + SOL + USD where priced), platform-wide, public agents.
+ const [tip24] = await sql`
+ SELECT
+ COUNT(*)::int AS count,
+ COALESCE(SUM(ce.amount_lamports), 0)::text AS lamports,
+ COALESCE(SUM(ce.usd), 0)::float8 AS usd
+ FROM agent_custody_events ce
+ JOIN agent_identities ai ON ai.id = ce.agent_id
+ AND ai.deleted_at IS NULL AND ai.is_public = true
+ AND COALESCE((ai.meta->>'pulse_opt_out')::boolean, false) = false
+ WHERE ce.network = ${network} AND ce.event_type = 'tip'
+ AND ce.status IN ('ok', 'confirmed')
+ AND ce.created_at > now() - interval '24 hours'
+ `;
+
+ // Top earning agents by tips received (rolling 7d). Lifetime would bury new
+ // agents under early movers; 7d keeps "who's hot right now" honest.
+ const topEarners = await sql`
+ SELECT ai.id AS agent_id, ai.name AS agent_name,
+ av.thumbnail_key AS thumb_key, av.visibility AS avatar_vis,
+ ai.meta->>'solana_address' AS agent_addr,
+ COUNT(*)::int AS tip_count,
+ COALESCE(SUM(ce.amount_lamports), 0)::text AS lamports,
+ COALESCE(SUM(ce.usd), 0)::float8 AS usd
+ FROM agent_custody_events ce
+ JOIN agent_identities ai ON ai.id = ce.agent_id
+ AND ai.deleted_at IS NULL AND ai.is_public = true
+ AND COALESCE((ai.meta->>'pulse_opt_out')::boolean, false) = false
+ LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL
+ WHERE ce.network = ${network} AND ce.event_type = 'tip'
+ AND ce.status IN ('ok', 'confirmed')
+ AND ce.created_at > now() - interval '7 days'
+ GROUP BY ai.id, ai.name, av.thumbnail_key, av.visibility, ai.meta->>'solana_address'
+ ORDER BY SUM(COALESCE(ce.usd, ce.amount_lamports / 1e9 * 0)) DESC NULLS LAST,
+ SUM(ce.amount_lamports) DESC NULLS LAST
+ LIMIT 6
+ `;
+
+ // Busiest wallets — most public events (any kind) in the last 24h.
+ const busiest = await sql`
+ SELECT ai.id AS agent_id, ai.name AS agent_name,
+ av.thumbnail_key AS thumb_key, av.visibility AS avatar_vis,
+ ai.meta->>'solana_address' AS agent_addr,
+ COUNT(*)::int AS events
+ FROM agent_custody_events ce
+ JOIN agent_identities ai ON ai.id = ce.agent_id
+ AND ai.deleted_at IS NULL AND ai.is_public = true
+ AND COALESCE((ai.meta->>'pulse_opt_out')::boolean, false) = false
+ LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL
+ WHERE ce.network = ${network}
+ AND ce.status IN ('ok', 'confirmed')
+ AND (ce.event_type = 'tip' OR (ce.event_type = 'spend' AND ce.category = ANY(${PUBLIC_SPEND_CATEGORIES})))
+ AND ce.created_at > now() - interval '24 hours'
+ GROUP BY ai.id, ai.name, av.thumbnail_key, av.visibility, ai.meta->>'solana_address'
+ ORDER BY COUNT(*) DESC
+ LIMIT 6
+ `;
+
+ // Launch + trade tempo for the headline counters.
+ const [launch24] = await sql`
+ SELECT COUNT(*)::int AS count
+ FROM pump_agent_mints pam
+ JOIN agent_identities ai ON ai.id = pam.agent_id
+ AND ai.deleted_at IS NULL AND ai.is_public = true
+ AND COALESCE((ai.meta->>'pulse_opt_out')::boolean, false) = false
+ WHERE pam.network = ${network} AND pam.created_at > now() - interval '24 hours'
+ `;
+ const [trade24] = await sql`
+ SELECT COUNT(*)::int AS count
+ FROM agent_custody_events ce
+ JOIN agent_identities ai ON ai.id = ce.agent_id
+ AND ai.deleted_at IS NULL AND ai.is_public = true
+ AND COALESCE((ai.meta->>'pulse_opt_out')::boolean, false) = false
+ WHERE ce.network = ${network} AND ce.event_type = 'spend'
+ AND ce.category = ANY(${PUBLIC_SPEND_CATEGORIES})
+ AND ce.status IN ('ok', 'confirmed')
+ AND ce.created_at > now() - interval '24 hours'
+ `;
+
+ const shapeAgent = (r) => ({
+ id: r.agent_id,
+ name: r.agent_name || 'Agent',
+ url: `/agent/${r.agent_id}`,
+ avatar_thumbnail_url: r2Url(r.thumb_key, r.avatar_vis === 'public' || r.avatar_vis === 'unlisted'),
+ solana_address: r.agent_addr || null,
+ tip_count: r.tip_count != null ? Number(r.tip_count) : undefined,
+ events: r.events != null ? Number(r.events) : undefined,
+ sol: r.lamports != null ? Number(r.lamports) / 1e9 : undefined,
+ usd: r.usd != null ? Number(r.usd) : undefined,
+ });
+
+ return {
+ network,
+ tips_24h: {
+ count: Number(tip24?.count || 0),
+ sol: Number(tip24?.lamports || 0) / 1e9,
+ usd: Number(tip24?.usd || 0),
+ },
+ launches_24h: Number(launch24?.count || 0),
+ trades_24h: Number(trade24?.count || 0),
+ top_earners: topEarners.map(shapeAgent),
+ busiest_wallets: busiest.map(shapeAgent),
+ };
+}
+
+// ── per-agent lifetime summary ─────────────────────────────────────────────────
+async function handleAgentSummary(network, agentId) {
+ const [agent] = await sql`
+ SELECT id, name, deleted_at FROM agent_identities WHERE id = ${agentId}
+ `;
+ if (!agent || agent.deleted_at) return null;
+
+ const [tips] = await sql`
+ SELECT COUNT(*)::int AS count,
+ COALESCE(SUM(amount_lamports), 0)::text AS lamports,
+ COALESCE(SUM(usd), 0)::float8 AS usd,
+ COALESCE(MAX(amount_lamports), 0)::text AS biggest_lamports,
+ COALESCE(MAX(usd), 0)::float8 AS biggest_usd
+ FROM agent_custody_events
+ WHERE agent_id = ${agentId} AND network = ${network}
+ AND event_type = 'tip' AND status IN ('ok', 'confirmed')
+ `;
+ // Public outflow = trades + snipes + agent-to-agent payments (never withdraws).
+ const [outflow] = await sql`
+ SELECT COUNT(*)::int AS count,
+ COALESCE(SUM(amount_lamports), 0)::text AS lamports,
+ COALESCE(SUM(usd), 0)::float8 AS usd
+ FROM agent_custody_events
+ WHERE agent_id = ${agentId} AND network = ${network}
+ AND event_type = 'spend' AND category = ANY(${PUBLIC_SPEND_CATEGORIES})
+ AND status IN ('ok', 'confirmed')
+ `;
+ const [launches] = await sql`
+ SELECT COUNT(*)::int AS count FROM pump_agent_mints
+ WHERE agent_id = ${agentId} AND network = ${network}
+ `;
+
+ return {
+ agent_id: agentId,
+ network,
+ tips: {
+ count: Number(tips?.count || 0),
+ sol: Number(tips?.lamports || 0) / 1e9,
+ usd: Number(tips?.usd || 0),
+ biggest_sol: Number(tips?.biggest_lamports || 0) / 1e9,
+ biggest_usd: Number(tips?.biggest_usd || 0),
+ },
+ outflow: {
+ count: Number(outflow?.count || 0),
+ sol: Number(outflow?.lamports || 0) / 1e9,
+ usd: Number(outflow?.usd || 0),
+ },
+ launches: Number(launches?.count || 0),
+ };
+}
+
+export default async function handler(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, 'http://x');
+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';
+ const view = url.searchParams.get('view') || 'feed';
+ const agentId = url.searchParams.get('agent_id') || null;
+ if (agentId && !isUuid(agentId)) return error(res, 400, 'validation_error', 'agent_id must be a uuid');
+ const typeRaw = url.searchParams.get('type') || 'all';
+ const type = TYPE_KINDS[typeRaw] ? typeRaw : 'all';
+ const cursor = url.searchParams.get('cursor');
+ const since = url.searchParams.get('since');
+
+ try {
+ if (view === 'stats') {
+ const cacheKey = `pulse:stats:${network}`;
+ let body = await cacheGet(cacheKey);
+ if (body === null) {
+ body = await handleStats(network);
+ await cacheSet(cacheKey, body, STATS_TTL_S);
+ }
+ res.setHeader('cache-control', 'public, max-age=20');
+ return json(res, 200, { data: body });
+ }
+
+ if (view === 'agent-summary') {
+ if (!agentId) return error(res, 400, 'validation_error', 'agent_id is required for agent-summary');
+ const body = await handleAgentSummary(network, agentId);
+ if (!body) return error(res, 404, 'not_found', 'agent not found');
+ res.setHeader('cache-control', 'public, max-age=20');
+ return json(res, 200, { data: body });
+ }
+
+ // Default: feed. A delta poll (`since`) is never cached — it must be live.
+ // A first page (no cursor/since) of the GLOBAL feed is cached briefly to
+ // shield the DB from a thundering herd of pollers.
+ const isFirstGlobalPage = !cursor && !since && !agentId;
+ if (isFirstGlobalPage) {
+ const cacheKey = `pulse:feed:${network}:${type}`;
+ let body = await cacheGet(cacheKey);
+ if (body === null) {
+ body = await handleFeed(req, res, { network, type, agentId, cursor, since });
+ await cacheSet(cacheKey, body, FEED_TTL_S);
+ }
+ res.setHeader('cache-control', 'public, max-age=8');
+ return json(res, 200, { data: body });
+ }
+
+ const body = await handleFeed(req, res, { network, type, agentId, cursor, since });
+ return json(res, 200, { data: body });
+ } catch (e) {
+ console.error('[api/pulse] failed', e?.message, e?.stack);
+ return serverError(res, 502, 'pulse_failed', e);
+ }
+}
diff --git a/api/sniper/close.js b/api/sniper/close.js
new file mode 100644
index 000000000..c16813e46
--- /dev/null
+++ b/api/sniper/close.js
@@ -0,0 +1,196 @@
+/**
+ * Agent Sniper — manual position close (one-tap "Sell now").
+ *
+ * POST /api/sniper/close → owner force-closes ONE open sniper position now.
+ *
+ * The autonomous worker already exits on take-profit / stop-loss / trailing /
+ * timeout, and the kill switch exits EVERY position. This endpoint is the missing
+ * per-position lever: the owner taps "Sell now" on a single live position and the
+ * agent sells its full holding of that mint immediately, at a real price, with a
+ * real signature.
+ *
+ * It reuses the worker's own `executeSell` — the single module that signs and
+ * broadcasts — so the manual exit takes the exact same path as an automated one:
+ * fresh re-quote, graduation→AMM routing, the protected execution engine, the
+ * realized-PnL write, and the custody/audit + Telegram notification. No trade
+ * logic is duplicated, so manual and automatic exits can never drift apart.
+ *
+ * Owner-only (the position's user_id must equal the caller). Selling moves SOL
+ * INWARD, so — like every sell path — it is deliberately not gated by the spend
+ * ceilings or the wallet freeze: getting out is always the safe direction.
+ *
+ * Auth: session cookie OR bearer token. CSRF required on this fund-moving write.
+ */
+
+import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { requireCsrf } from '../_lib/csrf.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { sql } from '../_lib/db.js';
+import { explorerTxUrl } from '../_lib/avatar-wallet.js';
+import { executeSell } from '../../workers/agent-sniper/executor.js';
+import { z } from 'zod';
+
+const CONFIRM_TIMEOUT_MS = 45_000;
+
+const BODY = z.object({
+ agent_id: z.string().uuid(),
+ network: z.enum(['mainnet', 'devnet']).default('mainnet'),
+ // One of these identifies the position. position_id is exact; mint is the
+ // friendlier handle from the live-positions UI (unique per agent+network).
+ position_id: z.string().uuid().optional(),
+ mint: z.string().min(32).max(44).optional(),
+});
+
+async function resolveUserId(req) {
+ const session = await getSessionUser(req);
+ if (session) return session.id;
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return bearer.userId;
+ return null;
+}
+
+export default async function handler(req, res) {
+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['POST'])) return;
+
+ const userId = await resolveUserId(req);
+ if (!userId) return error(res, 401, 'unauthorized', 'sign in to manage the sniper');
+
+ const rlUser = await limits.tradePerUser(userId);
+ if (!rlUser.success) return rateLimited(res, rlUser);
+ const rlIp = await limits.authIp(clientIp(req));
+ if (!rlIp.success) return rateLimited(res, rlIp);
+
+ let raw;
+ try {
+ raw = await readJson(req);
+ } catch (e) {
+ return error(res, e?.status === 415 ? 415 : 400, 'bad_request', e?.message || 'invalid request body');
+ }
+ const parsed = BODY.safeParse(raw);
+ if (!parsed.success) {
+ return error(res, 400, 'bad_request', parsed.error.issues[0]?.message || 'invalid request');
+ }
+ const { agent_id, network, position_id, mint } = parsed.data;
+ if (!position_id && !mint) {
+ return error(res, 400, 'bad_request', 'provide a position_id or a mint to close');
+ }
+
+ if (!(await requireCsrf(req, res, userId))) return;
+
+ // Atomically CLAIM the open position by flipping it to 'closing'. Owner-scoped
+ // by user_id. This both authorizes the caller (no row → not theirs / not open)
+ // and serializes against the worker's own sweep, so a manual close and an
+ // automatic exit can never both fire a sell for the same bag: only the txn that
+ // finds the row still 'open' wins the flip.
+ const [claim] = await sql`
+ UPDATE agent_sniper_positions
+ SET status = 'closing'
+ WHERE id = (
+ SELECT id FROM agent_sniper_positions
+ WHERE agent_id = ${agent_id}
+ AND user_id = ${userId}
+ AND network = ${network}
+ AND status = 'open'
+ AND (${position_id ?? null}::uuid IS NULL OR id = ${position_id ?? null})
+ AND (${mint ?? null}::text IS NULL OR mint = ${mint ?? null})
+ ORDER BY opened_at DESC NULLS LAST
+ LIMIT 1
+ )
+ AND status = 'open'
+ RETURNING id, agent_id, user_id, network, mint, symbol, name,
+ base_amount, entry_quote_lamports, error
+ `;
+
+ if (!claim) {
+ // Distinguish "nothing open" from "someone else is already closing it" so the
+ // UI message is honest.
+ const [existing] = await sql`
+ SELECT status FROM agent_sniper_positions
+ WHERE agent_id = ${agent_id} AND user_id = ${userId} AND network = ${network}
+ AND (${position_id ?? null}::uuid IS NULL OR id = ${position_id ?? null})
+ AND (${mint ?? null}::text IS NULL OR mint = ${mint ?? null})
+ ORDER BY opened_at DESC NULLS LAST
+ LIMIT 1
+ `;
+ if (existing?.status === 'closing') {
+ return error(res, 409, 'position_busy', 'this position is already being closed — give it a moment');
+ }
+ if (existing?.status === 'closed') {
+ return error(res, 409, 'already_closed', 'this position is already closed');
+ }
+ return error(res, 404, 'not_found', 'no open position found for that agent on this network');
+ }
+
+ // Enrich the claimed position with the fields executeSell uses for slippage,
+ // notifications, and the audit name. The positions table stores none of these
+ // (slippage + Telegram live on the strategy; the display name on the agent),
+ // so read them once now that ownership + the claim are settled.
+ const [meta] = await sql`
+ SELECT a.name AS agent_name, s.slippage_bps, s.telegram_chat_id
+ FROM agent_identities a
+ LEFT JOIN agent_sniper_strategies s ON s.agent_id = a.id AND s.network = ${network}
+ WHERE a.id = ${claim.agent_id}
+ LIMIT 1
+ `;
+ const pos = {
+ ...claim,
+ agent_name: meta?.agent_name || null,
+ slippage_bps: meta?.slippage_bps ?? null,
+ telegram_chat_id: meta?.telegram_chat_id ?? null,
+ };
+
+ if (!pos.base_amount || BigInt(pos.base_amount) <= 0n) {
+ // A position with no recorded token balance can't be sold; reopen it so the
+ // claim doesn't strand the row in 'closing'.
+ await sql`UPDATE agent_sniper_positions SET status = 'open' WHERE id = ${pos.id} AND status = 'closing'`.catch(() => {});
+ return error(res, 409, 'not_sellable', 'this position has no token balance to sell yet — try again in a moment');
+ }
+
+ const cfg = {
+ network,
+ mode: process.env.SNIPER_MODE === 'simulate' ? 'simulate' : 'live',
+ confirmTimeoutMs: CONFIRM_TIMEOUT_MS,
+ };
+
+ let result;
+ try {
+ // executeSell re-reads status with its own `WHERE status='open'` guard (a
+ // no-op now that we hold the 'closing' claim) and then sells, writing the
+ // realized PnL + sell_sig and flipping the row to 'closed'. On failure it
+ // reopens the position itself so a later retry (worker or owner) can exit.
+ result = await executeSell({ cfg, position: pos, reason: 'manual' });
+ } catch (e) {
+ await sql`UPDATE agent_sniper_positions SET status = 'open', error = ${'manual_close_failed'} WHERE id = ${pos.id} AND status = 'closing'`.catch(() => {});
+ return error(res, 502, 'sell_failed', 'the sell could not be submitted and no funds were moved — try again');
+ }
+
+ if (result.status === 'closed') {
+ const live = result.sig && result.sig !== 'SIMULATED';
+ const pnlSol = Number(BigInt(result.pnl || '0')) / 1e9;
+ return json(res, 200, {
+ data: {
+ status: 'closed',
+ agent_id: pos.agent_id,
+ mint: pos.mint,
+ symbol: pos.symbol || null,
+ venue: result.venue || null,
+ pnl_sol: pnlSol,
+ simulated: !live,
+ signature: live ? result.sig : null,
+ explorer: live ? explorerTxUrl(result.sig, network) : null,
+ },
+ });
+ }
+
+ // executeSell already reopened the position on a retry/failure outcome.
+ if (result.status === 'retry') {
+ return error(res, 502, 'sell_retry', 'the sell did not land — the position is still open, try again in a moment', {
+ reason: result.reason || null,
+ });
+ }
+ return error(res, 502, 'sell_failed', `the sell did not complete (${result.reason || result.status})`, {
+ reason: result.reason || null,
+ });
+}
diff --git a/pages/agent-studio.html b/pages/agent-studio.html
index a156ab8c2..fd2c94f3b 100644
--- a/pages/agent-studio.html
+++ b/pages/agent-studio.html
@@ -26,6 +26,7 @@
<link rel="stylesheet" href="/buttons.css" />
<link rel="stylesheet" href="/brain-studio.css" />
<link rel="stylesheet" href="/memory-studio.css" />
+ <link rel="stylesheet" href="/studio-panels.css" />
<style>
/* Base reset: this page deliberately skips style.css, so it must carry
@@ -418,5 +419,11 @@
<script type="module" src="/src/studio/brain/brain-mount.js"></script>
<!-- P2: Memory Studio binds itself to the shell's Memory tab on studio-shell:ready. -->
<script type="module" src="/src/studio/memory/memory-mount.js"></script>
+ <!-- P3: Body Studio binds itself to the shell's Body tab on studio-shell:ready. -->
+ <script type="module" src="/src/studio/body/body-mount.js"></script>
+ <!-- P4: Money Studio binds itself to the shell's Money tab on studio-shell:ready. -->
+ <script type="module" src="/src/studio/money/money-mount.js"></script>
+ <!-- P5: Skills Studio binds itself to the shell's Skills tab on studio-shell:ready. -->
+ <script type="module" src="/src/studio/skills/skills-mount.js"></script>
</body>
</html>
diff --git a/public/studio-panels.css b/public/studio-panels.css
new file mode 100644
index 000000000..20dc2deb6
--- /dev/null
+++ b/public/studio-panels.css
@@ -0,0 +1,477 @@
+/* ════════════════════════════════════════════════════════════════════════════
+ * Agent Studio — Body · Money · Skills panels (P3–P5)
+ * ════════════════════════════════════════════════════════════════════════════
+ * Shared styling for the three sub-studios that mount into the shell's tab
+ * panels. Uses the same design-token vocabulary as agent-studio.html / the Brain
+ * + Memory studios so the five tabs feel like one product. Each tab owns a class
+ * prefix: .bdy (Body), .mny (Money), .skl (Skills).
+ */
+
+/* ── Shared section scaffolding ──────────────────────────────────────────── */
+.bdy-section,
+.mny-section,
+.skl-section {
+ margin-bottom: var(--space-xl, 2.618rem);
+}
+.bdy-section:last-child,
+.mny-section:last-child,
+.skl-section:last-child {
+ margin-bottom: 0;
+}
+.bdy-section-head h3,
+.mny-section-head h3,
+.skl-section-head h3 {
+ margin: 0 0 2px;
+ font-family: var(--font-display);
+ font-size: var(--text-lg, 1.236rem);
+ color: var(--ink-bright, #fff);
+}
+.bdy-section-head p,
+.mny-section-head p,
+.skl-section-head p {
+ margin: 0 0 var(--space-md, 1rem);
+ font-size: var(--text-md, 0.8125rem);
+ line-height: var(--leading-normal, 1.618);
+ color: var(--ink-dim, #888);
+}
+
+/* Shared inline empty / error states */
+.bdy-empty,
+.mny-empty,
+.mny-inline-empty,
+.skl-inline-empty {
+ text-align: center;
+ color: var(--ink-dim, #888);
+ padding: var(--space-lg, 1.618rem);
+}
+.bdy-empty h3,
+.mny-empty h3 {
+ margin: 8px 0 6px;
+ font-family: var(--font-display);
+ color: var(--ink-bright, #fff);
+}
+.bdy-empty-glyph,
+.mny-empty-glyph {
+ width: 48px;
+ height: 48px;
+ margin: 0 auto var(--space-sm);
+ display: grid;
+ place-items: center;
+ font-size: 22px;
+ border-radius: var(--radius-lg, 14px);
+ background: var(--surface-2, rgba(255, 255, 255, 0.05));
+ border: 1px solid var(--stroke);
+ color: var(--ink-dim);
+}
+.mny-empty-glyph.small { width: 38px; height: 38px; font-size: 18px; }
+.mny-inline-empty p,
+.skl-inline-empty p { margin: 0 0 10px; font-size: var(--text-md, 0.8125rem); }
+
+/* ════════════════════════════════════════════════════════════════════════════
+ * BODY
+ * ══════════════════════════════════════════════════════════════════════════ */
+.bdy-avatar-card {
+ display: flex;
+ gap: var(--space-md, 1rem);
+ align-items: center;
+ padding: var(--space-md, 1rem);
+ border-radius: var(--radius-lg, 14px);
+ background: var(--surface-1, rgba(255, 255, 255, 0.03));
+ border: 1px solid var(--stroke);
+}
+.bdy-avatar-thumb {
+ flex: 0 0 auto;
+ width: 84px;
+ height: 84px;
+ border-radius: var(--radius-md, 10px);
+ overflow: hidden;
+ background:
+ radial-gradient(120% 90% at 50% 0%, rgba(139, 92, 246, 0.18), transparent 65%),
+ var(--surface-3, rgba(255, 255, 255, 0.06));
+ display: grid;
+ place-items: center;
+ border: 1px solid var(--stroke);
+}
+.bdy-avatar-thumb img { width: 100%; height: 100%; object-fit: cover; }
+.bdy-avatar-fallback { font-size: 32px; color: var(--ink-faint, #666); }
+.bdy-avatar-meta { display: flex; flex-direction: column; gap: 3px; min-width: 0; }
+.bdy-avatar-name {
+ font-weight: var(--weight-bold, 700);
+ font-size: var(--text-base, 1rem);
+ color: var(--ink-bright, #fff);
+}
+.bdy-avatar-sub { font-size: var(--text-md, 0.8125rem); color: var(--ink-dim, #888); }
+.bdy-avatar-actions { display: flex; flex-wrap: wrap; gap: var(--space-sm, 0.618rem); margin-top: 8px; }
+.bdy-avatar-actions .studio-action { margin-top: 0; }
+
+/* Resting pose readout */
+.bdy-resting {
+ display: inline-flex;
+ align-items: center;
+ gap: 8px;
+ padding: 6px 12px;
+ margin-bottom: var(--space-md, 1rem);
+ border-radius: var(--radius-pill, 999px);
+ background: var(--surface-2, rgba(255, 255, 255, 0.05));
+ border: 1px solid var(--stroke);
+}
+.bdy-resting-label { font-size: var(--text-2xs, 0.6875rem); color: var(--ink-dim); text-transform: uppercase; letter-spacing: 0.06em; }
+.bdy-resting-val { font-size: var(--text-md, 0.8125rem); font-weight: var(--weight-semibold, 600); color: var(--accent, #a78bfa); }
+
+/* Featured + category clip grids */
+.bdy-featured {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
+ gap: 8px;
+ margin-bottom: var(--space-md, 1rem);
+}
+.bdy-grid {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(120px, 1fr));
+ gap: 8px;
+ padding: 10px 0 4px;
+}
+.bdy-cat { border-top: 1px solid var(--stroke); }
+.bdy-cat-summary {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ padding: 11px 2px;
+ cursor: pointer;
+ font-weight: var(--weight-semibold, 600);
+ font-size: var(--text-ui, 0.875rem);
+ color: var(--ink, #e8e8e8);
+ list-style: none;
+ user-select: none;
+}
+.bdy-cat-summary::-webkit-details-marker { display: none; }
+.bdy-cat-summary:hover { color: var(--ink-bright, #fff); }
+.bdy-cat-count {
+ font-size: var(--text-2xs, 0.6875rem);
+ color: var(--ink-dim);
+ background: var(--surface-3, rgba(255, 255, 255, 0.08));
+ border-radius: var(--radius-pill, 999px);
+ padding: 1px 8px;
+}
+
+.bdy-chip {
+ position: relative;
+ display: flex;
+ border-radius: var(--radius-md, 10px);
+ background: var(--surface-1, rgba(255, 255, 255, 0.03));
+ border: 1px solid var(--stroke);
+ overflow: hidden;
+ transition: border-color var(--duration-fast, 140ms) var(--ease-standard), background var(--duration-fast) var(--ease-standard), transform var(--duration-fast) var(--ease-standard);
+}
+.bdy-chip:hover { border-color: var(--stroke-strong, rgba(255, 255, 255, 0.2)); background: var(--surface-2); }
+.bdy-chip--featured { background: var(--surface-2, rgba(255, 255, 255, 0.05)); }
+.bdy-chip--playing { border-color: var(--accent, #a78bfa); box-shadow: 0 0 0 1px var(--accent, #a78bfa) inset; }
+.bdy-chip--resting { border-color: rgba(139, 92, 246, 0.5); }
+.bdy-chip-play {
+ flex: 1;
+ display: flex;
+ flex-direction: column;
+ align-items: flex-start;
+ gap: 4px;
+ appearance: none;
+ background: transparent;
+ border: none;
+ cursor: pointer;
+ padding: 10px 11px;
+ color: var(--ink, #e8e8e8);
+ text-align: left;
+ min-width: 0;
+}
+.bdy-chip-icon { font-size: 18px; line-height: 1; }
+.bdy-chip-label {
+ font-size: var(--text-md, 0.8125rem);
+ font-weight: var(--weight-medium, 500);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ max-width: 100%;
+}
+.bdy-chip-play:active { transform: scale(0.97); }
+.bdy-chip-pin {
+ position: absolute;
+ top: 5px;
+ right: 5px;
+ appearance: none;
+ background: rgba(0, 0, 0, 0.3);
+ border: none;
+ border-radius: 50%;
+ width: 22px;
+ height: 22px;
+ cursor: pointer;
+ color: var(--ink-faint, #777);
+ font-size: 13px;
+ line-height: 1;
+ opacity: 0;
+ transition: opacity var(--duration-fast) var(--ease-standard), color var(--duration-fast) var(--ease-standard), transform var(--duration-fast) var(--ease-standard);
+}
+.bdy-chip:hover .bdy-chip-pin,
+.bdy-chip-pin.on { opacity: 1; }
+.bdy-chip-pin:hover { color: var(--accent, #a78bfa); transform: scale(1.15); }
+.bdy-chip-pin.on { color: var(--accent, #a78bfa); }
+
+/* Body skeleton */
+.bdy-skel-card { height: 116px; border-radius: var(--radius-lg, 14px); }
+.bdy-skel-row { height: 36px; width: 180px; border-radius: var(--radius-pill, 999px); margin: 16px 0; }
+.bdy-skel-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 8px; }
+.bdy-skel-chip { height: 64px; border-radius: var(--radius-md, 10px); }
+.bdy-skel-card,
+.bdy-skel-row,
+.bdy-skel-chip,
+.mny-skel-card {
+ background: linear-gradient(110deg, rgba(255, 255, 255, 0.03) 30%, rgba(255, 255, 255, 0.07) 50%, rgba(255, 255, 255, 0.03) 70%);
+ background-size: 220% 100%;
+ animation: studio-shimmer 1.4s ease-in-out infinite;
+}
+
+/* ════════════════════════════════════════════════════════════════════════════
+ * MONEY
+ * ══════════════════════════════════════════════════════════════════════════ */
+.mny-skel-card { height: 120px; border-radius: var(--radius-lg, 14px); margin-bottom: 14px; }
+
+.mny-wallet-card {
+ padding: var(--space-md, 1rem);
+ border-radius: var(--radius-lg, 14px);
+ background:
+ radial-gradient(120% 80% at 0% 0%, rgba(74, 222, 128, 0.08), transparent 55%),
+ var(--surface-1, rgba(255, 255, 255, 0.03));
+ border: 1px solid var(--stroke);
+}
+.mny-wallet-empty { text-align: center; }
+.mny-wallet-glyph { font-size: 30px; color: var(--ink-faint, #666); margin-bottom: 8px; }
+.mny-wallet-empty p { margin: 0 0 12px; color: var(--ink-dim); }
+.mny-wallet-bal { display: flex; gap: var(--space-lg, 1.618rem); margin-bottom: 14px; }
+.mny-bal { display: flex; flex-direction: column; }
+.mny-bal b { font-family: var(--font-display); font-size: var(--text-xl, 1.618rem); color: var(--ink-bright, #fff); line-height: 1.1; }
+.mny-bal span { font-size: var(--text-2xs, 0.6875rem); color: var(--ink-dim); text-transform: uppercase; letter-spacing: 0.06em; }
+
+.mny-wallet-addr {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ flex-wrap: wrap;
+ padding: 10px 12px;
+ border-radius: var(--radius-md, 10px);
+ background: var(--surface-2, rgba(255, 255, 255, 0.05));
+ border: 1px solid var(--stroke);
+ margin-bottom: 12px;
+}
+.mny-addr-label { font-size: var(--text-2xs, 0.6875rem); color: var(--ink-dim); text-transform: uppercase; letter-spacing: 0.06em; }
+.mny-addr { font-family: var(--font-mono, ui-monospace, monospace); font-size: var(--text-md, 0.8125rem); color: var(--ink-bright, #fff); }
+.mny-icon-btn {
+ appearance: none;
+ display: inline-grid;
+ place-items: center;
+ width: 26px;
+ height: 26px;
+ border-radius: var(--radius-sm, 6px);
+ border: 1px solid var(--stroke);
+ background: var(--surface-3, rgba(255, 255, 255, 0.08));
+ color: var(--ink, #e8e8e8);
+ cursor: pointer;
+ text-decoration: none;
+ font-size: 13px;
+ transition: background var(--duration-fast) var(--ease-standard), border-color var(--duration-fast) var(--ease-standard);
+}
+.mny-icon-btn:hover { background: var(--surface-4, rgba(255, 255, 255, 0.12)); border-color: var(--stroke-strong); }
+.mny-wallet-tools { display: flex; flex-wrap: wrap; gap: var(--space-sm, 0.618rem); }
+.mny-wallet-tools .studio-action { margin-top: 0; }
+
+/* Pricing rows */
+.mny-price-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; }
+.mny-price-row {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: var(--space-md, 1rem);
+ flex-wrap: wrap;
+ padding: 11px 13px;
+ border-radius: var(--radius-md, 10px);
+ background: var(--surface-1, rgba(255, 255, 255, 0.03));
+ border: 1px solid var(--stroke);
+ transition: border-color var(--duration-fast) var(--ease-standard);
+}
+.mny-price-row.is-priced { border-color: rgba(74, 222, 128, 0.35); }
+.mny-price-meta { display: flex; align-items: center; gap: 10px; min-width: 0; }
+.mny-price-icon { font-size: 18px; }
+.mny-price-name { display: block; font-weight: var(--weight-semibold, 600); color: var(--ink-bright, #fff); font-size: var(--text-md, 0.8125rem); }
+.mny-price-desc { display: block; font-size: var(--text-2xs, 0.6875rem); color: var(--ink-dim); max-width: 36ch; }
+.mny-price-input { display: flex; align-items: center; gap: 6px; }
+.mny-price-cur { color: var(--ink-dim); font-size: var(--text-md); }
+.mny-price-input input {
+ width: 72px;
+ padding: 6px 8px;
+ border-radius: var(--radius-sm, 6px);
+ border: 1px solid var(--stroke);
+ background: var(--surface-2, rgba(255, 255, 255, 0.05));
+ color: var(--ink-bright, #fff);
+ font-size: var(--text-md, 0.8125rem);
+ text-align: right;
+}
+.mny-price-input input:focus { outline: none; border-color: var(--accent, #a78bfa); }
+.mny-price-unit { font-size: var(--text-2xs, 0.6875rem); color: var(--ink-dim); }
+.mny-price-save { margin-top: 0; }
+
+/* Earnings feed */
+.mny-earn-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; }
+.mny-earn-row {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ padding: 9px 12px;
+ border-radius: var(--radius-md, 10px);
+ background: var(--surface-1, rgba(255, 255, 255, 0.03));
+ border: 1px solid var(--stroke);
+ font-size: var(--text-md, 0.8125rem);
+}
+.mny-earn-row[data-status='pending'] { opacity: 0.65; }
+.mny-earn-amt { font-weight: var(--weight-bold, 700); color: var(--success, #4ade80); white-space: nowrap; }
+.mny-earn-detail { flex: 1; min-width: 0; color: var(--ink, #e8e8e8); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+.mny-earn-detail b { color: var(--ink-bright, #fff); }
+.mny-earn-time { color: var(--ink-dim); font-size: var(--text-2xs, 0.6875rem); white-space: nowrap; }
+.mny-earn-tx { color: var(--ink-dim); text-decoration: none; }
+.mny-earn-tx:hover { color: var(--ink-bright); }
+
+/* ════════════════════════════════════════════════════════════════════════════
+ * SKILLS
+ * ══════════════════════════════════════════════════════════════════════════ */
+.skl-grid {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(240px, 1fr));
+ gap: 10px;
+}
+.skl-card {
+ display: flex;
+ gap: 12px;
+ padding: 13px;
+ border-radius: var(--radius-lg, 14px);
+ background: var(--surface-1, rgba(255, 255, 255, 0.03));
+ border: 1px solid var(--stroke);
+ transition: border-color var(--duration-fast) var(--ease-standard), background var(--duration-fast) var(--ease-standard), opacity var(--duration-fast) var(--ease-standard);
+}
+.skl-card.is-on { border-color: rgba(139, 92, 246, 0.4); background: var(--surface-2, rgba(255, 255, 255, 0.05)); }
+.skl-card:not(.is-on):not(.is-locked) { opacity: 0.72; }
+.skl-card:not(.is-on):not(.is-locked):hover { opacity: 1; border-color: var(--stroke-strong); }
+.skl-card-icon {
+ flex: 0 0 auto;
+ width: 36px;
+ height: 36px;
+ display: grid;
+ place-items: center;
+ font-size: 18px;
+ border-radius: var(--radius-md, 10px);
+ background: var(--surface-3, rgba(255, 255, 255, 0.08));
+ border: 1px solid var(--stroke);
+}
+.skl-card-main { flex: 1; min-width: 0; }
+.skl-card-top { display: flex; align-items: center; gap: 8px; }
+.skl-card-name { font-weight: var(--weight-semibold, 600); color: var(--ink-bright, #fff); font-size: var(--text-md, 0.8125rem); }
+.skl-sellable-tag {
+ font-size: 9px;
+ text-transform: uppercase;
+ letter-spacing: 0.07em;
+ font-weight: var(--weight-bold, 700);
+ color: var(--success, #4ade80);
+ background: rgba(74, 222, 128, 0.12);
+ border: 1px solid rgba(74, 222, 128, 0.3);
+ border-radius: var(--radius-pill, 999px);
+ padding: 1px 7px;
+}
+.skl-card-desc { margin: 3px 0 0; font-size: var(--text-2xs, 0.6875rem); color: var(--ink-dim); line-height: 1.5; }
+.skl-card-foot { margin-top: 7px; min-height: 0; }
+.skl-price-chip {
+ appearance: none;
+ cursor: pointer;
+ font-size: var(--text-2xs, 0.6875rem);
+ font-weight: var(--weight-semibold, 600);
+ color: var(--ink-dim);
+ background: var(--surface-3, rgba(255, 255, 255, 0.08));
+ border: 1px solid var(--stroke);
+ border-radius: var(--radius-pill, 999px);
+ padding: 3px 10px;
+ transition: color var(--duration-fast) var(--ease-standard), border-color var(--duration-fast) var(--ease-standard);
+}
+.skl-price-chip:hover { color: var(--ink-bright, #fff); border-color: var(--stroke-strong); }
+.skl-price-chip.is-priced { color: var(--success, #4ade80); border-color: rgba(74, 222, 128, 0.3); }
+.skl-price-chip.is-loading { cursor: default; }
+.skl-card-toggle { flex: 0 0 auto; display: grid; place-items: center; }
+.skl-locked-badge { color: var(--accent, #a78bfa); font-size: 11px; }
+
+/* Toggle switch */
+.skl-switch {
+ appearance: none;
+ position: relative;
+ width: 38px;
+ height: 22px;
+ border-radius: var(--radius-pill, 999px);
+ background: var(--surface-3, rgba(255, 255, 255, 0.12));
+ border: 1px solid var(--stroke);
+ cursor: pointer;
+ transition: background var(--duration-fast) var(--ease-standard), border-color var(--duration-fast) var(--ease-standard);
+}
+.skl-switch[aria-checked='true'] { background: rgba(139, 92, 246, 0.6); border-color: rgba(139, 92, 246, 0.8); }
+.skl-switch-knob {
+ position: absolute;
+ top: 2px;
+ left: 2px;
+ width: 16px;
+ height: 16px;
+ border-radius: 50%;
+ background: #fff;
+ transition: transform var(--duration-fast) var(--ease-standard);
+}
+.skl-switch[aria-checked='true'] .skl-switch-knob { transform: translateX(16px); }
+.skl-switch:focus-visible { outline: 2px solid var(--focus-ring-color, #fff); outline-offset: 2px; }
+
+/* ── Toasts (shared shape) ───────────────────────────────────────────────── */
+.bdy-toast,
+.mny-toast,
+.skl-toast {
+ position: fixed;
+ left: 50%;
+ bottom: 24px;
+ transform: translateX(-50%) translateY(12px);
+ z-index: 100;
+ padding: 9px 16px;
+ border-radius: var(--radius-pill, 999px);
+ background: var(--surface-4, rgba(30, 31, 40, 0.95));
+ border: 1px solid var(--stroke-strong, rgba(255, 255, 255, 0.2));
+ color: var(--ink-bright, #fff);
+ font-size: var(--text-md, 0.8125rem);
+ font-weight: var(--weight-semibold, 600);
+ box-shadow: var(--shadow-2, 0 8px 32px rgba(0, 0, 0, 0.5));
+ opacity: 0;
+ pointer-events: none;
+ transition: opacity var(--duration-base, 220ms) var(--ease-out), transform var(--duration-base) var(--ease-out);
+}
+.bdy-toast.show,
+.mny-toast.show,
+.skl-toast.show { opacity: 1; transform: translateX(-50%) translateY(0); }
+.mny-toast-err,
+.skl-toast-err,
+.bdy-toast-err { border-color: var(--danger, #f87171); color: var(--danger, #f87171); }
+
+/* ── Responsive ──────────────────────────────────────────────────────────── */
+@media (max-width: 540px) {
+ .bdy-featured,
+ .bdy-grid { grid-template-columns: repeat(auto-fill, minmax(104px, 1fr)); }
+ .skl-grid { grid-template-columns: 1fr; }
+ .mny-price-row { align-items: flex-start; }
+ .bdy-avatar-card { flex-direction: column; align-items: flex-start; }
+}
+@media (prefers-reduced-motion: reduce) {
+ .bdy-skel-card,
+ .bdy-skel-row,
+ .bdy-skel-chip,
+ .mny-skel-card { animation: none; }
+ .bdy-chip-play,
+ .skl-switch-knob,
+ .bdy-chip-pin { transition: none; }
+}
diff --git a/scripts/build-animations.mjs b/scripts/build-animations.mjs
index e640abb33..af0936729 100644
--- a/scripts/build-animations.mjs
+++ b/scripts/build-animations.mjs
@@ -20,6 +20,7 @@ import { createHash } from 'node:crypto';
import { fileURLToPath } from 'node:url';
import { dirname, resolve, basename } from 'node:path';
import { Blob } from 'node:buffer';
+import { liftHipsUpright } from './upright-hips.mjs';
// three's loaders + exporter touch a handful of DOM globals; stub them out for node.
globalThis.self = globalThis;
@@ -272,6 +273,18 @@ async function main() {
clip.name = def.name;
if (def.trim) trimClip(clip, def.trim);
const json = await serializeClip(clip);
+ // Sources whose up-axis conversion rides on the animated Hips (three.js
+ // Soldier/Michelle GLBs) bake a ~90° parent-frame bias the retargeter
+ // can't see — re-stand them upright so the runtime fallen-pose guard
+ // doesn't reject the clip. Opt-in per source; a no-op on healthy clips.
+ if (def.uprightFix) {
+ const lift = liftHipsUpright(json);
+ if (lift.changed) {
+ console.log(
+ `[animations] upright ${def.name.padEnd(12)} ${lift.tiltBefore.toFixed(0)}° → ${lift.tiltAfter.toFixed(0)}°`,
+ );
+ }
+ }
const text = JSON.stringify(json);
writeFileSync(outPath, text);
hashCache[def.name] = cacheKey;
diff --git a/scripts/upright-hips.mjs b/scripts/upright-hips.mjs
new file mode 100644
index 000000000..7b0280456
--- /dev/null
+++ b/scripts/upright-hips.mjs
@@ -0,0 +1,175 @@
+/**
+ * upright-hips.mjs — remove a constant Hips orientation bias from a baked clip.
+ *
+ * Some source skeletons store their up-axis convention (the Y-up→Z-up rotation
+ * Blender/Maya bakes on export) on the Hips bone's LOCAL track rather than on a
+ * parent armature node. three.js's `Soldier.glb` and `Michelle.glb` are exactly
+ * this case: the −90°X / +90°X conversion rides on the animated Hips itself. The
+ * extract → retarget pipeline copies the Hips track verbatim onto a canonical
+ * (identity-rest) rig, so the conversion is no longer cancelled by a parent and
+ * the whole body lies on its back. The runtime fallen-pose guard then correctly
+ * rejects the clip (~90° off vertical) and the avatar falls back to bind pose —
+ * which is what produced the `fallen-pose retarget` reports for `samba-dance`
+ * and the soldier idle/walk/run clips.
+ *
+ * The fix is to fold that constant bias out of the clip: the bias is a single
+ * rotation applied in the Hips' parent frame, so pre-multiplying every Hips
+ * keyframe quaternion by its inverse — and rotating every Hips position keyframe
+ * by the same inverse — re-stands the entire animation upright while leaving the
+ * internal pose (every child bone, relative to the Hips) byte-for-byte untouched.
+ * It is the precise inverse of the missing parent node, not a heuristic reshape.
+ *
+ * Sources that already export upright (Xbot/Robot GLBs, every Mixamo FBX) carry
+ * no bias, so this is opt-in per source via `uprightFix` in animations.config.json
+ * — an authored bent pose (a yoga fold, a crouch) is never silently straightened.
+ * The function is self-gating regardless: a clip already within tolerance of
+ * vertical is returned unchanged, so applying it twice — or to a healthy clip —
+ * is a no-op.
+ *
+ * Operates on the three.js `AnimationClip.toJSON()` shape (`{ tracks: [{ name,
+ * type, times, values }] }`) so the same routine corrects the build output and
+ * repairs already-committed clip JSON.
+ */
+
+// At-rest Hips tilt (degrees off vertical) above which a clip is treated as
+// carrying a baked bias worth removing. Healthy clips peak at ~30° of authored
+// lean (the `dance` choreography); a parent-frame bias lands near 90°. 45° sits
+// cleanly between — and equals the runtime guard's catastrophe threshold, so
+// "would the guard reject this at rest?" and "does this need correcting?" agree.
+const BIAS_THRESHOLD_DEG = 45;
+
+function qMul(a, b) {
+ return [
+ a[3] * b[0] + a[0] * b[3] + a[1] * b[2] - a[2] * b[1],
+ a[3] * b[1] - a[0] * b[2] + a[1] * b[3] + a[2] * b[0],
+ a[3] * b[2] + a[0] * b[1] - a[1] * b[0] + a[2] * b[3],
+ a[3] * b[3] - a[0] * b[0] - a[1] * b[1] - a[2] * b[2],
+ ];
+}
+
+function qNormalize(q) {
+ const l = Math.hypot(q[0], q[1], q[2], q[3]) || 1;
+ return [q[0] / l, q[1] / l, q[2] / l, q[3] / l];
+}
+
+// Rotate a vector by a unit quaternion (q · v · q⁻¹), the standard expansion.
+function qRotateVec(q, v) {
+ const [x, y, z, w] = q;
+ const [vx, vy, vz] = v;
+ const tx = 2 * (y * vz - z * vy);
+ const ty = 2 * (z * vx - x * vz);
+ const tz = 2 * (x * vy - y * vx);
+ return [
+ vx + w * tx + (y * tz - z * ty),
+ vy + w * ty + (z * tx - x * tz),
+ vz + w * tz + (x * ty - y * tx),
+ ];
+}
+
+// World up-axis a Hips quaternion imposes (its local +Y in world space).
+function hipsUp(q) {
+ return qRotateVec(q, [0, 1, 0]);
+}
+
+function tiltDeg(up) {
+ return (Math.acos(Math.max(-1, Math.min(1, up[1]))) * 180) / Math.PI;
+}
+
+// Shortest-arc unit quaternion rotating unit vector `from` onto unit vector `to`.
+function quatFromTo(from, to) {
+ const d = from[0] * to[0] + from[1] * to[1] + from[2] * to[2];
+ if (d > 0.999999) return [0, 0, 0, 1];
+ if (d < -0.999999) {
+ // Antiparallel: rotate 180° about any axis perpendicular to `from`.
+ let axis = Math.abs(from[0]) < 0.9 ? [1, 0, 0] : [0, 1, 0];
+ const c = [
+ from[1] * axis[2] - from[2] * axis[1],
+ from[2] * axis[0] - from[0] * axis[2],
+ from[0] * axis[1] - from[1] * axis[0],
+ ];
+ const l = Math.hypot(c[0], c[1], c[2]) || 1;
+ return [c[0] / l, c[1] / l, c[2] / l, 0];
+ }
+ const c = [
+ from[1] * to[2] - from[2] * to[1],
+ from[2] * to[0] - from[0] * to[2],
+ from[0] * to[1] - from[1] * to[0],
+ ];
+ return qNormalize([c[0], c[1], c[2], 1 + d]);
+}
+
+function findTrack(clipJson, suffix) {
+ return (clipJson.tracks || []).find(
+ (t) => typeof t.name === 'string' && t.name.endsWith(suffix),
+ );
+}
+
+/**
+ * Re-stand a clip whose Hips track carries a constant parent-frame orientation
+ * bias. Mutates the clip's Hips quaternion + position track values in place.
+ *
+ * @param {{ tracks: Array<{ name: string, type?: string, times: number[], values: number[] }> }} clipJson
+ * @returns {{ changed: boolean, tiltBefore: number, tiltAfter: number, reason?: string }}
+ */
+export function liftHipsUpright(clipJson) {
+ const quat = findTrack(clipJson, 'Hips.quaternion');
+ if (!quat || !quat.values || quat.values.length < 4) {
+ return { changed: false, tiltBefore: 0, tiltAfter: 0, reason: 'no-hips-quaternion' };
+ }
+
+ const v = quat.values;
+ const frames = v.length / 4;
+
+ // Mean imposed up-axis across the clip — robust to per-frame motion, so a
+ // transient lean (a dance dip) doesn't skew the bias estimate.
+ const mean = [0, 0, 0];
+ for (let i = 0; i < frames; i++) {
+ const o = i * 4;
+ const up = hipsUp([v[o], v[o + 1], v[o + 2], v[o + 3]]);
+ mean[0] += up[0];
+ mean[1] += up[1];
+ mean[2] += up[2];
+ }
+ const ml = Math.hypot(mean[0], mean[1], mean[2]) || 1;
+ const meanUp = [mean[0] / ml, mean[1] / ml, mean[2] / ml];
+
+ const tiltBefore = tiltDeg([v[0], v[1], v[2], v[3]]);
+ // Self-gate: a clip whose mean up-axis is already near vertical carries no
+ // bias to remove. Returning unchanged makes the routine idempotent and safe
+ // to run on healthy clips.
+ if (tiltDeg(meanUp) <= BIAS_THRESHOLD_DEG) {
+ return { changed: false, tiltBefore, tiltAfter: tiltBefore, reason: 'already-upright' };
+ }
+
+ // The correction is the rotation that maps the baked mean up-axis back to
+ // world vertical — the inverse of the missing parent node.
+ const correction = quatFromTo(meanUp, [0, 1, 0]);
+
+ for (let i = 0; i < frames; i++) {
+ const o = i * 4;
+ const q = qNormalize(qMul(correction, [v[o], v[o + 1], v[o + 2], v[o + 3]]));
+ v[o] = q[0];
+ v[o + 1] = q[1];
+ v[o + 2] = q[2];
+ v[o + 3] = q[3];
+ }
+
+ // The Hips position track lives in the same (biased) parent frame, so the
+ // root trajectory is rotated by the identical correction — otherwise forward
+ // travel leaks into the vertical axis (the soldier-walk Y reaching 6.5 m).
+ const pos = findTrack(clipJson, 'Hips.position');
+ if (pos && pos.values && pos.values.length >= 3) {
+ const p = pos.values;
+ for (let i = 0; i + 2 < p.length; i += 3) {
+ const r = qRotateVec(correction, [p[i], p[i + 1], p[i + 2]]);
+ p[i] = r[0];
+ p[i + 1] = r[1];
+ p[i + 2] = r[2];
+ }
+ }
+
+ const tiltAfter = tiltDeg([v[0], v[1], v[2], v[3]]);
+ return { changed: true, tiltBefore, tiltAfter };
+}
+
+export { BIAS_THRESHOLD_DEG };
diff --git a/src/dashboard-next/pages/sniper.js b/src/dashboard-next/pages/sniper.js
index ebaf4700c..0924ff6ca 100644
--- a/src/dashboard-next/pages/sniper.js
+++ b/src/dashboard-next/pages/sniper.js
@@ -128,6 +128,11 @@ const STYLE = `<style>
.sn-pos-pnl { font-size: 14px; font-weight: 600; font-variant-numeric: tabular-nums; text-align: right; }
.sn-pos-link { font-size: 12px; color: var(--nxt-accent); text-decoration: none; padding: 4px 10px; border: 1px solid color-mix(in srgb, var(--nxt-accent) 35%, transparent); border-radius: var(--nxt-radius-sm); white-space: nowrap; transition: background .12s; }
.sn-pos-link:hover { background: color-mix(in srgb, var(--nxt-accent) 12%, transparent); }
+.sn-pos-actions { display: flex; gap: 8px; align-items: center; justify-content: flex-end; }
+.sn-pos-sell { font-size: 12px; font-family: inherit; padding: 4px 12px; border-radius: var(--nxt-radius-sm); white-space: nowrap; cursor: pointer; color: var(--nxt-danger, #f87171); border: 1px solid color-mix(in srgb, var(--nxt-danger, #f87171) 45%, transparent); background: color-mix(in srgb, var(--nxt-danger, #f87171) 8%, transparent); transition: background .12s, transform .12s; }
+.sn-pos-sell:hover { background: color-mix(in srgb, var(--nxt-danger, #f87171) 16%, transparent); transform: translateY(-1px); }
+.sn-pos-sell:focus-visible { outline: 2px solid var(--nxt-danger, #f87171); outline-offset: 2px; }
+.sn-pos-sell:disabled { opacity: .5; cursor: progress; transform: none; }
.sn-pos-oracle { display: inline-flex; }
.sn-ob { display: inline-flex; align-items: center; gap: 3px; background: rgba(0,0,0,0.4); border: 1px solid rgba(255,255,255,0.08); border-radius: 6px; padding: 3px 7px; text-decoration: none; transition: border-color .12s; }
.sn-ob:hover { border-color: rgba(255,255,255,0.22); }
@@ -592,6 +597,13 @@ function posRow(p) {
const link = p.buy_url
? `<a class="sn-pos-link" href="${esc(p.buy_url)}" target="_blank" rel="noopener">Solscan ↗</a>`
: p.mint ? `<a class="sn-pos-link" href="${pumpUrl(p.mint)}" target="_blank" rel="noopener">pump.fun ↗</a>` : '';
+ const sym = p.symbol || p.mint?.slice(0, 8) || 'this position';
+ // One-tap manual exit: sell the agent's full holding of this mint now, at a
+ // real price, via /api/sniper/close (the same executeSell the worker uses).
+ // Only a fully-open position with a known id can be force-closed.
+ const sellBtn = (p.id && p.status === 'open')
+ ? `<button class="sn-pos-sell" data-action="sell-now" data-pos="${esc(p.id)}" data-agent="${esc(p.agent_id || '')}" data-mint="${esc(p.mint || '')}" data-net="${esc(p.network || 'mainnet')}" data-sym="${esc(sym)}" title="Sell this position now from the agent wallet">Sell now</button>`
+ : '';
const mintAttr = p.mint ? ` data-oracle-mint="${esc(p.mint)}"` : '';
return `<div class="sn-pos-row"${mintAttr}>
<div class="sn-pos-info">
@@ -601,7 +613,7 @@ function posRow(p) {
</div>
<div class="sn-pos-pnl">${pnlStr}</div>
<span class="sn-pos-oracle"></span>
- ${link}
+ <div class="sn-pos-actions">${sellBtn}${link}</div>
</div>`;
}
@@ -867,6 +879,10 @@ function wireEvents(root) {
const toggleKill = e.target.closest('[data-action="toggle-kill"]');
if (toggleKill) { toggleKill_(toggleKill, root); return; }
+ // One-tap manual sell of an open position
+ const sellBtn = e.target.closest('[data-action="sell-now"]');
+ if (sellBtn) { sellNow(sellBtn, root); return; }
+
// Arm btn
if (e.target.id === 'sn-arm-btn') { openArmModal(root); return; }
});
@@ -1088,6 +1104,7 @@ function normPos(p) {
id: p.id,
agent_id: p.agent_id,
agent_name: p.agent_name,
+ network: p.network || 'mainnet',
mint: p.mint,
symbol: p.symbol || p.name,
status: p.status || 'open',
diff --git a/src/irl/marker-anchor.js b/src/irl/marker-anchor.js
new file mode 100644
index 000000000..34e6d0d82
--- /dev/null
+++ b/src/irl/marker-anchor.js
@@ -0,0 +1,241 @@
+// @ts-check
+// Pure marker-frame anchoring math for /irl indoor colocalization (Epic M).
+//
+// Why this exists
+// ───────────────
+// The room frame (src/irl/room-anchor.js) anchors a cluster of agents to ONE
+// origin so their intra-room layout is exact for every viewer. But that origin
+// is a GPS coordinate, and GPS is dead indoors: ±20–50 m, no floor, and it
+// differs phone-to-phone. So "place an agent in my living room, my friend walks
+// in and finds it standing in the exact spot" cannot ride GPS — two phones never
+// agree on the frame.
+//
+// A printed/handheld VISUAL MARKER (a QR a phone can read) fixes this. The marker
+// is a shared, camera-observable origin: both phones look at the SAME marker and
+// each measures its 3D pose in its OWN AR session. That pose becomes the room
+// origin. From there the existing room math is reused verbatim — an agent is
+// stored as an exact metre offset (relEast/relNorth) from the marker, so it
+// renders in the identical physical spot for whoever sees the marker, GPS-free.
+//
+// The one subtlety that makes this work without a shared compass: a WebXR AR
+// session's world frame is gravity-aligned (Y up) but its HEADING (azimuth about
+// Y) is arbitrary and differs per device. So we never express an agent in true
+// north. We store its offset in the MARKER'S OWN frame (along the marker's right
+// and up edges) — a frame both phones can measure directly off the QR. Each
+// viewer measures the marker's azimuth in ITS session live and rotates the
+// marker-local offset into its own frame. The two sessions' heading offset is
+// unknown, but it cancels exactly because the stored offset is frame-independent.
+// That live per-viewer yaw is the whole trick: it replaces the shared compass GPS
+// rooms rely on, which is why this colocalizes indoors where compass+GPS can't.
+//
+// This module owns ONLY what is marker-specific and keeps it pure (no DOM, no
+// Three.js, no BarcodeDetector, no I/O — plain numbers in/out so the test suite
+// verifies it directly). The heavy geometry is delegated to room-anchor.js so
+// there is ONE rotation and one set of conventions on every path:
+//
+// • markerRoomId(payload) — deterministic room id both phones derive from
+// the same QR, so neither needs GPS to find the
+// other's pins (the API reads by room_id).
+// • normalizeMarkerPayload — canonicalize whatever the QR encodes so a
+// three.ws marker URL and its bare token hash equal.
+// • markerYawFromEdge — the marker's world azimuth from two world
+// points spanning its horizontal edge.
+// • markerRelFromWorld — a placed world point → its exact offset in the
+// marker's local frame (the inverse render op).
+// • markerWorldPos — that offset back to a world position for a
+// viewer who has localized the marker.
+//
+// Coordinate conventions — IDENTICAL to src/irl.js and room-anchor.js, do not drift:
+// World: North = −Z · East = +X · Y = up · 1 unit = 1 metre.
+// Yaw/azimuth: degrees 0–359 clockwise from world −Z (north); 0 = N, 90 = E.
+
+import {
+ agentWorldPosition,
+ localToTrueNorth,
+ localToBearingDistance,
+} from './room-anchor.js';
+
+// Mirrors api/irl/pins.js ROOM_ID_RE — a marker room id must satisfy it too.
+const ROOM_ID_MAX = 64;
+// The marker room id is `m-<hash>`; the prefix is how the render path recognises a
+// marker pin (vs a GPS room `r-…`) without a schema column. Keep in sync with the
+// `m-` test in markerRoomId / isMarkerRoomId.
+export const MARKER_ROOM_PREFIX = 'm-';
+
+/**
+ * Canonicalize whatever a QR encodes into the stable token we hash. A three.ws
+ * marker is shared as a URL (`https://three.ws/irl?m=<token>`) so it is also a
+ * tappable deep link; an ad-hoc QR can hold any text. We extract the `m=` token
+ * when present so the URL and the bare token resolve to the SAME marker, then
+ * lower-case + trim so trivial formatting differences don't fork a room.
+ *
+ * @param {unknown} raw the decoded QR string
+ * @returns {string|null} the canonical token, or null if there's nothing usable
+ */
+export function normalizeMarkerPayload(raw) {
+ if (typeof raw !== 'string') return null;
+ let s = raw.trim();
+ if (!s) return null;
+ // Pull the `m=` parameter out of a three.ws marker link so the link and the
+ // raw token collapse to one identity. Tolerant of http/https and any host —
+ // the token is what identifies the marker, not where the link points.
+ const m = s.match(/[?&]m=([^&#\s]+)/i);
+ if (m && m[1]) {
+ try { s = decodeURIComponent(m[1]); } catch { s = m[1]; }
+ }
+ s = s.trim().toLowerCase();
+ if (!s) return null;
+ // Cap to a sane length — a QR can hold ~2–4 KB, but the identity is a short
+ // token. Hashing a capped slice keeps the room id bounded and the hash cheap.
+ return s.slice(0, 512);
+}
+
+// FNV-1a (32-bit) — a small, fast, dependency-free string hash. We need only a
+// stable, well-distributed token both phones compute identically from the same
+// payload; this is not a security primitive (the QR itself is the capability).
+function fnv1a(str) {
+ let h = 0x811c9dc5;
+ for (let i = 0; i < str.length; i++) {
+ h ^= str.charCodeAt(i);
+ // h *= 16777619, kept in 32-bit via Math.imul.
+ h = Math.imul(h, 0x01000193);
+ }
+ return h >>> 0; // unsigned
+}
+
+/**
+ * The deterministic room id for a marker: `m-<base36 hash>`. Both phones derive
+ * the identical id from the same QR, so the placer's pins are found by anyone who
+ * scans the marker — the API reads them by room_id with no GPS gate. Always
+ * satisfies api/irl/pins.js ROOM_ID_RE (`^[a-z0-9-]{1,64}$`).
+ *
+ * @param {unknown} payload raw QR string (or an already-normalized token)
+ * @returns {string|null} the room id, or null if the payload is unusable
+ */
+export function markerRoomId(payload) {
+ const token = normalizeMarkerPayload(payload);
+ if (!token) return null;
+ // Two 32-bit halves (token + token reversed) widen the space to ~64 bits so
+ // distinct markers don't collide on a room. base36 keeps it slug-safe.
+ const a = fnv1a(token).toString(36);
+ const b = fnv1a(token.split('').reverse().join('')).toString(36);
+ return `${MARKER_ROOM_PREFIX}${a}${b}`.slice(0, ROOM_ID_MAX);
+}
+
+/**
+ * Whether a room id is a marker room (vs a GPS room). The render path uses this
+ * to decide a pin is localized by a visual marker, not by the viewer's GPS.
+ * @param {unknown} roomId
+ * @returns {boolean}
+ */
+export function isMarkerRoomId(roomId) {
+ return typeof roomId === 'string' && roomId.startsWith(MARKER_ROOM_PREFIX);
+}
+
+/**
+ * The marker's azimuth (degrees, 0–359 clockwise from the session's −Z) IN THE
+ * CURRENT AR SESSION FRAME, from two world points spanning its horizontal "right"
+ * edge — e.g. the marker centre and a point one edge to its right, each resolved
+ * by a WebXR hit-test through the QR's detected corners. This is a per-session
+ * number (the session heading is arbitrary), measured fresh by every viewer; that
+ * is by design — see the module header. Keeps all camera/CV work in hit-test ray
+ * space (the platform's job) and leaves this module a pure azimuth-of-a-delta,
+ * reusing room-anchor's localToBearingDistance so the convention can never drift.
+ *
+ * The marker's local "north" (its +relNorth axis) is defined as the in-plane
+ * direction 90° counter-clockwise from its right edge, matching how a viewer
+ * reads the marker upright — so an agent placed "to the right of the marker as I
+ * face it" lands to the right for the next viewer who faces it too.
+ *
+ * @param {{x:number,z:number}} centerWorld marker centre in world (XZ)
+ * @param {{x:number,z:number}} rightWorld a point along the marker's right edge
+ * @returns {number|null} azimuth degrees, or null if the points coincide
+ */
+export function markerYawFromEdge(centerWorld, rightWorld) {
+ const dEast = rightWorld.x - centerWorld.x; // east = +X
+ const dNorth = -(rightWorld.z - centerWorld.z); // north = −Z
+ if (Math.hypot(dEast, dNorth) < 1e-4) return null; // degenerate: no edge length
+ // Azimuth of the RIGHT edge. The marker frame's own north is 90° CCW of it, so
+ // the stored originYawDeg (frame rotation vs true north) is rightAzimuth − 90,
+ // normalized — the same originYawDeg agentWorldPosition consumes.
+ const { bearingDeg } = localToBearingDistance(dEast, dNorth);
+ return (((bearingDeg - 90) % 360) + 360) % 360;
+}
+
+/**
+ * A placed agent's world point → its EXACT offset in the marker's local frame
+ * (relEast / relNorth, metres). The inverse of {@link markerWorldPos}: it
+ * un-rotates the world delta by the marker's yaw so the stored offset round-trips
+ * cleanly back to world for any viewer who localizes the same marker. Mirrors
+ * floor-anchor's roomRelFromGeo, but the origin is a live marker pose, not a GPS
+ * index — markerYawDeg is THIS session's measured marker azimuth, not true north.
+ *
+ * @param {object} p
+ * @param {{x:number,z:number}} p.markerWorld marker origin in the placer's session frame (XZ)
+ * @param {number} p.markerYawDeg marker azimuth in the placer's session frame (from markerYawFromEdge)
+ * @param {number} p.x agent world X (east, +X)
+ * @param {number} p.z agent world Z (north is −Z)
+ * @returns {{ relEast:number, relNorth:number }}
+ */
+export function markerRelFromWorld({ markerWorld, markerYawDeg = 0, x, z }) {
+ const trueEast = x - markerWorld.x;
+ const trueNorth = -(z - markerWorld.z); // north = −Z
+ const room = markerYawDeg
+ ? localToTrueNorth(trueEast, trueNorth, -markerYawDeg) // inverse rotation into the marker frame
+ : { east: trueEast, north: trueNorth };
+ return { relEast: room.east, relNorth: room.north };
+}
+
+/**
+ * The world position of a marker-anchored agent for a viewer who has localized the
+ * marker. The marker pose plays the role the GPS-derived room origin plays in
+ * room-anchor's agentWorldPosition — so this is that same hot-path call with the
+ * marker as origin, sharing its exact rotation math (no duplicated geometry).
+ *
+ * @param {object} p
+ * @param {{x:number,z:number}} p.markerWorld marker origin in THIS viewer's session frame (XZ)
+ * @param {number} [p.markerYawDeg] marker azimuth in THIS viewer's session frame (from markerYawFromEdge)
+ * @param {number} p.relEast metres east of the marker (marker frame)
+ * @param {number} p.relNorth metres north of the marker (marker frame)
+ * @param {number} [p.heightM] floor offset (Y) relative to the marker
+ * @returns {{ x:number, y:number, z:number }}
+ */
+export function markerWorldPos({ markerWorld, markerYawDeg = 0, relEast, relNorth, heightM = 0 }) {
+ return agentWorldPosition({
+ originWorld: markerWorld,
+ relEast,
+ relNorth,
+ heightM,
+ originYawDeg: markerYawDeg,
+ });
+}
+
+/**
+ * Build the POST `room` block for a marker placement, ready for api/irl/pins.js.
+ * A marker pin is a room pin whose id is derived from the QR and whose origin GPS
+ * is only a coarse INDEX (the marker, not GPS, positions the agent). The server
+ * requires a finite, non-(0,0) origin lat/lng, so the caller passes its coarse
+ * fix; when none is available the caller must gate placement on a fix first
+ * (the marker still needs an index row), exactly like GPS room mode.
+ *
+ * @param {object} p
+ * @param {string} p.roomId from {@link markerRoomId}
+ * @param {number} p.indexLat the placer's coarse fix latitude (GPS index only)
+ * @param {number} p.indexLng the placer's coarse fix longitude
+ * @param {number} p.relEast marker-frame offset east (metres)
+ * @param {number} p.relNorth marker-frame offset north (metres)
+ * @returns {{ id:string, originLat:number, originLng:number, originYawDeg:number, relEast:number, relNorth:number }}
+ */
+export function markerRoomBlock({ roomId, indexLat, indexLng, relEast, relNorth }) {
+ return {
+ id: roomId,
+ originLat: indexLat,
+ originLng: indexLng,
+ // The marker's own yaw is measured LIVE per viewer from the QR, never stored
+ // in the frame — so the stored frame is north-aligned (0) and relEast/relNorth
+ // are already in the marker's local axes from markerRelFromWorld.
+ originYawDeg: 0,
+ relEast,
+ relNorth,
+ };
+}
diff --git a/src/shared/agent-networth.js b/src/shared/agent-networth.js
new file mode 100644
index 000000000..55080d0f4
--- /dev/null
+++ b/src/shared/agent-networth.js
@@ -0,0 +1,159 @@
+/**
+ * Net-Worth-Reactive Avatar — the single client source of truth.
+ *
+ * The agent wears its wallet: holdings, $THREE, fork lineage and reputation become
+ * the 3D body's aura, material, idle confidence and regalia. Every number here is
+ * REAL — it comes from GET /api/agents/:id/solana/networth, which aggregates real
+ * Solana balances (via api/_lib/balances.js), real $THREE holdings, and real fork
+ * counts, and returns the canonical "look" so the galaxy star, the profile hero,
+ * and the AR body always agree (one normalizer, one truth).
+ *
+ * The server computes the canonical look/tier/marks; this module fetches it,
+ * persists owner reactivity prefs (CSRF-gated), and carries a small local mirror of
+ * the tier model (kept in lockstep with api/_lib/networth-model.js) for the
+ * hold-last-state / offline path so a brief RPC hiccup never blanks an avatar.
+ */
+
+// Mirror of api/_lib/networth-model.js — keep the thresholds in lockstep. Used
+// only for the offline/hold-last fallback; the server result is authoritative.
+export const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+export const PRESENCE_TIERS = [
+ { 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 = ['off', 'subtle', 'balanced', 'expressive'];
+export const DEFAULT_PREFS = { reactivity: 'balanced', signals: { aura: true, events: true, reputation: true } };
+
+const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, Number(n) || 0));
+
+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 t = PRESENCE_TIERS[index];
+ const nx = PRESENCE_TIERS[index + 1] || null;
+ return {
+ key: t.key, label: t.label, index, accent: t.accent,
+ next: nx ? { key: nx.key, label: nx.label, usd_to_next: Math.max(0, nx.min - v) } : null,
+ };
+}
+
+/** Local mirror of the server look computation (offline / hold-last fallback). */
+export function computeLook(state = {}) {
+ const usd = Math.max(0, Number(state.usd) || 0);
+ const tier = tierForUsd(usd);
+ const wealth = clamp(Math.log10(usd + 1) / 5, 0, 1);
+ 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);
+ 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);
+ const confidence = clamp(tier.index / 5 * 0.6 + repScore * 0.25 + forkBoost, 0, 1);
+ return {
+ tier,
+ auraIntensity,
+ auraColor: tier.accent,
+ materialTier: Math.floor(tier.index / 2),
+ confidence,
+ glow: clamp(0.12 + auraIntensity * 0.88, 0, 1),
+ };
+}
+
+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 } };
+}
+
+// ── Network ──────────────────────────────────────────────────────────────────
+
+/**
+ * Fetch the agent's real net-worth look. Returns the server payload, or `null`
+ * when the read fails (callers then hold the last real state — never invent one).
+ * @param {string} agentId
+ * @param {object} [opts]
+ * @param {AbortSignal} [opts.signal]
+ * @returns {Promise<object|null>}
+ */
+export async function fetchNetWorth(agentId, opts = {}) {
+ if (!agentId) return null;
+ try {
+ const r = await fetch(`/api/agents/${encodeURIComponent(agentId)}/solana/networth`, {
+ headers: { accept: 'application/json' },
+ credentials: 'include',
+ signal: opts.signal,
+ });
+ if (!r.ok) return null;
+ const j = await r.json().catch(() => null);
+ return j?.data || null;
+ } catch {
+ return null; // network/abort — hold last state
+ }
+}
+
+let _csrf = null;
+async function csrfToken() {
+ if (_csrf && _csrf.expiresAt > Date.now() + 5_000) return _csrf.token;
+ const r = await fetch('/api/csrf-token', { credentials: 'include' });
+ if (!r.ok) throw new Error('Could not obtain a security token — sign in again.');
+ const j = await r.json();
+ _csrf = { token: j.data.token, expiresAt: Date.now() + (j.data.expires_in - 30) * 1000 };
+ return _csrf.token;
+}
+
+/**
+ * Persist the owner's reactivity preferences (owner-only, CSRF-gated server-side).
+ * @param {string} agentId
+ * @param {{reactivity?:string, signals?:object}} prefs
+ * @returns {Promise<object>} the saved, normalized prefs
+ */
+export async function saveNetWorthPrefs(agentId, prefs) {
+ const token = await csrfToken();
+ _csrf = null; // single-use
+ const r = await fetch(`/api/agents/${encodeURIComponent(agentId)}/solana/networth`, {
+ method: 'PUT',
+ headers: { 'content-type': 'application/json', 'x-csrf-token': token, accept: 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify(prefs),
+ });
+ const j = await r.json().catch(() => ({}));
+ if (!r.ok) throw Object.assign(new Error(j?.error_description || 'Could not save presence settings'), { status: r.status, code: j?.error });
+ return j.data?.prefs || normalizePrefs(prefs);
+}
+
+// ── Formatting ───────────────────────────────────────────────────────────────
+
+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`;
+}
+
+/** Parse a hex accent (#rgb / #rrggbb) to a normalized [r,g,b] triple for WebGL. */
+export function hexToRgb(hex) {
+ let h = String(hex || '#8b5cf6').replace('#', '');
+ if (h.length === 3) h = h.split('').map((c) => c + c).join('');
+ const int = parseInt(h, 16);
+ if (Number.isNaN(int)) return [0.55, 0.36, 0.96];
+ return [((int >> 16) & 255) / 255, ((int >> 8) & 255) / 255, (int & 255) / 255];
+}
diff --git a/src/shared/networth-aura.js b/src/shared/networth-aura.js
new file mode 100644
index 000000000..b06714f31
--- /dev/null
+++ b/src/shared/networth-aura.js
@@ -0,0 +1,147 @@
+/**
+ * Net-Worth Aura — the tasteful, performance-cheap glow that embodies an agent's
+ * real wealth/reputation tier around its 3D body.
+ *
+ * Two additive sprites: a floor halo (a pool of light at the feet) and a soft
+ * back-glow behind the figure. Both read as *presence*, never a slot-machine.
+ * Intensity/colour come straight from the net-worth look descriptor
+ * (src/shared/agent-networth.js → computeLook), which is derived from real chain
+ * reads. A zero-value wallet gets a calm, near-invisible floor; a Beacon-tier
+ * agent gets a confident violet halo.
+ *
+ * Reduced-motion safe: the glow holds a static intensity (no pulse) when motion is
+ * off, so the tier still reads. Cheap by construction: one shared radial texture,
+ * two sprites, no per-frame allocation; the host stops calling update() when the
+ * avatar is offscreen.
+ */
+
+import * as THREE from 'three';
+
+// One soft radial-alpha texture, shared by every aura instance on the page.
+let _spriteTex = null;
+function radialTexture() {
+ if (_spriteTex) return _spriteTex;
+ const s = 128;
+ const c = document.createElement('canvas');
+ c.width = c.height = s;
+ const ctx = c.getContext('2d');
+ const g = ctx.createRadialGradient(s / 2, s / 2, 0, s / 2, s / 2, s / 2);
+ g.addColorStop(0, 'rgba(255,255,255,1)');
+ g.addColorStop(0.35, 'rgba(255,255,255,0.55)');
+ g.addColorStop(0.7, 'rgba(255,255,255,0.12)');
+ g.addColorStop(1, 'rgba(255,255,255,0)');
+ ctx.fillStyle = g;
+ ctx.fillRect(0, 0, s, s);
+ _spriteTex = new THREE.CanvasTexture(c);
+ _spriteTex.colorSpace = THREE.SRGBColorSpace;
+ return _spriteTex;
+}
+
+const REDUCED_MOTION =
+ typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
+
+const lerp = (a, b, t) => a + (b - a) * Math.min(1, Math.max(0, t));
+
+export class NetWorthAura {
+ constructor() {
+ this.object3D = new THREE.Group();
+ this.object3D.name = 'networth-aura';
+ this.object3D.renderOrder = -1; // draw behind the avatar
+
+ const tex = radialTexture();
+ this._floorMat = new THREE.SpriteMaterial({ map: tex, color: 0x8b5cf6, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, opacity: 0 });
+ this._backMat = new THREE.SpriteMaterial({ map: tex, color: 0x8b5cf6, transparent: true, depthWrite: false, blending: THREE.AdditiveBlending, opacity: 0 });
+
+ this._floor = new THREE.Sprite(this._floorMat);
+ this._floor.center.set(0.5, 0.5);
+ this._back = new THREE.Sprite(this._backMat);
+ this._back.center.set(0.5, 0.5);
+
+ this.object3D.add(this._floor, this._back);
+
+ this._radius = 1;
+ this._height = 1.7;
+ this._intensity = 0; // target glow 0..1
+ this._cur = 0; // smoothed glow
+ this._color = new THREE.Color(0x8b5cf6);
+ this._pulse = 0; // transient additive boost, decays
+ this._pulseSign = 1; // +1 celebratory, -1 subdued
+ this._t = 0;
+ this.visible = true;
+ }
+
+ /** Fit the aura to the avatar's real bounds (call once after the model loads). */
+ setBounds({ radius, height, centerY = 0, baseY = 0 } = {}) {
+ if (radius > 0) this._radius = radius;
+ if (height > 0) this._height = height;
+ // Floor halo: flat pool at the feet, ~2.6× footprint.
+ const fr = this._radius * 2.6;
+ this._floor.scale.set(fr, fr, 1);
+ this._floor.position.set(0, baseY + 0.02, 0);
+ this._floor.material.rotation = 0;
+ // Back-glow: a tall soft column centered on the torso.
+ this._back.scale.set(this._radius * 3.2, this._height * 1.25, 1);
+ this._back.position.set(0, centerY, -this._radius * 0.4);
+ return this;
+ }
+
+ /**
+ * Apply a net-worth look. `auraColor` may be a hex string or an [r,g,b] triple;
+ * `glow` (0..1) sets the steady intensity.
+ */
+ setLook(look = {}) {
+ const glow = Math.max(0, Math.min(1, Number(look.glow ?? look.auraIntensity) || 0));
+ this._intensity = glow;
+ const c = look.auraColor;
+ if (Array.isArray(c)) this._color.setRGB(c[0], c[1], c[2]);
+ else if (typeof c === 'string') this._color.set(c);
+ this._floorMat.color.copy(this._color);
+ this._backMat.color.copy(this._color);
+ return this;
+ }
+
+ /** Fire a transient pulse on a real event. kind: 'positive' | 'subdued'. */
+ pulse(kind = 'positive') {
+ if (REDUCED_MOTION) return; // static look only — never flash with motion off
+ this._pulseSign = kind === 'subdued' ? -1 : 1;
+ this._pulse = kind === 'subdued' ? 0.5 : 1;
+ }
+
+ /** Per-frame. Skips work when hidden. dt in seconds. */
+ update(dt) {
+ if (!this.visible) return;
+ this._t += dt;
+ // Smoothly chase the target intensity (so tier changes ease in).
+ this._cur = lerp(this._cur, this._intensity, dt * 2.5);
+ // Decay the transient pulse.
+ if (this._pulse > 0.001) this._pulse = Math.max(0, this._pulse - dt * (this._pulseSign > 0 ? 1.1 : 0.7));
+ else this._pulse = 0;
+
+ // Gentle breathing on the steady glow (suppressed under reduced motion).
+ const breathe = REDUCED_MOTION ? 1 : 1 + 0.06 * Math.sin(this._t * 1.1);
+ const pulseBoost = this._pulse * this._pulseSign * 0.6;
+
+ const floorBase = 0.10 + this._cur * 0.42;
+ const backBase = 0.04 + this._cur * 0.26;
+ this._floorMat.opacity = Math.max(0, (floorBase + pulseBoost) * breathe);
+ this._backMat.opacity = Math.max(0, (backBase + pulseBoost * 0.7) * breathe);
+ // Pulse also briefly widens the floor pool.
+ if (this._pulse > 0) {
+ const k = 1 + this._pulse * this._pulseSign * 0.18;
+ const fr = this._radius * 2.6 * k;
+ this._floor.scale.set(fr, fr, 1);
+ }
+ }
+
+ setVisible(v) {
+ this.visible = !!v;
+ this.object3D.visible = !!v;
+ }
+
+ dispose() {
+ this._floorMat.dispose();
+ this._backMat.dispose();
+ this.object3D.parent?.remove(this.object3D);
+ // The shared texture is intentionally NOT disposed (other auras may use it).
+ }
+}
diff --git a/src/studio/studio-shell.js b/src/studio/studio-shell.js
index ca2c12201..5bd589396 100644
--- a/src/studio/studio-shell.js
+++ b/src/studio/studio-shell.js
@@ -40,27 +40,30 @@ const TABS = [
{ key: 'skills', label: 'Skills', hint: 'Capabilities the agent can perform and sell.' },
];
+// Fallback copy shown only if a sub-studio bundle fails to load (each mount
+// removes this and renders its own designed loading/empty/error states). The
+// copy is real and actionable — never a "mounts here" placeholder.
const EMPTY_COPY = {
brain: {
- title: 'Wire up a brain',
- body: 'Pick a model and shape how your agent thinks. The Brain studio mounts here.',
+ title: 'Loading the Brain studio…',
+ body: "Pick a model and shape how your agent thinks. If this doesn't load, refresh the page.",
},
memory: {
- title: 'Give it a memory',
- body: 'Decide what your agent recalls across conversations. The Memory studio mounts here.',
+ title: 'Loading the Memory studio…',
+ body: "Decide what your agent recalls across conversations. If this doesn't load, refresh the page.",
},
body: {
- title: 'Choose a body',
- body: 'Attach a 3D avatar, dress it, and set its animations. The Body studio mounts here.',
+ title: 'Loading the Body studio…',
+ body: 'Choose a 3D avatar, customize its outfit, and set how it moves. If this stalls, refresh the page.',
cta: { label: 'Create an avatar →', href: '/create' },
},
money: {
- title: 'Set up money',
- body: "Fund the agent's wallet and price its skills. The Money studio mounts here.",
+ title: 'Loading the Money studio…',
+ body: "Fund the agent's wallet and price its skills. If this stalls, refresh the page.",
},
skills: {
- title: 'Add skills',
- body: 'Turn on capabilities your agent can perform and monetize. The Skills studio mounts here.',
+ title: 'Loading the Skills studio…',
+ body: "Turn on capabilities your agent can perform and monetize. If this stalls, refresh the page.",
},
};
diff --git a/vercel.json b/vercel.json
index f7687bf79..2aa5da9ca 100644
--- a/vercel.json
+++ b/vercel.json
@@ -12,6 +12,9 @@
"api/agents/[id].js": {
"maxDuration": 45
},
+ "api/agents/networth.js": {
+ "maxDuration": 60
+ },
"api/club/tips-stream.js": {
"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
"maxDuration": 300
@@ -2167,6 +2170,10 @@
"src": "/api/sniper/strategy",
"dest": "/api/sniper/strategy.js"
},
+ {
+ "src": "/api/sniper/close",
+ "dest": "/api/sniper/close.js"
+ },
{
"src": "/api/sniper/stream",
"dest": "/api/sniper/stream.js"
@@ -2429,6 +2436,10 @@
"src": "/api/agents/endpoint-shopper-run",
"dest": "/api/agents/endpoint-shopper-run"
},
+ {
+ "src": "/api/agents/networth",
+ "dest": "/api/agents/networth"
+ },
{
"src": "/api/agents/([^/]+)",
"dest": "/api/agents/[id]"