Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: enhance reasoning ledger with score visualization and new studio adapter
qbdz5772bedba98d
diff --git a/pages/dashboard-next/sniper.html b/pages/dashboard-next/sniper.htmlindex 32c02d14b..6f657d934 100644--- a/pages/dashboard-next/sniper.html+++ b/pages/dashboard-next/sniper.html@@ -8,6 +8,11 @@<link rel="icon" href="/favicon.ico" /><link rel="stylesheet" href="/fonts/fonts.css" /><link rel="stylesheet" href="/dashboard-next/shell.css" />+ <!-- Design tokens + panel styles for the embedded Money Studio (Wallet,+ Trading Brain, Pricing, Earnings). tokens.css is variables-only;+ studio-panels.css classes are .mny-/.tb- prefixed — no clash with .sn-. -->+ <link rel="stylesheet" href="/tokens.css" />+ <link rel="stylesheet" href="/studio-panels.css" /></head><body><script type="module" src="/src/dashboard-next/pages/sniper.js"></script>diff --git a/pages/home.html b/pages/home.htmlindex e2bc83bca..00317ef3f 100644--- a/pages/home.html+++ b/pages/home.html@@ -2850,6 +2850,263 @@</div></section>+<!-- ── AUTONOMOUS SNIPING & TRADING ─────────────────────────────── -->+<style>+ #home-sniper .snipe-lede-pill {+ display: inline-flex; align-items: center; gap: 8px; margin-top: 18px;+ padding: 6px 12px; border: 1px solid var(--hairline-strong); border-radius: 999px;+ font-size: 12px; letter-spacing: .02em; color: var(--text-2); background: var(--surface-1);+ }+ #home-sniper .snipe-console {+ margin-top: 40px; border: 1px solid var(--hairline-strong); border-radius: 16px;+ background: var(--surface-0); overflow: hidden;+ box-shadow: 0 1px 0 rgba(255,255,255,0.03) inset, 0 24px 60px -32px rgba(0,0,0,0.8);+ }+ #home-sniper .snipe-console-head {+ display: flex; align-items: center; justify-content: space-between; gap: 16px;+ padding: 14px 20px; border-bottom: 1px solid var(--hairline);+ background: linear-gradient(to bottom, var(--surface-1), var(--surface-0));+ }+ #home-sniper .snipe-status { display: flex; align-items: center; gap: 12px; min-width: 0; }+ #home-sniper .snipe-state {+ display: inline-flex; align-items: center; gap: 8px; font-size: 13px; font-weight: 600;+ color: var(--text); white-space: nowrap;+ }+ #home-sniper .snipe-dot {+ width: 8px; height: 8px; border-radius: 50%; background: var(--text-3);+ box-shadow: 0 0 0 0 rgba(52,211,153,0.5); flex: none;+ }+ #home-sniper .snipe-dot.live { background: #34d399; animation: snipe-pulse 2s ease-out infinite; }+ #home-sniper .snipe-dot.degraded { background: #fbbf24; }+ #home-sniper .snipe-dot.down { background: #f87171; }+ @keyframes snipe-pulse {+ 0% { box-shadow: 0 0 0 0 rgba(52,211,153,0.5); }+ 70% { box-shadow: 0 0 0 7px rgba(52,211,153,0); }+ 100% { box-shadow: 0 0 0 0 rgba(52,211,153,0); }+ }+ #home-sniper .snipe-substate { font-size: 12px; color: var(--text-3); white-space: nowrap; }+ #home-sniper .snipe-net {+ font-size: 11px; letter-spacing: .08em; text-transform: uppercase; color: var(--text-3);+ font-variant-numeric: tabular-nums; white-space: nowrap;+ }+ #home-sniper .snipe-body { display: grid; grid-template-columns: 1.35fr 1fr; }+ @media (max-width: 860px) { #home-sniper .snipe-body { grid-template-columns: 1fr; } }++ /* ── decision pipeline ─────────────────────────────────────── */+ #home-sniper .snipe-pipeline {+ position: relative; padding: 34px 26px; border-right: 1px solid var(--hairline);+ display: flex; flex-direction: column; gap: 20px;+ }+ @media (max-width: 860px) { #home-sniper .snipe-pipeline { border-right: none; border-bottom: 1px solid var(--hairline); } }+ #home-sniper .snipe-flow-label {+ font-size: 11px; letter-spacing: .12em; text-transform: uppercase; color: var(--text-3);+ }+ #home-sniper .snipe-stages { position: relative; display: flex; align-items: stretch; gap: 0; }+ #home-sniper .snipe-rail {+ position: absolute; left: 8%; right: 8%; top: 21px; height: 2px;+ background: var(--hairline-strong); border-radius: 2px; overflow: visible;+ }+ #home-sniper .snipe-packet {+ position: absolute; top: -3px; left: 0; width: 8px; height: 8px; border-radius: 50%;+ background: #fff; box-shadow: 0 0 10px 2px rgba(255,255,255,0.7);+ opacity: 0; transform: translateX(0); will-change: transform, opacity;+ }+ #home-sniper .snipe-stage {+ position: relative; flex: 1; display: flex; flex-direction: column; align-items: center;+ gap: 10px; text-align: center; background: none; border: none; padding: 0; cursor: pointer;+ font: inherit; color: inherit; z-index: 1;+ }+ #home-sniper .snipe-node {+ width: 44px; height: 44px; border-radius: 12px; display: grid; place-items: center;+ background: var(--surface-2); border: 1px solid var(--hairline-strong);+ color: var(--text-2); transition: transform .25s cubic-bezier(.2,.7,.3,1),+ border-color .25s, color .25s, box-shadow .25s, background .25s;+ }+ #home-sniper .snipe-node svg { width: 20px; height: 20px; }+ #home-sniper .snipe-stage:hover .snipe-node,+ #home-sniper .snipe-stage:focus-visible .snipe-node {+ border-color: rgba(255,255,255,0.45); color: var(--text); transform: translateY(-2px);+ }+ #home-sniper .snipe-stage.active .snipe-node,+ #home-sniper .snipe-stage.flow .snipe-node {+ border-color: #fff; color: #fff; background: var(--surface-3);+ box-shadow: 0 0 0 4px rgba(255,255,255,0.08), 0 0 18px -2px rgba(255,255,255,0.4);+ transform: translateY(-2px) scale(1.04);+ }+ #home-sniper .snipe-stage-name { font-size: 12px; font-weight: 600; color: var(--text); }+ #home-sniper .snipe-stage-sub { font-size: 10.5px; color: var(--text-3); line-height: 1.3; }+ #home-sniper .snipe-explain {+ min-height: 44px; margin-top: 2px; padding: 12px 14px; border-radius: 10px;+ background: var(--surface-1); border: 1px solid var(--hairline);+ font-size: 12.5px; line-height: 1.5; color: var(--text-2);+ transition: opacity .2s; opacity: 1;+ }+ #home-sniper .snipe-explain strong { color: var(--text); font-weight: 600; }++ /* ── live trade tape ───────────────────────────────────────── */+ #home-sniper .snipe-tape-wrap { display: flex; flex-direction: column; min-width: 0; }+ #home-sniper .snipe-tape-head {+ display: flex; align-items: center; justify-content: space-between; gap: 8px;+ padding: 14px 18px 10px; font-size: 11px; letter-spacing: .1em; text-transform: uppercase;+ color: var(--text-3);+ }+ #home-sniper .snipe-tape {+ list-style: none; margin: 0; padding: 0 10px 12px; display: flex; flex-direction: column;+ gap: 4px; overflow: hidden; flex: 1; min-height: 232px;+ }+ #home-sniper .snipe-row {+ display: grid; grid-template-columns: auto 1fr auto; align-items: center; gap: 10px;+ padding: 9px 10px; border-radius: 9px; background: var(--surface-1);+ border: 1px solid transparent; text-decoration: none; color: inherit;+ transition: background .2s, border-color .2s;+ }+ #home-sniper a.snipe-row:hover { background: var(--surface-2); border-color: var(--hairline-strong); }+ #home-sniper .snipe-row.enter { animation: snipe-row-in .42s cubic-bezier(.2,.7,.3,1); }+ @keyframes snipe-row-in {+ from { opacity: 0; transform: translateY(-8px); }+ to { opacity: 1; transform: translateY(0); }+ }+ #home-sniper .snipe-tag {+ font-size: 10px; font-weight: 700; letter-spacing: .04em; padding: 3px 7px; border-radius: 6px;+ text-transform: uppercase; flex: none;+ }+ #home-sniper .snipe-tag.buy { color: #34d399; background: rgba(52,211,153,0.12); }+ #home-sniper .snipe-tag.sell { color: #cbd5e1; background: rgba(203,213,225,0.1); }+ #home-sniper .snipe-tag.open { color: #5fe3ff; background: rgba(95,227,255,0.12); }+ #home-sniper .snipe-rmeta { min-width: 0; }+ #home-sniper .snipe-rsym { font-size: 13px; font-weight: 600; color: var(--text); }+ #home-sniper .snipe-ragent {+ font-size: 11px; color: var(--text-3); white-space: nowrap; overflow: hidden;+ text-overflow: ellipsis; max-width: 100%;+ }+ #home-sniper .snipe-rpnl { font-size: 13px; font-weight: 600; font-variant-numeric: tabular-nums; text-align: right; }+ #home-sniper .snipe-rpnl.up { color: #34d399; }+ #home-sniper .snipe-rpnl.down { color: #f87171; }+ #home-sniper .snipe-rpnl.flat { color: var(--text-3); }+ #home-sniper .snipe-tape-msg { padding: 40px 16px; text-align: center; color: var(--text-3); font-size: 13px; line-height: 1.5; }+ #home-sniper .snipe-skel {+ height: 38px; border-radius: 9px; margin: 0 0 4px;+ background: linear-gradient(90deg, var(--surface-1) 25%, rgba(255,255,255,0.05) 50%, var(--surface-1) 75%);+ background-size: 200% 100%; animation: snipe-shimmer 1.3s linear infinite;+ }+ @keyframes snipe-shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } }++ /* ── footer: KPIs + CTAs ───────────────────────────────────── */+ #home-sniper .snipe-foot {+ display: flex; align-items: center; justify-content: space-between; gap: 20px; flex-wrap: wrap;+ padding: 16px 20px; border-top: 1px solid var(--hairline); background: var(--surface-1);+ }+ #home-sniper .snipe-kpis { display: flex; gap: 26px; flex-wrap: wrap; }+ #home-sniper .snipe-kpi { display: flex; flex-direction: column; gap: 2px; }+ #home-sniper .snipe-kpi-val { font-size: 18px; font-weight: 700; color: var(--text); font-variant-numeric: tabular-nums; line-height: 1; }+ #home-sniper .snipe-kpi-val.accent { color: #34d399; }+ #home-sniper .snipe-kpi-val.loading { color: var(--text-3); animation: snipe-shimmer-text 1.4s ease-in-out infinite; }+ @keyframes snipe-shimmer-text { 0%,100% { opacity: .4; } 50% { opacity: 1; } }+ #home-sniper .snipe-kpi-lbl { font-size: 11px; color: var(--text-3); letter-spacing: .02em; }+ #home-sniper .snipe-ctas { display: flex; gap: 10px; flex-wrap: wrap; }+ #home-sniper .snipe-cta {+ display: inline-flex; align-items: center; gap: 6px; padding: 10px 16px; border-radius: 10px;+ font-size: 13px; font-weight: 600; text-decoration: none; transition: transform .2s, background .2s, border-color .2s;+ }+ #home-sniper .snipe-cta.primary { background: #fff; color: #0b0b0b; }+ #home-sniper .snipe-cta.primary:hover { transform: translateY(-1px); }+ #home-sniper .snipe-cta.ghost { background: transparent; color: var(--text); border: 1px solid var(--hairline-strong); }+ #home-sniper .snipe-cta.ghost:hover { background: var(--surface-2); border-color: rgba(255,255,255,0.4); }+ @media (prefers-reduced-motion: reduce) {+ #home-sniper .snipe-dot.live { animation: none; }+ #home-sniper .snipe-row.enter { animation: none; }+ #home-sniper .snipe-skel { animation: none; }+ #home-sniper .snipe-kpi-val.loading { animation: none; }+ }+</style>+<section class="block" id="home-sniper">+ <div class="wrap-1280">+ <div class="block-head reveal">+ <p class="block-eyebrow"><span class="num">03</span>Autonomous trading</p>+ <h2 class="block-h">Your agents don't just talk. <em>They trade.</em></h2>+ <p class="block-lede">+ Every three.ws agent can run an on-chain sniper: it watches new pump.fun launches in+ real time, scores each one, clears its risk guards, buys, and exits on its own —+ stop-loss, take-profit, trailing, or timeout. One loop, fully autonomous, provable on-chain.+ </p>+ <span class="snipe-lede-pill"><span class="snipe-dot live" aria-hidden="true"></span> Live engine · real positions · no simulation</span>+ </div>++ <div class="snipe-console reveal reveal-d1">+ <div class="snipe-console-head">+ <div class="snipe-status" id="snipe-status">+ <span class="snipe-state"><span class="snipe-dot" id="snipe-state-dot" aria-hidden="true"></span><span id="snipe-state-text">Connecting to the engine…</span></span>+ <span class="snipe-substate" id="snipe-substate"></span>+ </div>+ <span class="snipe-net">mainnet · pump.fun</span>+ </div>++ <div class="snipe-body">+ <!-- decision pipeline -->+ <div class="snipe-pipeline">+ <span class="snipe-flow-label">The trade loop</span>+ <div class="snipe-stages" id="snipe-stages" role="group" aria-label="The autonomous trade loop — select a stage to learn what it does">+ <div class="snipe-rail">+ <span class="snipe-packet" id="snipe-packet" aria-hidden="true"></span>+ </div>+ <button type="button" class="snipe-stage active" data-stage="watch" aria-pressed="true">+ <span class="snipe-node"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M2 12s3.5-7 10-7 10 7 10 7-3.5 7-10 7-10-7-10-7Z"/></svg></span>+ <span class="snipe-stage-name">Watch</span>+ <span class="snipe-stage-sub">new launches</span>+ </button>+ <button type="button" class="snipe-stage" data-stage="score" aria-pressed="false">+ <span class="snipe-node"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M3 3v18h18"/><path d="m7 14 3-4 3 3 5-7"/></svg></span>+ <span class="snipe-stage-name">Score</span>+ <span class="snipe-stage-sub">conviction</span>+ </button>+ <button type="button" class="snipe-stage" data-stage="guard" aria-pressed="false">+ <span class="snipe-node"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10Z"/></svg></span>+ <span class="snipe-stage-name">Guard</span>+ <span class="snipe-stage-sub">risk checks</span>+ </button>+ <button type="button" class="snipe-stage" data-stage="buy" aria-pressed="false">+ <span class="snipe-node"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M12 19V5"/><path d="m5 12 7-7 7 7"/></svg></span>+ <span class="snipe-stage-name">Buy</span>+ <span class="snipe-stage-sub">sign & land</span>+ </button>+ <button type="button" class="snipe-stage" data-stage="exit" aria-pressed="false">+ <span class="snipe-node"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><path d="m16 17 5-5-5-5"/><path d="M21 12H9"/></svg></span>+ <span class="snipe-stage-name">Exit</span>+ <span class="snipe-stage-sub">TP / SL / trail</span>+ </button>+ </div>+ <p class="snipe-explain" id="snipe-explain"><strong>Watch.</strong> A PumpPortal feed streams every new pump.fun mint the instant it's created — the agent sees launches the moment they exist.</p>+ </div>++ <!-- live trade tape -->+ <div class="snipe-tape-wrap">+ <div class="snipe-tape-head">+ <span>Live activity</span>+ <span class="snipe-state" style="font-size:11px"><span class="snipe-dot live" aria-hidden="true"></span> streaming</span>+ </div>+ <ul class="snipe-tape" id="snipe-tape" aria-live="polite" aria-label="Live sniper trades">+ <li class="snipe-skel"></li><li class="snipe-skel"></li><li class="snipe-skel"></li>+ <li class="snipe-skel"></li><li class="snipe-skel"></li>+ </ul>+ </div>+ </div>++ <div class="snipe-foot">+ <div class="snipe-kpis" id="snipe-kpis">+ <div class="snipe-kpi"><span class="snipe-kpi-val accent loading" id="snipe-kpi-winrate">—</span><span class="snipe-kpi-lbl">Win rate</span></div>+ <div class="snipe-kpi"><span class="snipe-kpi-val loading" id="snipe-kpi-roi">—</span><span class="snipe-kpi-lbl">Best ROI</span></div>+ <div class="snipe-kpi"><span class="snipe-kpi-val loading" id="snipe-kpi-open">—</span><span class="snipe-kpi-lbl">Open positions</span></div>+ <div class="snipe-kpi"><span class="snipe-kpi-val loading" id="snipe-kpi-armed">—</span><span class="snipe-kpi-lbl">Strategies armed</span></div>+ </div>+ <div class="snipe-ctas">+ <a class="snipe-cta primary" href="/arena" data-cta="watch_arena" data-cta-loc="home_sniper">Watch the arena →</a>+ <a class="snipe-cta ghost" href="/oracle/arm" data-cta="arm_strategy" data-cta-loc="home_sniper">Arm a strategy</a>+ </div>+ </div>+ </div>+ </div>+</section>+<!-- ── WHAT YOU GET ──────────────────────────────────────────────── --><section class="block" id="what-you-get"><div class="wrap-1280">diff --git a/public/changelog.json b/public/changelog.jsonindex 98f484164..1ac9a4eee 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-30T03:48:58.716Z",+ "generated_at": "2026-06-30T19:18:38.865Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",diff --git a/public/features.json b/public/features.jsonindex e4dbb0821..d185f76d9 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-30T03:48:58.673Z",+ "generated_at": "2026-06-30T19:18:38.834Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/src/agent-screen.js b/src/agent-screen.jsindex 8e5861387..da232b592 100644--- a/src/agent-screen.js+++ b/src/agent-screen.js@@ -878,6 +878,7 @@ async function boot(id) {maxlength="1000"spellcheck="false">+ <button class="asc-task-forge-toggle" id="asc-forge-toggle" type="button" aria-pressed="false" aria-controls="asc-forge-form" title="Forge a 3D avatar from text — free">✦</button><button class="asc-task-voice" id="asc-task-voice" type="button" aria-pressed="false" title="Voice on — click to mute">🔊</button><button class="asc-task-send" id="asc-task-send" type="submit" title="Send"><svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">diff --git a/src/dashboard-next/pages/sniper.js b/src/dashboard-next/pages/sniper.jsindex 593d5d502..0a837f5b4 100644--- a/src/dashboard-next/pages/sniper.js+++ b/src/dashboard-next/pages/sniper.js@@ -14,6 +14,8 @@import { mountShell } from '../shell.js';import { requireUser, get, post, esc, relTime, ApiError } from '../api.js';+import { StudioAdapter } from '../studio-adapter.js';+import { mountMoneyStudio } from '../../studio/money/money-studio.js';const SOL = 1_000_000_000n;const lamportsToSol = (l) => Number(BigInt(l || '0')) / 1e9;diff --git a/src/dashboard-next/studio-adapter.js b/src/dashboard-next/studio-adapter.jsnew file mode 100644index 000000000..fedd1d605--- /dev/null+++ b/src/dashboard-next/studio-adapter.js@@ -0,0 +1,205 @@+/**+ * Per-agent Studio adapter (dashboard-next)+ * =========================================+ * The Agent Studio sub-studios (Money, Trading Brain, …) are written against a+ * `studio` object — the singleton in `src/studio/agent-studio-store.js`. That+ * singleton loads only the caller's OWN `me` agent, so it can't back a dashboard+ * that mounts those panels for many different agents at once.+ *+ * This adapter implements the exact slice of that contract the Money Studio + its+ * Trading Brain actually use — `agent` (getter), `patch`, `emit`/`on`,+ * `emitMarket`/`onMarket`, `commit`, `destroy` — for a single agent, seeded from a+ * plain `/api/agents/:id` record (no AgentIdentity / memory load). Persistence is+ * the same debounced, optimistic `PUT /api/agents/:id` via the shared `apiFetch`+ * (CSRF + cookies handled), with rollback on failure.+ *+ * import { StudioAdapter } from '../studio-adapter.js';+ * const adapter = new StudioAdapter(agentRecord); // agentRecord = (await get(`/api/agents/${id}`)).agent+ * mountMoneyStudio(host, { studio: adapter });+ * // later: adapter.destroy();+ */++import { apiFetch } from '../api.js';++const DEBOUNCE_MS = 600;++// Fields the studio owns on the agent record and is allowed to PUT — mirrors the+// WRITABLE set in agent-studio-store.js so an accidental patch can't try to write+// a read-only/derived column.+const WRITABLE = new Set(['name', 'description', 'avatarId', 'skills', 'meta', 'personaPrompt', 'homeUrl']);++function isPlainObject(v) {+ return v !== null && typeof v === 'object' && !Array.isArray(v);+}++// Deep-merge `src` into `dst` for plain objects; arrays and scalars replace.+// Pure (never mutates inputs). Intentionally self-contained so the dashboard stays+// decoupled from the studio store's internals.+function deepMerge(dst, src) {+ const out = Array.isArray(dst) ? [...dst] : { ...dst };+ for (const [k, v] of Object.entries(src)) {+ if (isPlainObject(v) && isPlainObject(out[k])) out[k] = deepMerge(out[k], v);+ else out[k] = isPlainObject(v) ? deepMerge({}, v) : v;+ }+ return out;+}++// Map a decorated `/api/agents/:id` record (snake_case on the wire) into the+// camelCase snapshot the sub-studios read — same shape AgentStudioStore exposes.+function snapshotFromRecord(rec) {+ return {+ id: rec.id,+ name: rec.name || 'Agent',+ description: rec.description || '',+ avatarId: rec.avatar_id || rec.avatarId || null,+ homeUrl: rec.home_url || rec.homeUrl || (rec.id ? `/agent/${rec.id}` : ''),+ skills: [...(rec.skills || [])],+ meta: structuredClone(rec.meta || {}),+ personaPrompt: rec.persona_prompt ?? rec.personaPrompt ?? '',+ updatedAt: rec.updated_at || rec.updatedAt || null,+ isOwner: typeof rec.isOwner === 'boolean' ? rec.isOwner : Boolean(rec.user_id),+ };+}++export class StudioAdapter {+ /** @param {object} agentRecord — the `agent` object from `/api/agents/:id`. */+ constructor(agentRecord) {+ this._record = snapshotFromRecord(agentRecord || {});+ this._optimistic = null;+ this._events = new Map();+ this._marketListeners = new Set();+ this._flushTimer = null;+ this._inflight = null;+ this._destroyed = false;+ }++ // ── Reactive read ─────────────────────────────────────────────────────────++ get agent() {+ return this._optimistic ? deepMerge(this._record, this._optimistic) : this._record;+ }++ get isLoaded() {+ return !!this._record?.id;+ }++ // ── Domain event bus ──────────────────────────────────────────────────────++ on(event, fn) {+ if (!this._events.has(event)) this._events.set(event, new Set());+ this._events.get(event).add(fn);+ return () => this._events.get(event)?.delete(fn);+ }++ emit(event, data) {+ const set = this._events.get(event);+ if (!set) return;+ for (const fn of set) {+ try { fn(data); } catch (e) { console.error(`[studio-adapter] '${event}' listener threw`, e); }+ }+ }++ // ── Market events ─────────────────────────────────────────────────────────+ // Presence (<agent-presence>) isn't on the dashboard, so emitMarket is a sink+ // for any listeners the panels register — never a crash for the callers.++ emitMarket(evt) {+ for (const fn of this._marketListeners) {+ try { fn(evt); } catch (e) { console.error('[studio-adapter] market listener threw', e); }+ }+ }++ onMarket(fn) {+ this._marketListeners.add(fn);+ return () => this._marketListeners.delete(fn);+ }++ // ── Optimistic patch + debounced persist ──────────────────────────────────++ patch(partial) {+ if (this._destroyed || !isPlainObject(partial) || !this._record?.id) return;+ const clean = {};+ for (const [k, v] of Object.entries(partial)) {+ if (WRITABLE.has(k)) clean[k] = v;+ else console.warn(`[studio-adapter] patch ignored unknown field: ${k}`);+ }+ if (!Object.keys(clean).length) return;+ this._optimistic = this._optimistic ? deepMerge(this._optimistic, clean) : deepMerge({}, clean);+ this.emit('save:pending');+ if (this._flushTimer) clearTimeout(this._flushTimer);+ this._flushTimer = setTimeout(() => { this.commit().catch(() => {}); }, DEBOUNCE_MS);+ }++ async commit() {+ if (this._flushTimer) { clearTimeout(this._flushTimer); this._flushTimer = null; }+ if (this._inflight) {+ await this._inflight.catch(() => {});+ if (this._optimistic) return this.commit();+ return this._record;+ }+ if (!this._optimistic || !this._record?.id) return this._record;++ const pending = this._optimistic;+ this._optimistic = null;+ const baseline = this._record;+ const optimisticRecord = deepMerge(baseline, pending);+ this._record = optimisticRecord;++ // Build the PUT body from changed fields only, camelCase → snake_case. `meta`+ // is always sent whole (the server shallow-merges top-level meta keys, so this+ // preserves sibling bags like onchain/token while replacing meta.studio).+ const body = {};+ if ('name' in pending) body.name = optimisticRecord.name;+ if ('description' in pending) body.description = optimisticRecord.description;+ if ('avatarId' in pending) body.avatar_id = optimisticRecord.avatarId;+ if ('skills' in pending) body.skills = optimisticRecord.skills;+ if ('homeUrl' in pending) body.home_url = optimisticRecord.homeUrl;+ if ('personaPrompt' in pending) body.persona_prompt = optimisticRecord.personaPrompt;+ if ('meta' in pending) body.meta = optimisticRecord.meta;++ this._inflight = (async () => {+ try {+ const resp = await apiFetch(`/api/agents/${baseline.id}`, {+ method: 'PUT',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(body),+ });+ if (!resp.ok) {+ const detail = await resp.json().catch(() => ({}));+ throw Object.assign(new Error(detail?.error?.message || `PUT ${resp.status}`), { status: resp.status });+ }+ const { agent } = await resp.json();+ // Server is authoritative for derived fields; keep our optimistic values+ // for what we just wrote so a slow round-trip doesn't visibly snap back.+ this._record = {+ ...optimisticRecord,+ meta: agent?.meta ? deepMerge(optimisticRecord.meta, agent.meta) : optimisticRecord.meta,+ personaPrompt: typeof agent?.persona_prompt === 'string' ? agent.persona_prompt : optimisticRecord.personaPrompt,+ updatedAt: agent?.updated_at || agent?.updatedAt || optimisticRecord.updatedAt,+ };+ this.emit('save:ok');+ return this._record;+ } catch (err) {+ // Roll back the optimistic edit and surface for the UI (toast). The edit+ // is dropped on purpose so the UI reflects true server state.+ this._record = baseline;+ this.emit('error', { op: 'patch', error: err, status: err.status });+ console.error('[studio-adapter] patch PUT failed, rolled back:', err.message);+ throw err;+ } finally {+ this._inflight = null;+ }+ })();++ return this._inflight;+ }++ destroy() {+ this._destroyed = true;+ if (this._flushTimer) { clearTimeout(this._flushTimer); this._flushTimer = null; }+ this._events.clear();+ this._marketListeners.clear();+ }+}++export default StudioAdapter;diff --git a/src/leaderboard.js b/src/leaderboard.jsindex 0f913e9a2..c0c07f4df 100644--- a/src/leaderboard.js+++ b/src/leaderboard.js@@ -100,7 +100,7 @@ function rowMarkup(r) {`realized P&L ${fmtSol(r.realized_pnl_sol)}`,].filter(Boolean).join(', ');return `- <a class="lb-row" href="${href}" data-top="${r.rank <= 3 ? r.rank : ''}" aria-label="${escapeHtml(rowLabel)}">+ <a class="lb-row" href="${href}" data-key="${escapeHtml(String(r.agent_id))}" data-top="${r.rank <= 3 ? r.rank : ''}" aria-label="${escapeHtml(rowLabel)}"><span class="lb-rank">${r.rank}</span><span class="lb-trader"><img class="lb-avatar" src="${escapeHtml(img)}" alt="" loading="lazy" onerror="this.src='${identicon(r.agent_id || r.wallet || '?')}'" />@@ -173,7 +173,7 @@ function liveRowMarkup(r) {`${r.trades} trades`,].filter(Boolean).join(', ');return `- <a class="lb-row lb-row--live" href="${escapeHtml(r.account_url)}" target="_blank" rel="noopener" data-top="${r.rank <= 3 ? r.rank : ''}" aria-label="${escapeHtml(label)}">+ <a class="lb-row lb-row--live" href="${escapeHtml(r.account_url)}" target="_blank" rel="noopener" data-key="${escapeHtml(String(r.wallet))}" data-top="${r.rank <= 3 ? r.rank : ''}" aria-label="${escapeHtml(label)}"><span class="lb-rank">${r.rank}</span><span class="lb-trader"><img class="lb-avatar" src="${escapeHtml(img)}" alt="" loading="lazy" />@@ -221,30 +221,44 @@ function summaryLabel(ddId, text) {if (dt) dt.textContent = text;}+// Count a summary tile from its previously-shown real value to the new one and+// flash the direction of change. Non-numeric / missing → static dash, and the+// tracked value is cleared so the next real number doesn't count from a stale one.+const intFmt = (n) => String(Math.round(n));+function setSummaryNum(el, value, format) {+ if (!el) return;+ if (value == null || !Number.isFinite(value)) { el.textContent = '—'; delete el.dataset.juiceVal; return; }+ updateValue(el, value, format);+}+function setSummaryStr(el, str) {+ if (!el) return;+ el.textContent = str;+ delete el.dataset.juiceVal;+}+function renderSummary(data) {const agents = data.leaderboard || [];const live = data.live_traders || [];const isLive = !agents.length && live.length > 0;- $('#lb-sum-sol').textContent = data.sol_usd ? `$${Math.round(data.sol_usd)}` : '—';+ setSummaryNum($('#lb-sum-sol'), data.sol_usd || null, (n) => `$${Math.round(n)}`);if (isLive) {const top = live[0];summaryLabel('lb-sum-traders', 'Live traders');summaryLabel('lb-sum-verified', 'Source');- $('#lb-sum-traders').textContent = String(live.length);- $('#lb-sum-verified').textContent = 'kolscan';- $('#lb-sum-top').textContent = top- ? (top.realized_pnl_sol != null ? fmtSol(top.realized_pnl_sol) : fmtUsd(top.realized_pnl_usd))- : '—';+ setSummaryNum($('#lb-sum-traders'), live.length, intFmt);+ setSummaryStr($('#lb-sum-verified'), 'kolscan');+ const topSol = top && top.realized_pnl_sol != null;+ setSummaryNum($('#lb-sum-top'), top ? (topSol ? top.realized_pnl_sol : top.realized_pnl_usd) : null, topSol ? fmtSol : fmtUsd);return;}summaryLabel('lb-sum-traders', 'Ranked traders');summaryLabel('lb-sum-verified', 'Verified');- $('#lb-sum-traders').textContent = String(agents.length);- $('#lb-sum-verified').textContent = String(agents.filter((r) => r.verified).length);+ setSummaryNum($('#lb-sum-traders'), agents.length, intFmt);+ setSummaryNum($('#lb-sum-verified'), agents.filter((r) => r.verified).length, intFmt);const top = agents[0];- $('#lb-sum-top').textContent = top ? fmtSol(top.realized_pnl_sol) : '—';+ setSummaryNum($('#lb-sum-top'), top ? top.realized_pnl_sol : null, fmtSol);}function renderTicker(trades) {@@ -275,17 +289,25 @@ function renderBoard(data) {const agents = data.leaderboard || [];const live = data.live_traders || [];board.setAttribute('aria-busy', 'false');+ // First paint staggers rows in; subsequent refreshes/sorts FLIP-animate rows to+ // their new rank instead of re-flashing the whole board (the --reflow class+ // suppresses the per-row entrance animation while standings settle in place).+ const initial = firstLoad;// 1. Provable three.ws agent track records take precedence.if (agents.length) {setBoardMode(false);clearLiveBanner();stateEl.innerHTML = '';+ const flip = initial ? null : flipReorder(rows, (el) => el.dataset.key || '');+ flip?.capture();+ rows.classList.toggle('lb-rows--reflow', !initial);rows.innerHTML = agents.map(rowMarkup).join('');// Wire the wallet chips' copy + Tip actions. The board is public — viewers// don't own these traders' agents — so chips render isOwner:false (◎ Tip).wireWalletChips(rows);- staggerRows(rows);+ if (initial) staggerRows(rows);+ flip?.play();return;}@@ -295,8 +317,12 @@ function renderBoard(data) {setBoardMode(true);showLiveBanner(data);stateEl.innerHTML = '';+ const flip = initial ? null : flipReorder(rows, (el) => el.dataset.key || '');+ flip?.capture();+ rows.classList.toggle('lb-rows--reflow', !initial);rows.innerHTML = sortLive(live, state.sort).map(liveRowMarkup).join('');- staggerRows(rows);+ if (initial) staggerRows(rows);+ flip?.play();return;}@@ -331,9 +357,11 @@ async function load() {renderTicker(data.trades);firstLoad = false;clearStale();+ setLiveDot($('#lb-live'), 'live', 'live');} catch (err) {board.setAttribute('aria-busy', 'false');if (firstLoad) {+ setLiveDot($('#lb-live'), 'error', 'offline');$('#lb-rows').innerHTML = '';$('#lb-state').innerHTML = `<div class="lb-state-title">Couldn’t load the leaderboard</div>@@ -344,6 +372,7 @@ async function load() {// On a refresh failure we keep the last good board on screen — no// flicker — but flag it as stale so the standings aren't trusted blindly.showStale();+ setLiveDot($('#lb-live'), 'connecting', 'reconnecting');}}}diff --git a/src/reasoning-ledger.js b/src/reasoning-ledger.jsindex 6cfbff2ab..db121c01c 100644--- a/src/reasoning-ledger.js+++ b/src/reasoning-ledger.js@@ -7,6 +7,7 @@// made visible — honesty is the trust signal.import { apiFetch } from './api.js';+import { countUp, enterStagger, sparkline, reducedMotion } from './ui-juice.js';const root = document.getElementById('rl-root');@@ -42,8 +43,19 @@ const state = {beforeSeq: null,entries: [],loadingMore: false,+ revealedCount: 0, // entries already animated-in, so only freshly-appended ones stagger};+// After a render: sweep the reputation ring, count the score up, and stagger only+// the timeline rows that haven't entered yet (the freshly-appended page on+// "load older", or every row on a fresh load / filter change).+function playLedgerMotion() {+ playScoreRing();+ const rows = Array.from(document.querySelectorAll('.rl-timeline .rl-entry'));+ enterStagger(rows.slice(state.revealedCount));+ state.revealedCount = rows.length;+}+// ── Fetch ────────────────────────────────────────────────────────────────────async function fetchLedger({ append = false } = {}) {@@ -77,25 +89,61 @@ async function fetchVerify() {// ── Render: score ring + calibration chart ────────────────────────────────────+function scoreColor(score) {+ return score >= 70 ? 'var(--rl-green)' : score >= 45 ? 'var(--rl-amber)' : 'var(--rl-red)';+}+function scoreRing(score) {const r = 56, c = 2 * Math.PI * r;const pct = Math.max(0, Math.min(100, score)) / 100;- const dash = (pct * c).toFixed(1);- const hue = score >= 70 ? '#4ade80' : score >= 45 ? '#fbbf24' : '#f87171';+ const off = (c * (1 - pct)).toFixed(1);+ const hue = scoreColor(score);+ // The arc starts empty (offset = full circumference) and `playScoreRing` sweeps+ // it to its real offset after paint; the number counts up in step. Reduced+ // motion lands on the final frame instantly (see playScoreRing / countUp).return `<div class="rl-score-ring"><svg viewBox="0 0 132 132" role="img" aria-label="Reputation score ${score} of 100"><circle cx="66" cy="66" r="${r}" fill="none" stroke="var(--rl-line)" stroke-width="10" />- <circle cx="66" cy="66" r="${r}" fill="none" stroke="${hue}" stroke-width="10"- stroke-linecap="round" stroke-dasharray="${dash} ${c.toFixed(1)}" />+ <circle class="rl-score-arc" cx="66" cy="66" r="${r}" fill="none" stroke="${hue}" stroke-width="10"+ stroke-linecap="round" stroke-dasharray="${c.toFixed(1)}"+ stroke-dashoffset="${c.toFixed(1)}" data-target="${off}" /></svg><div class="rl-score-num">- <span class="rl-score-val" style="color:${hue}">${score}</span>+ <span class="rl-score-val" data-score="${score}" style="color:${hue}">${score}</span><span class="rl-score-cap">/ 100</span></div></div>`;}+// Sweep the reputation arc from empty to its real offset and count the number up+// in lockstep. Reduced motion → jump straight to the final state.+function playScoreRing() {+ const arc = document.querySelector('.rl-score-arc');+ const num = document.querySelector('.rl-score-val');+ if (arc) {+ const target = arc.getAttribute('data-target');+ if (reducedMotion()) arc.style.strokeDashoffset = target;+ else requestAnimationFrame(() => requestAnimationFrame(() => { arc.style.strokeDashoffset = target; }));+ }+ if (num) {+ const score = Number(num.dataset.score) || 0;+ countUp(num, 0, score, { format: (n) => String(Math.round(n)) });+ }+}++// Cumulative realized P&L across the reconciled decisions in view, oldest→newest —+// a real "is this agent's judgment paying off" trend. Returns null when there+// aren't yet two settled, P&L-bearing calls to draw a line between.+function qualityTrend(entries) {+ const settled = [...entries]+ .reverse()+ .filter((d) => d.outcome?.status === 'reconciled' && d.outcome.pnl_sol != null);+ if (settled.length < 2) return null;+ let running = 0;+ return settled.map((d) => { running += Number(d.outcome.pnl_sol) || 0; return running; });+}+function calibrationChart(rep) {const buckets = (rep.calibration || []).filter((b) => b.count > 0 && b.predicted != null && b.actual != null);const S = 300, pad = 34;@@ -150,6 +198,17 @@ function repCard(rep) {<div class="rl-stat"><dt>Confidence</dt><dd>${(rep.confidence * 100).toFixed(0)}%</dd></div></dl></div>+ ${(() => {+ const trend = qualityTrend(state.entries);+ if (!trend) return '';+ const net = trend[trend.length - 1];+ const cls = net > 0 ? 'pos' : net < 0 ? 'neg' : '';+ return `<div class="rl-trend">+ <span class="rl-trend-k">Realized P&L · settled calls in view</span>+ <span class="rl-trend-spark">${sparkline(trend, { width: 160, height: 32, fill: true, animate: true })}</span>+ <span class="rl-trend-v ${cls}">${fmtSol(net)}</span>+ </div>`;+ })()}<div class="rl-verify-row" id="rl-verify-row"></div><details class="rl-drill"><summary>How is this score computed?</summary>@@ -303,6 +362,7 @@ function renderNoDecisions() {<a class="rl-btn" href="/agents/${esc(state.agentId)}">View agent profile →</a></div></section>`;mountVerify();+ playLedgerMotion();}function renderAll() {@@ -315,6 +375,7 @@ function renderAll() {${timelineSection()}`;mountVerify();wireFilters();+ playLedgerMotion();}// ── Wiring ────────────────────────────────────────────────────────────────────@@ -346,6 +407,7 @@ function wireFilters() {async function reloadTimeline() {state.beforeSeq = null;+ state.revealedCount = 0; // a filter/search change re-renders the whole list — stagger all of ittry {await fetchLedger({ append: false });renderAll();diff --git a/src/swarms.js b/src/swarms.jsindex a8ddcb6b4..3b4803dc2 100644--- a/src/swarms.js+++ b/src/swarms.js@@ -608,8 +608,8 @@ function subscribeStream(id) {if (t.open_positions != null) updateTile(document.getElementById('sw-open'), t.open_positions, (v) => String(Math.round(v)));const pnl = document.getElementById('sw-pnl');if (pnl && t.realized_pnl_sol != null) {- pnl.className = 'sw-tile-v ' + (t.realized_pnl_sol > 0 ? 'pos' : t.realized_pnl_sol < 0 ? 'neg' : '');- updateTile(pnl, t.realized_pnl_sol, (v) => `${v >= 0 ? '+' : ''}${SOL(v)}`);+ updateTile(pnl, t.realized_pnl_sol, (v) => `${v >= 0 ? '+' : ''}${SOL(v)}`,+ (v) => { pnl.className = 'sw-tile-v ' + (v > 0 ? 'pos' : v < 0 ? 'neg' : ''); });}if (t.win_rate != null) updateTile(document.getElementById('sw-wr'), t.win_rate * 100, (v) => `${Math.round(v)}%`);} catch {}@@ -627,27 +627,33 @@ function flash(el) {}// ── treasury tile juice: count between two real values, flash on change ──────────-const reduceMotion = () => window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;+// Skip the motion for reduced-motion users AND for a backgrounded tab — rAF is+// throttled while hidden, which would otherwise strand a half-finished count and a+// stuck flash class when the user returns. Both cases just snap to the real value.+const motionOff = () => document.hidden || (window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches);const countTimers = new WeakMap();// Animate a tile's number from its previously displayed real value to the new real// value, preserving the tile's own formatting. Cancels any in-flight count on the-// same element. Reduced-motion (or no prior value) → instant set, no animation.-function countTile(el, to, format) {+// same element. onValue (optional) fires each frame with the current number so a+// caller can keep dependent styling (e.g. P&L sign/colour) in lockstep with it.+function countTile(el, to, format, onValue) {if (!el) return;const prevTimer = countTimers.get(el);if (prevTimer) { cancelAnimationFrame(prevTimer); countTimers.delete(el); }const prevRaw = el.dataset.val;const prev = prevRaw == null || prevRaw === '' ? null : Number(prevRaw);el.dataset.val = to == null ? '' : String(to);- if (to == null || prev == null || prev === to || reduceMotion()) { el.textContent = format(to); return; }+ if (to == null || prev == null || prev === to || motionOff()) { el.textContent = format(to); if (onValue) onValue(to); return; }const dur = 480, start = performance.now(), delta = to - prev;const ease = (x) => 1 - Math.pow(1 - x, 3); // easeOutCubicconst step = (now) => {const p = Math.min(1, (now - start) / dur);- el.textContent = format(prev + delta * ease(p));+ const v = p < 1 ? prev + delta * ease(p) : to;+ el.textContent = format(v);+ if (onValue) onValue(v);if (p < 1) { countTimers.set(el, requestAnimationFrame(step)); }- else { el.textContent = format(to); countTimers.delete(el); }+ else { countTimers.delete(el); }};countTimers.set(el, requestAnimationFrame(step));}@@ -655,7 +661,7 @@ function countTile(el, to, format) {// Direction-aware tile tint: dir > 0 → green, dir < 0 → red/neutral, then settle.function flashTile(el, dir) {const tile = el && el.closest && el.closest('.sw-tile');- if (!tile || !dir || reduceMotion()) return;+ if (!tile || !dir || motionOff()) return;tile.classList.remove('sw-tile--up', 'sw-tile--down');void tile.offsetWidth; // restart the animation if it's already mid-flighttile.classList.add(dir > 0 ? 'sw-tile--up' : 'sw-tile--down');@@ -664,12 +670,12 @@ function flashTile(el, dir) {}// Count to the new value and flash in its direction in one call.-function updateTile(el, to, format) {+function updateTile(el, to, format, onValue) {if (!el) return;const prevRaw = el.dataset.val;const prev = prevRaw == null || prevRaw === '' ? null : Number(prevRaw);if (prev != null && to != null && to !== prev) flashTile(el, to - prev);- countTile(el, to, format);+ countTile(el, to, format, onValue);}const prefersReducedMotion = () => typeof window.matchMedia === 'function' && window.matchMedia('(prefers-reduced-motion: reduce)').matches;