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 economy ticker, strategy library, and NVIDIA vision lane

nirholas14aa38402426
diff --git a/api/_lib/vision-nvidia.js b/api/_lib/vision-nvidia.js
new file mode 100644
index 000000000..07dfa002f
--- /dev/null
+++ b/api/_lib/vision-nvidia.js
@@ -0,0 +1,209 @@
+// Free NVIDIA NIM vision lane — multimodal VLM understanding over the same
+// OpenAI-compatible REST surface (integrate.api.nvidia.com) and the same free
+// nvapi key already used by api/chat.js. Net-new capability: hand the model an
+// image (a viewer screenshot, an uploaded reference, a launch thumbnail) and a
+// question, get back text — "describe this 3D model", "write alt text", "is this
+// thumbnail readable", "what style is this avatar".
+//
+// ── Image transport (the contract that makes this non-trivial) ───────────────
+// NVIDIA's hosted VLMs accept an image two ways, and which one is legal depends
+// on size:
+// • Inline: embed a data URI in the message content as an HTML <img> tag,
+// <img src="data:image/jpeg;base64,…" />
+// This is REJECTED for payloads at/above ~180 KB (the documented inline cap).
+// • Asset reference: for anything larger, upload the bytes to the NVCF Assets
+// API first, then reference the returned asset id in the SAME <img> tag with
+// the `asset_id` scheme and list it in the NVCF-INPUT-ASSET-REFERENCES header:
+// <img src="data:image/jpeg;asset_id,<id>" /> + header: NVCF-INPUT-ASSET-REFERENCES: <id>
+// This module picks the right path by size so callers never have to. The
+// asset-id `;asset_id,` + NVCF-INPUT-ASSET-REFERENCES handshake is the same one
+// documented for the TRELLIS provider (api/_providers/nvidia.js).
+//
+// Error codes match the provider contract used elsewhere (tts-nvidia.js):
+// not_configured | invalid_key | rate_limited | invalid_argument |
+// timeout | provider_unreachable | provider_error.
+
+import { env } from './env.js';
+
+const CHAT_URL = 'https://integrate.api.nvidia.com/v1/chat/completions';
+const ASSETS_URL = 'https://api.nvcf.nvidia.com/v2/nvcf/assets';
+
+// Inline data-URI images must stay under the hosted cap. NVIDIA documents ~180 KB
+// on the encoded payload; measure the base64 string length (what actually rides
+// in the JSON) and switch to the asset upload below this with margin.
+const INLINE_B64_LIMIT = 180_000;
+const DEFAULT_TIMEOUT_MS = 45_000;
+
+// Hosted free VLMs. Default is the strongest general model; the 11B is a lighter,
+// faster option. Callers may pass any of these; anything else falls back to the
+// default so a typo never reaches the upstream as an invalid model.
+export const VISION_MODELS = new Set([
+ 'meta/llama-3.2-90b-vision-instruct',
+ 'meta/llama-3.2-11b-vision-instruct',
+ 'microsoft/phi-3.5-vision-instruct',
+ 'nvidia/vila',
+]);
+export const DEFAULT_VISION_MODEL = 'meta/llama-3.2-90b-vision-instruct';
+
+// A useful default task when the caller supplies only an image: a tight,
+// platform-relevant description rather than an open-ended ramble.
+export const DEFAULT_VISION_PROMPT =
+ 'Describe this 3D model or avatar render in two sentences: subject, style, and notable details. Be concrete and concise.';
+
+export function visionConfigured() {
+ return Boolean(env.NVIDIA_API_KEY);
+}
+
+export function resolveVisionModel(model) {
+ return VISION_MODELS.has(model) ? model : DEFAULT_VISION_MODEL;
+}
+
+function providerError(status, detail) {
+ let code = 'provider_error';
+ if (status === 401 || status === 403) code = 'invalid_key';
+ else if (status === 429) code = 'rate_limited';
+ else if (status === 400 || status === 422) code = 'invalid_argument';
+ const err = new Error(`NVIDIA vision returned ${status}${detail ? `: ${String(detail).slice(0, 300)}` : ''}`);
+ err.code = code;
+ err.providerStatus = status;
+ return err;
+}
+
+// Upload image bytes to the NVCF Assets API and return the asset id. Two steps:
+// register the asset (get a presigned PUT url + id), then PUT the bytes. The
+// description is echoed into the required x-amz-meta header on the PUT.
+async function uploadAsset({ bytes, contentType, apiKey, timeoutMs }) {
+ const description = 'three.ws vision input';
+ let reg;
+ try {
+ reg = await fetch(ASSETS_URL, {
+ method: 'POST',
+ headers: {
+ authorization: `Bearer ${apiKey}`,
+ 'content-type': 'application/json',
+ accept: 'application/json',
+ },
+ body: JSON.stringify({ contentType, description }),
+ signal: AbortSignal.timeout(timeoutMs),
+ });
+ } catch (e) {
+ throw Object.assign(new Error(`NVCF asset registration unreachable: ${e?.message}`), { code: 'provider_unreachable' });
+ }
+ if (!reg.ok) {
+ const detail = await reg.text().catch(() => '');
+ throw providerError(reg.status, detail);
+ }
+ const { uploadUrl, assetId } = await reg.json();
+ if (!uploadUrl || !assetId) {
+ throw Object.assign(new Error('NVCF asset registration returned no uploadUrl/assetId'), { code: 'provider_error' });
+ }
+
+ let put;
+ try {
+ put = await fetch(uploadUrl, {
+ method: 'PUT',
+ headers: {
+ 'content-type': contentType,
+ 'x-amz-meta-nvcf-asset-description': description,
+ },
+ body: bytes,
+ signal: AbortSignal.timeout(timeoutMs),
+ });
+ } catch (e) {
+ throw Object.assign(new Error(`NVCF asset upload unreachable: ${e?.message}`), { code: 'provider_unreachable' });
+ }
+ if (!put.ok) {
+ const detail = await put.text().catch(() => '');
+ throw providerError(put.status, detail);
+ }
+ return assetId;
+}
+
+// Ask a hosted VLM about an image.
+//
+// { imageBytes: Buffer, contentType?, prompt?, model?, maxTokens?, temperature?,
+// timeoutMs?, apiKey? }
+// → { text, model, assetId|null }
+//
+// Throws Error with .code ∈ not_configured | invalid_key | rate_limited |
+// invalid_argument | timeout | provider_unreachable | provider_error.
+export async function describeImage({
+ imageBytes,
+ contentType = 'image/jpeg',
+ prompt = DEFAULT_VISION_PROMPT,
+ model = DEFAULT_VISION_MODEL,
+ maxTokens = 512,
+ temperature = 0.2,
+ timeoutMs = DEFAULT_TIMEOUT_MS,
+ apiKey,
+} = {}) {
+ const key = apiKey || env.NVIDIA_API_KEY;
+ if (!key) {
+ throw Object.assign(new Error('NVIDIA_API_KEY not set'), { code: 'not_configured' });
+ }
+ const bytes = Buffer.isBuffer(imageBytes) ? imageBytes : Buffer.from(imageBytes || []);
+ if (!bytes.length) {
+ throw Object.assign(new Error('no image bytes to analyze'), { code: 'invalid_argument' });
+ }
+
+ const resolvedModel = resolveVisionModel(model);
+ const base64 = bytes.toString('base64');
+ const extraHeaders = {};
+ let assetId = null;
+ let imgTag;
+
+ if (base64.length < INLINE_B64_LIMIT) {
+ imgTag = `<img src="data:${contentType};base64,${base64}" />`;
+ } else {
+ assetId = await uploadAsset({ bytes, contentType, apiKey: key, timeoutMs });
+ imgTag = `<img src="data:${contentType};asset_id,${assetId}" />`;
+ extraHeaders['NVCF-INPUT-ASSET-REFERENCES'] = assetId;
+ }
+
+ const userPrompt = String(prompt || DEFAULT_VISION_PROMPT).slice(0, 2000);
+ const body = {
+ model: resolvedModel,
+ messages: [{ role: 'user', content: `${userPrompt} ${imgTag}` }],
+ max_tokens: Math.min(Math.max(Number(maxTokens) || 512, 16), 2048),
+ temperature: Math.min(Math.max(Number(temperature) || 0, 0), 1),
+ stream: false,
+ };
+
+ let res;
+ try {
+ res = await fetch(CHAT_URL, {
+ method: 'POST',
+ headers: {
+ authorization: `Bearer ${key}`,
+ 'content-type': 'application/json',
+ accept: 'application/json',
+ ...extraHeaders,
+ },
+ body: JSON.stringify(body),
+ signal: AbortSignal.timeout(timeoutMs),
+ });
+ } catch (e) {
+ const timedOut = e?.name === 'TimeoutError' || e?.name === 'AbortError';
+ throw Object.assign(new Error(`NVIDIA vision unreachable: ${e?.message}`), {
+ code: timedOut ? 'timeout' : 'provider_unreachable',
+ });
+ }
+
+ if (!res.ok) {
+ let detail = '';
+ try {
+ const j = await res.json();
+ detail = j?.detail || j?.message || j?.error?.message || JSON.stringify(j);
+ } catch {
+ detail = await res.text().catch(() => '');
+ }
+ throw providerError(res.status, detail);
+ }
+
+ const data = await res.json().catch(() => null);
+ const text = data?.choices?.[0]?.message?.content?.trim?.() || '';
+ if (!text) {
+ throw Object.assign(new Error('NVIDIA vision returned an empty completion'), { code: 'provider_error' });
+ }
+ return { text, model: resolvedModel, assetId };
+}
diff --git a/api/strategies.js b/api/strategies.js
index 8d3accc4b..42d9fccfd 100644
--- a/api/strategies.js
+++ b/api/strategies.js
@@ -128,15 +128,22 @@ async function handleList(req, res, auth) {
return json(res, 200, { data: { scope, strategies: rows.map((r) => publicStrategy(r, perf.get(r.id), names.get(r.owner_id))) } });
}
- // Published marketplace (public). An optional `author` filters to one creator's
- // published strategies — the agent-profile "strategies this creator publishes".
+ // Published marketplace (public). Optional filters: `author` (a user id) or
+ // `agent` (resolve that agent's creator server-side, so the agent-profile panel
+ // can show "strategies this creator publishes" without exposing the owner id).
const rl = await limits.publicIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
- const author = p.get('author');
+ let author = isUuid(p.get('author')) ? p.get('author') : null;
+ const agentParam = p.get('agent');
+ if (!author && isUuid(agentParam)) {
+ const [a] = await sql`SELECT user_id FROM agent_identities WHERE id = ${agentParam} AND deleted_at IS NULL`.catch(() => [null]);
+ author = a?.user_id || null;
+ if (!author) return json(res, 200, { data: { scope, sort, strategies: [] } });
+ }
const rows = await sql`
SELECT * FROM agent_strategies
WHERE published = true AND deleted_at IS NULL
- ${isUuid(author) ? sql`AND owner_id = ${author}` : sql``}
+ ${author ? sql`AND owner_id = ${author}` : sql``}
${q ? sql`AND (name ILIKE ${'%' + q + '%'} OR description ILIKE ${'%' + q + '%'})` : sql``}
ORDER BY ${sort === 'forks' ? sql`forks_count DESC` : sort === 'equips' ? sql`equips_count DESC` : sql`published_at DESC`}
LIMIT ${limit}
diff --git a/pages/agent-detail.html b/pages/agent-detail.html
index f19c18883..9dd07924d 100644
--- a/pages/agent-detail.html
+++ b/pages/agent-detail.html
@@ -595,6 +595,15 @@
<div id="ad-mirror-panel"></div>
</section>
+ <section class="ad-card" id="ad-strategy-objects-card" hidden>
+ <div class="ad-card-head">
+ <span class="ad-bullet"></span>
+ <h2>STRATEGIES</h2>
+ <a class="ad-card-link" href="/strategies" style="margin-left:auto;font-size:.7rem;color:var(--ink-dim,#888);text-decoration:none">Strategy library →</a>
+ </div>
+ <div id="ad-strategy-panel"></div>
+ </section>
+
<section class="ad-card">
<div class="ad-card-head">
<span class="ad-bullet ad-bullet-amber"></span>
diff --git a/pages/home.html b/pages/home.html
index 9f3420d22..1c45f5b57 100644
--- a/pages/home.html
+++ b/pages/home.html
@@ -40,6 +40,7 @@
<link rel="stylesheet" href="/tokens.css" />
<link rel="stylesheet" href="/buttons.css" />
<link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/economy-ticker.css" />
<style>
:root {
color-scheme: dark;
@@ -4276,6 +4277,22 @@
</div>
</section>
+<!-- ── LIVE ECONOMY ──────────────────────────────────────────────────── -->
+<section class="block">
+ <div class="wrap-1280">
+ <div class="block-head reveal">
+ <p class="block-eyebrow"><span class="num">05</span>Live economy</p>
+ <h2 class="block-h">Watch real value <em>move between agents.</em></h2>
+ <p class="block-lede">
+ Every tip, payment, trade, and token launch on three.ws is on-chain and explorer-verifiable. Here it is in real time — and the full 3D money map lives in the <a href="/galaxy" style="text-decoration:underline;">Agent Galaxy</a>.
+ </p>
+ </div>
+ <div class="reveal" style="max-width:640px;margin:0 auto;">
+ <div id="economyTicker"></div>
+ </div>
+ </div>
+</section>
+
<!-- ── ORACLE CONVICTION ─────────────────────────────────────────────── -->
<section class="block">
<div class="wrap-1280">
@@ -6020,6 +6037,7 @@
})();
</script>
<script type="module" src="/src/api-playground.js"></script>
+<script type="module" src="/src/economy-ticker.js"></script>
<script type="module">
// "Pose it here" pulls Three.js + OrbitControls + the full mannequin rig —
// load it only when the section approaches the viewport. The module
diff --git a/pages/strategies.html b/pages/strategies.html
new file mode 100644
index 000000000..1bf8c7c2f
--- /dev/null
+++ b/pages/strategies.html
@@ -0,0 +1,122 @@
+<!doctype html>
+<html lang="en">
+ <head>
+ <script>/* three.ws theme boot — no-flash; runtime in /theme-switcher.js */(function(){try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>
+ <meta charset="utf-8" />
+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />
+ <title>Strategies · three.ws</title>
+ <meta name="description" content="Trading know-how as a collectible. Equip a real, rule-based strategy on your agent and it trades for real, on-chain, strictly within your spend policy. Publish yours, fork the best, ranked by verified live performance." />
+ <meta property="og:type" content="website" />
+ <meta property="og:site_name" content="three.ws" />
+ <meta property="og:url" content="https://three.ws/strategies" />
+ <meta property="og:title" content="Strategies · three.ws" />
+ <meta property="og:description" content="Equip a real, rule-based strategy on your agent — trades on-chain within your spend policy. Publish, fork, and rank by verified live performance." />
+ <meta property="og:image" content="https://three.ws/api/page-og?s=crypto&amp;t=Strategies&amp;d=Equip+a+real%2C+rule-based+strategy+on+your+agent+%E2%80%94+on-chain%2C+within+your+spend+policy.&amp;p=%2Fstrategies" />
+ <meta property="og:image:width" content="1200" />
+ <meta property="og:image:height" content="630" />
+ <meta name="twitter:card" content="summary_large_image" />
+ <meta name="twitter:site" content="@trythreews" />
+ <meta name="twitter:title" content="Strategies · three.ws" />
+ <meta name="twitter:description" content="Ownable, forkable, leaderboard-ranked trade strategies — proven on real chain data. Equip one on your agent." />
+ <meta name="theme-color" content="#0a0a0a" />
+ <link rel="icon" href="/favicon.ico" sizes="any" />
+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />
+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />
+ <link rel="manifest" href="/site.webmanifest" />
+ <link rel="stylesheet" href="/fonts/fonts.css" />
+ <link rel="stylesheet" href="/tokens.css" />
+ <link rel="stylesheet" href="/nav.css" />
+ <link rel="stylesheet" href="/footer.css" />
+ <link rel="canonical" href="https://three.ws/strategies" />
+ <style>
+ body { background: var(--bg-0, #0a0a0a); color: var(--ink, #e8e8e8); margin: 0; font-family: var(--font-body, system-ui); }
+ .sp-shell { max-width: 960px; margin: 0 auto; padding: var(--space-lg, 24px) var(--space-md, 16px) var(--space-2xl, 64px); }
+ .sp-hero { text-align: center; padding: var(--space-xl, 42px) 0 var(--space-lg, 24px); }
+ .sp-kicker { display: inline-flex; align-items: center; gap: 8px; font-size: var(--text-2xs, .66rem); text-transform: uppercase; letter-spacing: .1em; color: var(--wallet-accent, #c4b5fd); margin: 0 0 12px; }
+ .sp-live-dot { width: 7px; height: 7px; border-radius: 50%; background: var(--success, #4ade80); box-shadow: 0 0 0 0 rgba(74,222,128,.5); animation: sp-pulse 1.8s ease infinite; }
+ @keyframes sp-pulse { 0%,100% { box-shadow: 0 0 0 0 rgba(74,222,128,.5); } 70% { box-shadow: 0 0 0 7px rgba(74,222,128,0); } }
+ .sp-title { font-family: var(--font-display, system-ui); font-size: clamp(1.8rem, 5vw, 2.8rem); margin: 0 0 12px; color: var(--ink-bright, #fff); letter-spacing: -.02em; }
+ .sp-sub { max-width: 640px; margin: 0 auto; font-size: var(--text-md, .95rem); line-height: 1.6; color: var(--ink-dim, #aaa); }
+ .sp-sub b { color: var(--wallet-accent, #c4b5fd); }
+ .sp-safety { display: flex; gap: 14px; flex-wrap: wrap; justify-content: center; margin-top: var(--space-md, 18px); }
+ .sp-safety span { display: inline-flex; align-items: center; gap: 6px; font-size: var(--text-2xs, .68rem); color: var(--ink-dim, #9a9a9a); }
+ .sp-safety b { color: var(--wallet-accent, #c4b5fd); }
+ .sp-bar { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; margin: var(--space-lg, 24px) 0 var(--space-md, 16px); }
+ .sp-seg { display: inline-flex; gap: 4px; background: var(--surface-1, rgba(255,255,255,.03)); padding: 4px; border-radius: var(--radius-pill, 999px); border: 1px solid var(--stroke, rgba(255,255,255,.08)); }
+ .sp-seg button { font: inherit; font-size: var(--text-2xs, .68rem); padding: 6px 14px; border-radius: 999px; border: none; background: transparent; color: var(--ink-dim, #aaa); cursor: pointer; transition: all .15s; }
+ .sp-seg button[aria-pressed="true"] { background: var(--wallet-accent, #c4b5fd); color: #1a1340; font-weight: 700; }
+ .sp-spacer { flex: 1 1 auto; }
+ .sp-new { font: inherit; font-size: var(--text-2xs, .72rem); font-weight: 700; padding: 9px 16px; border-radius: var(--radius-pill, 999px); border: none; background: var(--wallet-accent, #c4b5fd); color: #1a1340; cursor: pointer; transition: background .15s; }
+ .sp-new:hover { background: var(--wallet-accent-strong, #a78bfa); }
+ .sp-new:focus-visible { outline: 2px solid var(--wallet-focus, rgba(139,92,246,.7)); outline-offset: 2px; }
+ .sp-search { flex: 1 1 180px; min-width: 140px; font: inherit; font-size: var(--text-sm, .82rem); padding: 8px 12px; border-radius: var(--radius-pill, 999px); border: 1px solid var(--stroke, rgba(255,255,255,.1)); background: var(--surface-1, rgba(255,255,255,.03)); color: var(--ink-bright, #fff); }
+ .sp-search:focus { outline: none; border-color: var(--wallet-stroke-strong, rgba(139,92,246,.5)); }
+ .sp-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(280px, 1fr)); gap: var(--space-md, 14px); }
+ .sp-card { display: flex; flex-direction: column; gap: 8px; border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-lg, 14px); background: var(--surface-1, rgba(255,255,255,.025)); padding: var(--space-md, 16px); transition: border-color .18s, transform .18s; }
+ .sp-card:hover { border-color: var(--wallet-stroke, rgba(139,92,246,.35)); transform: translateY(-1px); }
+ .sp-card-top { display: flex; align-items: flex-start; gap: 8px; }
+ .sp-card-name { flex: 1 1 auto; min-width: 0; font-family: var(--font-display, inherit); font-size: var(--text-md, 1rem); font-weight: 700; color: var(--ink-bright, #fff); }
+ .sp-badge { flex: 0 0 auto; font-size: var(--text-2xs, .58rem); text-transform: uppercase; letter-spacing: .05em; padding: 3px 8px; border-radius: 999px; font-family: var(--font-mono, monospace); }
+ .sp-badge.proven { color: var(--success, #4ade80); background: rgba(74,222,128,.1); border: 1px solid rgba(74,222,128,.3); }
+ .sp-badge.unproven { color: var(--warn, #fbbf24); background: rgba(251,191,36,.08); border: 1px solid rgba(251,191,36,.25); }
+ .sp-desc { font-size: var(--text-xs, .74rem); color: var(--ink-dim, #aaa); line-height: 1.45; min-height: 1.4em; }
+ .sp-rules { font-size: var(--text-2xs, .66rem); color: var(--ink-dim, #9a9a9a); font-family: var(--font-mono, monospace); line-height: 1.5; }
+ .sp-stats { display: flex; gap: 12px; flex-wrap: wrap; font-family: var(--font-mono, monospace); font-size: var(--text-2xs, .68rem); color: var(--ink-dim, #9a9a9a); padding-top: 4px; border-top: 1px solid var(--stroke, rgba(255,255,255,.06)); }
+ .sp-stats .pos { color: var(--success, #4ade80); }
+ .sp-stats .neg { color: var(--danger, #f87171); }
+ .sp-meta { display: flex; align-items: center; gap: 8px; font-size: var(--text-2xs, .64rem); color: var(--ink-faint, #888); }
+ .sp-meta a { color: var(--ink-dim, #aaa); text-decoration: none; }
+ .sp-meta a:hover { color: var(--wallet-accent, #c4b5fd); }
+ .sp-actions { display: flex; gap: 6px; margin-top: 2px; }
+ .sp-btn { flex: 1; font: inherit; font-size: var(--text-2xs, .7rem); padding: 8px 10px; border-radius: var(--radius-sm, 8px); border: 1px solid var(--stroke-strong, rgba(255,255,255,.14)); background: var(--surface-2, rgba(255,255,255,.05)); color: var(--ink, #e8e8e8); cursor: pointer; transition: all .16s; white-space: nowrap; }
+ .sp-btn:hover { border-color: var(--wallet-stroke-strong, rgba(139,92,246,.5)); color: #fff; }
+ .sp-btn:focus-visible { outline: 2px solid var(--wallet-focus, rgba(139,92,246,.7)); outline-offset: 2px; }
+ .sp-btn-primary { background: var(--wallet-accent, #c4b5fd); color: #1a1340; border-color: transparent; font-weight: 700; }
+ .sp-btn-primary:hover { background: var(--wallet-accent-strong, #a78bfa); }
+ .sp-sk { height: 168px; border-radius: var(--radius-lg, 14px); background: linear-gradient(90deg, var(--surface-1, rgba(255,255,255,.03)) 25%, var(--surface-2, rgba(255,255,255,.05)) 50%, var(--surface-1, rgba(255,255,255,.03)) 75%); background-size: 200% 100%; animation: sp-sh 1.3s infinite; }
+ @keyframes sp-sh { from { background-position: 200% 0; } to { background-position: -200% 0; } }
+ .sp-empty { grid-column: 1 / -1; text-align: center; padding: var(--space-xl, 42px) var(--space-md, 16px); color: var(--ink-dim, #9a9a9a); font-size: var(--text-sm, .82rem); line-height: 1.6; }
+ .sp-empty strong { display: block; color: var(--ink-bright, #fff); font-family: var(--font-display, inherit); margin-bottom: 6px; }
+ .sp-rank { position: absolute; top: -8px; left: -8px; width: 26px; height: 26px; border-radius: 50%; display: flex; align-items: center; justify-content: center; font-family: var(--font-mono, monospace); font-size: var(--text-2xs, .66rem); font-weight: 700; background: var(--wallet-accent, #c4b5fd); color: #1a1340; box-shadow: var(--shadow-1, 0 2px 8px rgba(0,0,0,.4)); }
+ .sp-card { position: relative; }
+ </style>
+ </head>
+ <body>
+ <header><div id="nav-container"></div></header>
+ <script src="/nav.js"></script>
+
+ <main class="sp-shell">
+ <section class="sp-hero">
+ <p class="sp-kicker"><span class="sp-live-dot" aria-hidden="true"></span> Ownable alpha · proven on real chain data</p>
+ <h1 class="sp-title">Equip a strategy, not a spreadsheet</h1>
+ <p class="sp-sub">A Strategy Object is a real, rule-based plan — entry conditions, sizing, take-profit, stop-loss — made into a <b>thing you own</b>. Equip it on your agent and it trades for real, on-chain, strictly inside your spend policy. Publish yours, fork the best, and watch the leaderboard rank them by <b>verified live performance</b> — numbers no one can fake.</p>
+ <div class="sp-safety">
+ <span>🔒 <b>Spend-policy gated</b> — every trade</span>
+ <span>⚡ <b>Real on-chain</b> — no backtested fiction</span>
+ <span>🍴 <b>Forkable</b> — rules only, never wallet access</span>
+ <span>⛔ <b>Kill switch</b> — halt all at once</span>
+ </div>
+ </section>
+
+ <div class="sp-bar">
+ <div class="sp-seg" role="tablist" aria-label="Strategy view" id="sp-scope">
+ <button data-scope="published" aria-pressed="true">Marketplace</button>
+ <button data-scope="leaderboard" aria-pressed="false">Leaderboard</button>
+ <button data-scope="mine" aria-pressed="false">My library</button>
+ </div>
+ <input class="sp-search" id="sp-search" type="search" placeholder="Search strategies…" aria-label="Search strategies" />
+ <div class="sp-spacer"></div>
+ <button class="sp-new" id="sp-new">+ New strategy</button>
+ </div>
+
+ <div class="sp-grid" id="sp-grid">
+ <div class="sp-sk"></div><div class="sp-sk"></div><div class="sp-sk"></div>
+ </div>
+ </main>
+
+ <script type="module" src="/src/strategies.js"></script>
+ <script src="/brand.js" defer></script>
+ <div id="footer-container"></div>
+ <script src="/footer.js"></script>
+ </body>
+</html>
diff --git a/public/changelog.json b/public/changelog.json
index 0e3813d3c..9fb9bbd51 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-23T05:17:28.201Z",
+ "generated_at": "2026-06-23T05:18:04.424Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
diff --git a/public/economy-ticker.css b/public/economy-ticker.css
new file mode 100644
index 000000000..c1e9b9c1f
--- /dev/null
+++ b/public/economy-ticker.css
@@ -0,0 +1,241 @@
+/* Live Economy ticker — the embeddable face of the Galaxy Money-Cam.
+ Self-contained, design-token driven, dark-first. Every interactive element
+ has hover / focus-visible states; the list is a real, keyboard-navigable list. */
+
+.eco-ticker {
+ display: flex;
+ flex-direction: column;
+ gap: 12px;
+ padding: 18px;
+ border: 1px solid var(--hairline, #1c1c1c);
+ border-radius: 16px;
+ background:
+ radial-gradient(120% 140% at 100% 0%, rgba(196, 181, 253, 0.08), transparent 60%),
+ var(--surface-0, #0b0b0b);
+ font-family: var(--font-body, system-ui, sans-serif);
+ color: var(--text, #f6f6f6);
+}
+
+.eco-head {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+}
+.eco-title {
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+ text-decoration: none;
+ color: inherit;
+ border-radius: 8px;
+}
+.eco-title-main {
+ font-family: var(--font-display, var(--font-body));
+ font-weight: 700;
+ font-size: 1.02rem;
+ letter-spacing: -0.01em;
+}
+.eco-title-sub {
+ font-size: 0.72rem;
+ color: var(--text-3, #8a8a8a);
+}
+.eco-title:hover .eco-title-main { color: var(--wallet-accent, #c4b5fd); }
+
+.eco-status {
+ display: inline-flex;
+ align-items: center;
+ gap: 6px;
+ font-size: 0.68rem;
+ font-weight: 600;
+ letter-spacing: 0.04em;
+ text-transform: uppercase;
+ color: var(--text-3, #8a8a8a);
+ white-space: nowrap;
+}
+.eco-dot {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: currentColor;
+ box-shadow: 0 0 8px currentColor;
+}
+.eco-status--live { color: #4ade80; }
+.eco-status--live .eco-dot { animation: eco-pulse 2s ease-in-out infinite; }
+.eco-status--stale { color: #fbbf24; }
+@keyframes eco-pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.35; } }
+@media (prefers-reduced-motion: reduce) {
+ .eco-status--live .eco-dot { animation: none; }
+}
+
+/* Hottest earner — the discovery hook */
+.eco-hot {
+ display: flex;
+ flex-direction: column;
+ gap: 4px;
+ padding: 12px 14px;
+ border: 1px solid var(--wallet-stroke, rgba(139, 92, 246, 0.30));
+ border-radius: 12px;
+ background: var(--wallet-accent-soft, rgba(139, 92, 246, 0.10));
+}
+.eco-hot-eyebrow {
+ font-size: 0.64rem;
+ font-weight: 700;
+ letter-spacing: 0.08em;
+ text-transform: uppercase;
+ color: var(--wallet-accent, #c4b5fd);
+}
+.eco-hot-link {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 10px;
+ text-decoration: none;
+ color: inherit;
+}
+.eco-hot-name {
+ font-family: var(--font-display, var(--font-body));
+ font-weight: 700;
+ font-size: 1.05rem;
+ letter-spacing: -0.01em;
+}
+.eco-hot-link:hover .eco-hot-name { text-decoration: underline; }
+.eco-hot-amt {
+ font-family: var(--font-mono, ui-monospace, monospace);
+ font-size: 0.78rem;
+ color: var(--wallet-accent-strong, #a78bfa);
+ white-space: nowrap;
+}
+
+/* Window stats */
+.eco-stats {
+ display: flex;
+ flex-wrap: wrap;
+ gap: 14px;
+ font-size: 0.72rem;
+ color: var(--text-3, #8a8a8a);
+}
+.eco-stats:empty { display: none; }
+.eco-stats strong {
+ color: var(--text, #f6f6f6);
+ font-family: var(--font-mono, ui-monospace, monospace);
+ font-weight: 600;
+}
+
+/* Flow list */
+.eco-list {
+ list-style: none;
+ margin: 0;
+ padding: 0;
+ display: flex;
+ flex-direction: column;
+}
+.eco-row {
+ display: flex;
+ align-items: center;
+ gap: 4px;
+ border-top: 1px solid var(--hairline, #1c1c1c);
+}
+.eco-row:first-child { border-top: none; }
+.eco-row-link {
+ display: flex;
+ align-items: center;
+ gap: 10px;
+ flex: 1;
+ min-width: 0;
+ padding: 9px 4px;
+ text-decoration: none;
+ color: inherit;
+ border-radius: 8px;
+}
+.eco-row-link:hover { background: var(--surface-2, #181818); }
+.eco-kind {
+ flex: 0 0 auto;
+ width: 8px;
+ height: 8px;
+ border-radius: 50%;
+ background: var(--k, #9fb4d6);
+ box-shadow: 0 0 8px var(--k, #9fb4d6);
+}
+.eco-row-main {
+ flex: 1;
+ min-width: 0;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ white-space: nowrap;
+ font-size: 0.82rem;
+}
+.eco-row-amt {
+ flex: 0 0 auto;
+ font-family: var(--font-mono, ui-monospace, monospace);
+ font-size: 0.76rem;
+ color: var(--text-2, #a8a8a8);
+}
+.eco-row-ago {
+ flex: 0 0 auto;
+ width: 34px;
+ text-align: right;
+ font-size: 0.7rem;
+ color: var(--text-4, #6e6e6e);
+ font-variant-numeric: tabular-nums;
+}
+.eco-row-tx {
+ flex: 0 0 auto;
+ padding: 4px 6px;
+ color: var(--text-4, #6e6e6e);
+ font-size: 0.8rem;
+ text-decoration: none;
+ border-radius: 6px;
+}
+.eco-row-tx:hover { color: var(--wallet-accent, #c4b5fd); background: var(--surface-2, #181818); }
+
+/* Newly-arrived rows flash gently (skipped under reduced-motion via no class) */
+.eco-row--fresh { animation: eco-flash 1.4s ease-out; }
+@keyframes eco-flash {
+ 0% { background: var(--wallet-accent-fill, rgba(139, 92, 246, 0.15)); }
+ 100% { background: transparent; }
+}
+
+.eco-empty {
+ padding: 16px 4px;
+ font-size: 0.8rem;
+ color: var(--text-3, #8a8a8a);
+ text-align: center;
+}
+.eco-empty a { color: var(--wallet-accent, #c4b5fd); text-decoration: none; }
+.eco-empty a:hover { text-decoration: underline; }
+
+.eco-note {
+ margin: 0;
+ font-size: 0.72rem;
+ color: var(--text-3, #8a8a8a);
+}
+
+/* Loading skeleton */
+.eco-row--skeleton {
+ height: 38px;
+ border-top: 1px solid var(--hairline, #1c1c1c);
+ position: relative;
+ overflow: hidden;
+}
+.eco-row--skeleton::after {
+ content: '';
+ position: absolute;
+ inset: 0;
+ background: linear-gradient(90deg, transparent, var(--surface-2, #181818), transparent);
+ animation: eco-shimmer 1.3s ease-in-out infinite;
+}
+@keyframes eco-shimmer {
+ 0% { transform: translateX(-100%); }
+ 100% { transform: translateX(100%); }
+}
+@media (prefers-reduced-motion: reduce) {
+ .eco-row--skeleton::after { animation: none; opacity: 0.4; }
+}
+
+/* Shared focus ring for every interactive element in the widget */
+.eco-ticker a:focus-visible,
+.eco-ticker button:focus-visible {
+ outline: 2px solid var(--wallet-focus, rgba(139, 92, 246, 0.70));
+ outline-offset: 2px;
+}
diff --git a/public/features.json b/public/features.json
index 9f7dbf6cd..ef71af6a4 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-23T05:17:27.947Z",
+ "generated_at": "2026-06-23T05:18:04.345Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/agent-detail.js b/src/agent-detail.js
index 6820d06fc..e66c3d0ae 100644
--- a/src/agent-detail.js
+++ b/src/agent-detail.js
@@ -12,6 +12,7 @@ import { onchainBadgeEl } from './shared/onchain-badge.js';
import { walletChipEl } from './shared/agent-wallet-chip.js';
import { mountMoneyPulse } from './shared/money-pulse.js';
import { mountMirrorPanel } from './shared/agent-mirror-panel.js';
+import { mountStrategyPanel } from './shared/agent-strategy-panel.js';
import { mountValidationBadge } from './shared/validation-badge.js';
import { seeInWorldHref, agentAvatarGlb } from './shared/agent-3d.js';
import { hydrateAvatarWallet } from './shared/wallet-aura.js';
@@ -35,6 +36,7 @@ const coinStatusHandles = [];
// polling interval + observers don't leak.
let _pulseHandle = null;
let _mirrorHandle = null;
+let _strategyHandle = null;
// The hero's wallet aura controller — torn down on re-render/unload so its live
// poll + rAF never leak.
@@ -797,6 +799,20 @@ function render(agent) {
}
}
+ // Strategy Objects — equip a real, rule-based plan and the agent trades it for
+ // real within the spend policy (owner), or equip a strategy this creator
+ // publishes with your own agent (visitor). Sibling primitive to mirroring; the
+ // panel reveals its own card (#ad-strategy-objects-card) only when there's
+ // something to show.
+ {
+ const strategyPanel = $('ad-strategy-panel');
+ if (_strategyHandle) { try { _strategyHandle.destroy(); } catch { /* idempotent */ } _strategyHandle = null; }
+ const wMeta = agent.rawMetadata?.meta || {};
+ if (strategyPanel && wMeta.solana_address) {
+ _strategyHandle = mountStrategyPanel({ mount: strategyPanel, agent, isOwner: !!agent.isOwner });
+ }
+ }
+
// A re-render (avatar refresh) clears the token body below; tear down any
// coin-status widgets first so their refresh timers don't leak.
destroyCoinStatus();
diff --git a/src/economy-ticker-core.js b/src/economy-ticker-core.js
new file mode 100644
index 000000000..6997f5518
--- /dev/null
+++ b/src/economy-ticker-core.js
@@ -0,0 +1,128 @@
+// Pure, DOM-free helpers for the home-page Live Economy ticker — the compact,
+// embeddable sibling of the Galaxy Money-Cam. Both read the same real feed
+// (GET /api/galaxy/flows): every row is one on-chain, explorer-verifiable money
+// movement that touches a public three.ws agent. There are NO synthetic flows —
+// a quiet market shows an honest empty state, never invented activity.
+//
+// Kept side-effect-free (no fetch, no document, no Buffer) so the formatting and
+// "hottest earner" derivation are unit-testable without a browser or a database.
+
+// Per-kind accent colors — identical palette to the Money-Cam (src/galaxy.js)
+// so the home ticker and the 3D map read as one feature. Payments use the
+// wallet-violet family accent.
+export const KIND_COLORS = {
+ tip: '#4ade80',
+ trade: '#4589ff',
+ snipe: '#fbbf24',
+ payment: '#c4b5fd',
+ launch: '#ffd27a',
+};
+
+export const KIND_LABEL = {
+ tip: 'Tip',
+ trade: 'Trade',
+ snipe: 'Snipe',
+ payment: 'Pay',
+ launch: 'Launch',
+};
+
+export function formatUsd(v) {
+ const n = Number(v) || 0;
+ if (n <= 0) return '';
+ if (n < 1000) return `$${n.toFixed(n < 1 ? 2 : 0)}`;
+ if (n < 1_000_000) return `$${Math.round(n).toLocaleString()}`;
+ return `$${(n / 1_000_000).toFixed(2)}M`;
+}
+
+export function shortAddr(w) {
+ if (!w || typeof w !== 'string') return '';
+ return w.length > 10 ? `${w.slice(0, 4)}…${w.slice(-4)}` : w;
+}
+
+// Compact relative age. `now` is injectable so tests are deterministic.
+export function relTime(iso, now = Date.now()) {
+ const ms = now - new Date(iso).getTime();
+ if (!Number.isFinite(ms)) return '';
+ const s = Math.max(0, Math.round(ms / 1000));
+ if (s < 60) return `${s}s`;
+ const m = Math.round(s / 60);
+ if (m < 60) return `${m}m`;
+ const h = Math.round(m / 60);
+ if (h < 24) return `${h}h`;
+ return `${Math.round(h / 24)}d`;
+}
+
+// A short, human, screen-reader-friendly sentence for one flow. Never invents a
+// counterparty — a one-sided flow reads against the market / a bare wallet.
+export function flowHeadline(f) {
+ const actor = f.actor?.name || 'An agent';
+ if (f.kind === 'launch') return `${actor} launched $${f.symbol || f.coin_name || 'a coin'}`;
+ if (f.kind === 'tip') {
+ const from = f.from?.name || shortAddr(f.from?.wallet) || 'someone';
+ return `${from} tipped ${actor}`;
+ }
+ const to = f.to?.name || shortAddr(f.to?.wallet) || 'the market';
+ if (f.kind === 'payment') return `${actor} paid ${to}`;
+ if (f.kind === 'snipe') return `${actor} sniped ${to}`;
+ return `${actor} traded with ${to}`;
+}
+
+// The best click-through for a row: the agent's own profile (discovery) when we
+// have one, else the real explorer link for the transaction, else the galaxy.
+// Every destination is real — we never point a row at a dead end.
+export function rowHref(f) {
+ if (f.actor?.id) return `/agents/${f.actor.id}`;
+ if (f.kind === 'launch' && f.mint_explorer) return f.mint_explorer;
+ if (f.explorer) return f.explorer;
+ return '/galaxy';
+}
+
+// The real explorer link for a flow's underlying transaction (or mint), or null.
+export function flowExplorer(f) {
+ if (f.kind === 'launch') return f.mint_explorer || null;
+ return f.explorer || null;
+}
+
+// Honest window summary over exactly the flows we were handed.
+export function summarizeFlows(flows) {
+ const out = { count: 0, usd: 0, edges: 0, byKind: { tip: 0, trade: 0, snipe: 0, payment: 0, launch: 0 } };
+ if (!Array.isArray(flows)) return out;
+ for (const f of flows) {
+ if (!f) continue;
+ out.count++;
+ if (f.usd) out.usd += Number(f.usd) || 0;
+ if (f.counterparty?.id && f.actor?.id && f.counterparty.id !== f.actor.id) out.edges++;
+ if (out.byKind[f.kind] != null) out.byKind[f.kind]++;
+ }
+ return out;
+}
+
+// The hottest EARNING agent in the window: the public agent that RECEIVED the
+// most real USD (inbound tips + payments). Earnings credit the receiver (flow.to
+// for inbound value), never the actor of an outbound spend — so this is honest
+// "who is the crowd paying right now," a discovery hook for the home page.
+// Returns the top earner { id, name, wallet, usd, count } or null when the window
+// has no priced inbound value.
+export function hottestEarner(flows) {
+ if (!Array.isArray(flows)) return null;
+ const byAgent = new Map();
+ for (const f of flows) {
+ if (!f) continue;
+ // Inbound value lands on the receiver. Tips are direction 'in' (to = actor);
+ // agent→agent payments are 'out' (to = counterparty agent). Either way the
+ // USD credits whoever `to` resolves to — but only when `to` is a real agent.
+ const recv = f.to;
+ const usd = Number(f.usd) || 0;
+ if (!recv?.id || usd <= 0) continue;
+ if (f.kind !== 'tip' && f.kind !== 'payment') continue;
+ const prev = byAgent.get(recv.id) || { id: recv.id, name: recv.name || 'Agent', wallet: recv.wallet || null, usd: 0, count: 0 };
+ prev.usd += usd;
+ prev.count++;
+ byAgent.set(recv.id, prev);
+ }
+ let top = null;
+ for (const a of byAgent.values()) {
+ if (!top || a.usd > top.usd) top = a;
+ }
+ return top;
+}
diff --git a/src/economy-ticker.js b/src/economy-ticker.js
new file mode 100644
index 000000000..cb350b91e
--- /dev/null
+++ b/src/economy-ticker.js
@@ -0,0 +1,270 @@
+// Live Economy ticker — the compact, embeddable face of the Galaxy Money-Cam.
+//
+// Drops onto the home page (and any surface that wants it) a real, always-on
+// readout of value moving between three.ws agents: a headline "hottest earner
+// right now" discovery hook, window totals, and a keyboard-navigable, screen-
+// reader-readable list of the most recent on-chain flows — each one links
+// through to the agent and to its real transaction on Solscan. The whole widget
+// is a doorway into the full 3D map at /galaxy.
+//
+// Same real feed as the Money-Cam (GET /api/galaxy/flows). Every row is one
+// explorer-verifiable transfer; nothing is fabricated. When the market is quiet
+// the ticker says so honestly rather than inventing activity. Live updates come
+// from a cheap delta poll (cursor handed back as ?since=), paused when the tab is
+// hidden, with a clear "reconnecting" affordance on a dropped feed — mirroring
+// the galaxy's own live pattern.
+
+import {
+ KIND_COLORS,
+ KIND_LABEL,
+ formatUsd,
+ relTime,
+ flowHeadline,
+ rowHref,
+ flowExplorer,
+ summarizeFlows,
+ hottestEarner,
+} from './economy-ticker-core.js';
+
+const REDUCED_MOTION =
+ typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
+
+const POLL_MS = 12_000; // passive home widget — gentler than the galaxy's 6s
+const MAX_ROWS = 8; // compact: newest N flows
+const HISTORY_CAP = 60;
+
+function esc(s) {
+ return String(s == null ? '' : s).replace(/[&<>"']/g, (c) =>
+ ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]),
+ );
+}
+
+function mount(root) {
+ const state = {
+ history: [], // ascending by ts
+ seen: new Set(),
+ headCursor: null,
+ fails: 0,
+ started: false,
+ pollTimer: null,
+ freshIds: new Set(), // ids to flash on next render (skipped under reduced-motion)
+ };
+
+ root.classList.add('eco-ticker');
+ root.setAttribute('aria-label', 'Live economy — real value moving between agents');
+ renderShell(root);
+
+ const els = {
+ status: root.querySelector('.eco-status'),
+ hot: root.querySelector('.eco-hot'),
+ stats: root.querySelector('.eco-stats'),
+ list: root.querySelector('.eco-list'),
+ note: root.querySelector('.eco-note'),
+ };
+
+ async function fetchFlows(params) {
+ const qs = new URLSearchParams({ network: 'mainnet', type: 'all', limit: '24', ...params });
+ const res = await fetch(`/api/galaxy/flows?${qs.toString()}`, { headers: { accept: 'application/json' } });
+ if (!res.ok) throw new Error(`flows ${res.status}`);
+ const body = await res.json().catch(() => ({}));
+ return body?.data || null;
+ }
+
+ function ingest(flowsNewestFirst) {
+ const fresh = [];
+ for (const f of flowsNewestFirst || []) {
+ if (!f || state.seen.has(f.id)) continue;
+ state.seen.add(f.id);
+ fresh.push(f);
+ }
+ if (!fresh.length) return [];
+ fresh.reverse(); // ascending
+ state.history.push(...fresh);
+ state.history.sort((a, b) => (a.ts < b.ts ? -1 : a.ts > b.ts ? 1 : a.id < b.id ? -1 : 1));
+ if (state.history.length > HISTORY_CAP) {
+ state.history.splice(0, state.history.length - HISTORY_CAP);
+ state.seen = new Set(state.history.map((f) => f.id));
+ }
+ return fresh;
+ }
+
+ async function load() {
+ setStatus('live', 'Live');
+ try {
+ const data = await fetchFlows();
+ if (!data) throw new Error('no data');
+ state.history = [];
+ state.seen = new Set();
+ ingest(data.flows || []);
+ state.headCursor = data.head_cursor || null;
+ state.fails = 0;
+ setNote('');
+ render();
+ start();
+ } catch {
+ setStatus('stale', 'Offline');
+ setNote('Couldn’t reach the live economy — retrying. No flows are invented to fill the gap.');
+ scheduleRetry();
+ }
+ }
+
+ async function poll() {
+ if (document.hidden) return;
+ if (!state.headCursor) return load();
+ try {
+ const data = await fetchFlows({ since: state.headCursor });
+ if (!data) throw new Error('no data');
+ const fresh = ingest(data.flows || []);
+ if (data.head_cursor) state.headCursor = data.head_cursor;
+ state.fails = 0;
+ setStatus('live', 'Live');
+ setNote('');
+ if (fresh.length) {
+ if (!REDUCED_MOTION) state.freshIds = new Set(fresh.map((f) => f.id));
+ render();
+ }
+ } catch {
+ state.fails++;
+ if (state.fails >= 2) {
+ setStatus('stale', 'Reconnecting…');
+ setNote('Reconnecting to the live economy…');
+ }
+ }
+ }
+
+ function start() {
+ stop();
+ state.pollTimer = setInterval(poll, POLL_MS);
+ }
+ function stop() {
+ if (state.pollTimer) { clearInterval(state.pollTimer); state.pollTimer = null; }
+ }
+ let retryTimer = null;
+ function scheduleRetry() {
+ clearTimeout(retryTimer);
+ const delay = Math.min(30_000, 2_000 * 2 ** Math.min(4, state.fails));
+ state.fails++;
+ retryTimer = setTimeout(load, delay);
+ }
+
+ function setStatus(kind, label) {
+ if (!els.status) return;
+ els.status.className = `eco-status eco-status--${kind}`;
+ els.status.innerHTML = `<span class="eco-dot" aria-hidden="true"></span>${esc(label)}`;
+ }
+ function setNote(msg) {
+ if (!els.note) return;
+ els.note.textContent = msg || '';
+ els.note.hidden = !msg;
+ }
+
+ function render() {
+ const recent = state.history.slice(-MAX_ROWS).reverse();
+ const summary = summarizeFlows(state.history);
+ const hot = hottestEarner(state.history);
+
+ // Headline discovery hook: who the crowd is paying right now.
+ if (els.hot) {
+ if (hot) {
+ els.hot.hidden = false;
+ els.hot.innerHTML =
+ `<span class="eco-hot-eyebrow">Hottest earner right now</span>` +
+ `<a class="eco-hot-link" href="/agents/${esc(hot.id)}">` +
+ `<span class="eco-hot-name">${esc(hot.name)}</span>` +
+ `<span class="eco-hot-amt">${esc(formatUsd(hot.usd))} earned · ${hot.count} flow${hot.count > 1 ? 's' : ''}</span>` +
+ `</a>`;
+ } else {
+ els.hot.hidden = true;
+ }
+ }
+
+ if (els.stats) {
+ els.stats.innerHTML = summary.count
+ ? `<span><strong>${summary.count.toLocaleString()}</strong> flows</span>` +
+ `<span><strong>${esc(formatUsd(summary.usd) || '$0')}</strong> moved</span>` +
+ `<span><strong>${summary.edges.toLocaleString()}</strong> agent↔agent</span>`
+ : '';
+ }
+
+ if (!els.list) return;
+ if (!recent.length) {
+ els.list.innerHTML =
+ '<li class="eco-empty">The market is calm — no public agent flows in the last day. ' +
+ '<a href="/galaxy">Open the galaxy →</a></li>';
+ return;
+ }
+ els.list.innerHTML = recent
+ .map((f) => {
+ const c = KIND_COLORS[f.kind] || '#9fb4d6';
+ const amount = f.usd
+ ? formatUsd(f.usd)
+ : f.kind === 'launch'
+ ? `$${esc(f.symbol || 'coin')}`
+ : f.sol != null
+ ? `${(+f.sol).toFixed(3)} SOL`
+ : '';
+ const explorer = flowExplorer(f);
+ const fresh = state.freshIds.has(f.id) ? ' eco-row--fresh' : '';
+ return (
+ `<li class="eco-row${fresh}">` +
+ `<a class="eco-row-link" href="${esc(rowHref(f))}">` +
+ `<span class="eco-kind" style="--k:${c}" title="${esc(KIND_LABEL[f.kind] || 'Flow')}" aria-hidden="true"></span>` +
+ `<span class="eco-row-main">${esc(flowHeadline(f))}</span>` +
+ `<span class="eco-row-amt">${esc(amount)}</span>` +
+ `<span class="eco-row-ago">${esc(relTime(f.ts))}</span>` +
+ `</a>` +
+ (explorer
+ ? `<a class="eco-row-tx" href="${esc(explorer)}" target="_blank" rel="noopener" aria-label="View transaction on Solscan">↗</a>`
+ : '') +
+ `</li>`
+ );
+ })
+ .join('');
+ state.freshIds = new Set();
+ }
+
+ document.addEventListener('visibilitychange', () => {
+ if (document.hidden) stop();
+ else if (state.started) { start(); poll(); }
+ });
+
+ state.started = true;
+ load();
+
+ return { destroy() { stop(); clearTimeout(retryTimer); } };
+}
+
+function renderShell(root) {
+ root.innerHTML =
+ `<div class="eco-head">` +
+ `<a class="eco-title" href="/galaxy">` +
+ `<span class="eco-title-main">Live economy</span>` +
+ `<span class="eco-title-sub">real value moving between agents → the galaxy</span>` +
+ `</a>` +
+ `<span class="eco-status eco-status--live"><span class="eco-dot" aria-hidden="true"></span>Live</span>` +
+ `</div>` +
+ `<div class="eco-hot" hidden></div>` +
+ `<div class="eco-stats" aria-live="polite"></div>` +
+ `<ul class="eco-list" aria-live="polite" aria-label="Most recent agent money flows">` +
+ `<li class="eco-row eco-row--skeleton"></li>`.repeat(4) +
+ `</ul>` +
+ `<p class="eco-note" hidden></p>`;
+}
+
+function boot() {
+ const root = document.getElementById('economyTicker');
+ if (root && !root.dataset.ecoMounted) {
+ root.dataset.ecoMounted = '1';
+ mount(root);
+ }
+}
+
+if (typeof document !== 'undefined') {
+ if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', boot, { once: true });
+ } else {
+ boot();
+ }
+}
+
+export { mount };
diff --git a/src/irl.js b/src/irl.js
index 5c73ef1dc..d68070940 100644
--- a/src/irl.js
+++ b/src/irl.js
@@ -1998,13 +1998,6 @@ function anchorGpsPin() {
const mLng = 111320 * Math.cos(gpsState.lat * (Math.PI / 180));
const pinLat = gpsState.lat + (-avatarRig.position.z / mLat);
const pinLng = gpsState.lng + ( avatarRig.position.x / mLng);
- // Close-range placement (a spot on a table, a chair) needs sub-metre anchoring,
- // which GPS never delivers. Only hand rendering to the viewer-centric GPS frame
- // when the fix is accurate enough not to make things worse — outdoors with a
- // clear sky. Indoors the fix is far too coarse (tens of metres), so keep the
- // rock-solid local gyro lock that holds the avatar exactly where it was dropped;
- // the pin still persists below for nearby discovery, and onGPSPosition() upgrades
- // to the GPS frame the moment a fix lands under GPS_RENDER_MAX_ACC_M.
// Local→GPS upgrade: glide the camera from the gyro pivot to the viewer origin
// instead of snapping. The avatar holds its world spot (its placed position is the
// pin's round-trip), so easing the only thing that moves — the camera — keeps it
diff --git a/src/shared/agent-strategy-panel.js b/src/shared/agent-strategy-panel.js
new file mode 100644
index 000000000..eac63f195
--- /dev/null
+++ b/src/shared/agent-strategy-panel.js
@@ -0,0 +1,329 @@
+// Shared Strategy Object panel — equipped, leashed, autonomous trading made into a
+// first-class surface on the agent detail page. Renders by viewer role:
+//
+// • Owner of the viewed agent → manage the strategies THIS agent runs: the global
+// kill switch (leash), each equip with its live P&L + positions, pause/unequip,
+// "Run now", and "+ Equip a strategy" (from your library or the marketplace).
+// • Visitor → the strategies THIS agent's creator publishes (equip one with your
+// own agent — the sibling primitive to mirroring), or a browse-the-library CTA.
+// • Logged-out → the same discovery + a sign-in prompt.
+//
+// 100% real: equips, positions, and P&L all come from /api/agents/:id/strategies
+// (real fills, real signatures, real spend-policy caps). No mock positions.
+
+import { apiFetch } from '../api.js';
+import {
+ ensureStrategyStyles, esc, shortAddr, fmtSol, timeAgo, toast, configSummary,
+ openStrategyEditor, openEquipPicker, VIOLET,
+} from './strategy-forms.js';
+
+const STYLE_ID = 'sop-panel-styles';
+function ensurePanelStyles() {
+ ensureStrategyStyles();
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;
+ const s = document.createElement('style');
+ s.id = STYLE_ID;
+ s.textContent = `
+.sop { font-family: var(--font-body, system-ui); color: var(--ink, #e8e8e8); display: flex; flex-direction: column; gap: var(--space-sm, 10px); }
+.sop-sk { height: 56px; border-radius: var(--radius-md, 10px); background: linear-gradient(90deg, var(--surface-1, rgba(255,255,255,.03)) 25%, var(--surface-2, rgba(255,255,255,.05)) 50%, var(--surface-1, rgba(255,255,255,.03)) 75%); background-size: 200% 100%; animation: sop-sh 1.3s infinite; }
+@keyframes sop-sh { from { background-position: 200% 0; } to { background-position: -200% 0; } }
+.sop-empty { text-align: center; padding: var(--space-lg, 22px) var(--space-md, 16px); color: var(--ink-dim, #9a9a9a); font-size: var(--text-sm, .8rem); line-height: 1.5; }
+.sop-empty strong { color: var(--ink-bright, #fff); display: block; margin-bottom: 4px; font-family: var(--font-display, inherit); }
+.sop-err { color: var(--danger, #f87171); font-size: var(--text-sm, .8rem); padding: var(--space-sm, 10px); }
+.sop-leash { display: flex; align-items: center; gap: var(--space-sm, 10px); padding: var(--space-sm, 10px) var(--space-md, 14px); border: 1px solid var(--wallet-stroke, rgba(139,92,246,.3)); border-radius: var(--radius-md, 10px); background: var(--wallet-accent-soft, rgba(139,92,246,.08)); }
+.sop-leash-ico { width: 24px; height: 24px; flex: 0 0 auto; color: ${VIOLET}; }
+.sop-leash-txt { flex: 1 1 auto; font-size: var(--text-xs, .72rem); color: var(--ink-dim, #b8b8b8); line-height: 1.4; }
+.sop-leash-txt b { color: ${VIOLET}; font-family: var(--font-mono, monospace); }
+.sop-toggle { display: inline-flex; align-items: center; gap: 7px; cursor: pointer; user-select: none; font-size: var(--text-2xs, .68rem); color: var(--ink-dim, #b8b8b8); }
+.sop-switch { width: 38px; height: 22px; border-radius: 999px; background: var(--surface-3, rgba(255,255,255,.1)); position: relative; transition: background var(--duration-fast, .18s) var(--ease-standard, ease); flex: 0 0 auto; }
+.sop-switch::after { content: ''; position: absolute; top: 2px; left: 2px; width: 18px; height: 18px; border-radius: 50%; background: #fff; transition: transform var(--duration-fast, .18s) var(--ease-standard, ease); }
+.sop-switch[data-on="true"] { background: var(--danger, #f87171); }
+.sop-switch[data-on="true"]::after { transform: translateX(16px); }
+.sop-switch.go[data-on="true"] { background: var(--success, #4ade80); }
+.sop-row { display: flex; align-items: center; justify-content: space-between; gap: var(--space-sm, 10px); }
+.sop-equip { border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md, 10px); background: var(--surface-1, rgba(255,255,255,.03)); padding: var(--space-sm, 10px) var(--space-md, 12px); transition: border-color .18s; }
+.sop-equip:hover { border-color: var(--wallet-stroke, rgba(139,92,246,.3)); }
+.sop-equip[data-paused="true"] { opacity: .6; }
+.sop-eq-head { display: flex; align-items: center; gap: var(--space-sm, 10px); }
+.sop-eq-body { flex: 1 1 auto; min-width: 0; }
+.sop-eq-name { font-size: var(--text-sm, .84rem); font-weight: 600; color: var(--ink-bright, #fff); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.sop-eq-sum { font-size: var(--text-2xs, .64rem); color: var(--ink-dim, #9a9a9a); margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.sop-eq-actions { display: flex; align-items: center; gap: 6px; flex: 0 0 auto; }
+.sop-perf { display: flex; gap: 10px; flex-wrap: wrap; margin-top: 7px; font-family: var(--font-mono, monospace); font-size: var(--text-2xs, .64rem); color: var(--ink-dim, #9a9a9a); }
+.sop-perf .pos { color: var(--success, #4ade80); }
+.sop-perf .neg { color: var(--danger, #f87171); }
+.sop-perf .unproven { color: var(--warn, #fbbf24); }
+.sop-pos { margin-top: 7px; display: flex; flex-direction: column; gap: 4px; }
+.sop-p { display: flex; align-items: center; gap: 8px; font-size: var(--text-2xs, .66rem); padding: 5px 8px; border-radius: var(--radius-sm, 6px); background: var(--surface-1, rgba(255,255,255,.025)); }
+.sop-dot { width: 7px; height: 7px; border-radius: 50%; flex: 0 0 auto; }
+.sop-dot.open { background: var(--success, #4ade80); }
+.sop-dot.closing { background: var(--warn, #fbbf24); }
+.sop-dot.closed { background: var(--ink-dim, #888); }
+.sop-dot.failed { background: var(--danger, #f87171); }
+.sop-p-main { flex: 1 1 auto; min-width: 0; color: var(--ink, #ddd); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+.sop-p-pnl { font-family: var(--font-mono, monospace); flex: 0 0 auto; }
+.sop-p-pnl.pos { color: var(--success, #4ade80); }
+.sop-p-pnl.neg { color: var(--danger, #f87171); }
+.sop-p a { color: ${VIOLET}; text-decoration: none; }
+.sop-btn { font: inherit; font-size: var(--text-2xs, .66rem); padding: 5px 9px; border-radius: var(--radius-sm, 6px); border: 1px solid var(--stroke-strong, rgba(255,255,255,.14)); background: var(--surface-2, rgba(255,255,255,.05)); color: var(--ink, #e8e8e8); cursor: pointer; transition: all .16s; white-space: nowrap; }
+.sop-btn:hover { border-color: var(--wallet-stroke-strong, rgba(139,92,246,.5)); color: #fff; }
+.sop-btn:focus-visible { outline: 2px solid var(--wallet-focus, rgba(139,92,246,.7)); outline-offset: 2px; }
+.sop-btn-primary { background: ${VIOLET}; color: #1a1340; border-color: transparent; font-weight: 700; }
+.sop-btn-primary:hover { background: var(--wallet-accent-strong, #a78bfa); }
+.sop-btn-danger { color: var(--danger, #f87171); border-color: var(--danger, #f87171); background: transparent; }
+.sop-btn-ico { padding: 5px 8px; line-height: 1; }
+.sop-h { font-size: var(--text-2xs, .64rem); text-transform: uppercase; letter-spacing: .07em; color: var(--ink-dim, #9a9a9a); margin: var(--space-xs, 8px) 0 2px; }
+.sop-add { text-align: center; }
+.sop-mp-card { border: 1px solid var(--stroke, rgba(255,255,255,.08)); border-radius: var(--radius-md, 10px); background: var(--surface-1, rgba(255,255,255,.03)); padding: var(--space-sm, 10px) var(--space-md, 12px); display: flex; align-items: center; gap: 10px; margin-bottom: 6px; }
+.sop-mp-body { flex: 1 1 auto; min-width: 0; }
+.sop-mp-name { font-size: var(--text-sm, .82rem); font-weight: 600; color: var(--ink-bright, #fff); }
+.sop-mp-sum { font-size: var(--text-2xs, .62rem); color: var(--ink-dim, #9a9a9a); margin-top: 2px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+`;
+ document.head.appendChild(s);
+}
+
+const LEASH_SVG = '<svg class="sop-leash-ico" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.7" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M18 8a6 6 0 0 0-12 0c0 7-3 9-3 9h18s-3-2-3-9"/><path d="M13.7 21a2 2 0 0 1-3.4 0"/></svg>';
+
+export function mountStrategyPanel({ mount, agent, isOwner = false }) {
+ if (!mount) return { destroy() {} };
+ ensurePanelStyles();
+ const card = mount.closest('#ad-strategy-objects-card') || mount.parentElement;
+ const agentId = agent.id;
+ let alive = true;
+ const isLoggedIn = () => window.__authed !== false;
+ const root = document.createElement('div');
+ root.className = 'sop';
+ mount.replaceChildren(root);
+ root.innerHTML = '<div class="sop-sk"></div><div class="sop-sk"></div>';
+
+ const show = () => { if (card) card.hidden = false; };
+ const hide = () => { if (card) card.hidden = true; };
+
+ function pnlClass(v) { return v > 0 ? 'pos' : v < 0 ? 'neg' : ''; }
+
+ function perfLine(p) {
+ if (!p || !p.proven) return `<span class="unproven">Unproven — no closed trades yet</span>`;
+ const roi = p.roi_pct != null ? `<span class="${pnlClass(p.roi_pct)}">${p.roi_pct > 0 ? '+' : ''}${p.roi_pct}% ROI</span>` : '';
+ const pnl = `<span class="${pnlClass(p.pnl_sol)}">${p.pnl_sol > 0 ? '+' : ''}◎${fmtSol(p.pnl_sol)}</span>`;
+ const win = p.win_rate != null ? `<span>${p.win_rate}% win</span>` : '';
+ return `${roi}${pnl}${win}<span>${p.trades} closed${p.open ? ` · ${p.open} open` : ''}</span>`;
+ }
+
+ function positionRow(p) {
+ const cls = p.status === 'open' ? 'open' : p.status === 'closing' ? 'closing' : p.status === 'failed' ? 'failed' : 'closed';
+ const live = p.status === 'open' || p.status === 'closing';
+ const pnl = p.pnl_sol != null ? p.pnl_sol : (live && p.value_sol != null && p.entry_sol != null ? p.value_sol - p.entry_sol : null);
+ const pnlPct = p.entry_sol > 0 && pnl != null ? (pnl / p.entry_sol) * 100 : null;
+ const sig = (p.exit_sig || p.entry_sig) ? ` <a href="https://solscan.io/tx/${esc(p.exit_sig || p.entry_sig)}" target="_blank" rel="noopener" title="View on Solscan">↗</a>` : '';
+ const label = live
+ ? `holding ${esc(p.symbol || shortAddr(p.mint))} · in ◎${fmtSol(p.entry_sol)}${p.value_sol != null ? ` → ◎${fmtSol(p.value_sol)}` : ''}`
+ : `${esc(exitWord(p.exit_reason))} ${esc(p.symbol || shortAddr(p.mint))} · ◎${fmtSol(p.entry_sol)} → ◎${fmtSol(p.exit_sol)}`;
+ const pnlEl = pnl != null ? `<span class="sop-p-pnl ${pnlClass(pnl)}">${pnl > 0 ? '+' : ''}◎${fmtSol(pnl)}${pnlPct != null ? ` (${pnlPct > 0 ? '+' : ''}${pnlPct.toFixed(0)}%)` : ''}</span>` : '';
+ return `<div class="sop-p"><span class="sop-dot ${cls}"></span><span class="sop-p-main">${label}${sig}</span>${pnlEl}</div>`;
+ }
+ function exitWord(r) {
+ return ({ take_profit: 'TP hit', stop_loss: 'stopped out', trailing_stop: 'trailed out', timeout: 'held out', manual: 'closed', kill_switch: 'killed', error: 'errored' })[r] || 'closed';
+ }
+
+ function renderOwner(d) {
+ const positionsByEquip = new Map();
+ for (const p of d.positions || []) {
+ if (!positionsByEquip.has(p.equip_id)) positionsByEquip.set(p.equip_id, []);
+ positionsByEquip.get(p.equip_id).push(p);
+ }
+ const equipsHtml = d.equips.length
+ ? d.equips.map((e) => {
+ const ps = (positionsByEquip.get(e.equip_id) || []).slice(0, 4);
+ return `<div class="sop-equip" data-equip="${esc(e.equip_id)}" data-paused="${!e.active}">
+ <div class="sop-eq-head">
+ <div class="sop-eq-body">
+ <div class="sop-eq-name">${esc(e.strategy_name)}${e.network === 'devnet' ? ' · devnet' : ''}</div>
+ <div class="sop-eq-sum">${configSummary(e.config)}</div>
+ </div>
+ <div class="sop-eq-actions">
+ <label class="sop-toggle" title="${e.active ? 'Pause' : 'Resume'} this strategy"><span class="sop-switch go" data-on="${e.active}" data-act="toggle"></span></label>
+ <button class="sop-btn sop-btn-ico sop-btn-danger" data-act="unequip" title="Unequip">✕</button>
+ </div>
+ </div>
+ <div class="sop-perf">${perfLine(e.performance)}${e.last_fired_at ? `<span>last fired ${timeAgo(e.last_fired_at)}</span>` : ''}</div>
+ ${ps.length ? `<div class="sop-pos">${ps.map(positionRow).join('')}</div>` : ''}
+ </div>`;
+ }).join('')
+ : `<div class="sop-empty"><strong>No strategy equipped</strong>Equip a rule-based plan and this agent trades it for real — within your spend policy. <br><a href="/strategies" style="color:${VIOLET}">Browse strategies →</a></div>`;
+
+ root.innerHTML = `
+ <div class="sop-leash">
+ ${LEASH_SVG}
+ <div class="sop-leash-txt">${d.killed
+ ? 'Strategies are <b>halted</b> by your kill switch. No strategy will trade until you turn it back on.'
+ : `Leashed autonomy: ${d.equips.filter((e) => e.active).length} active ${d.equips.filter((e) => e.active).length === 1 ? 'strategy' : 'strategies'}, strictly inside your spend policy. Stop anytime.`}</div>
+ <label class="sop-toggle" title="${d.killed ? 'Resume all strategies' : 'Halt ALL strategies instantly'}">${d.killed ? 'Killed' : 'Kill'} <span class="sop-switch" data-on="${d.killed}" data-act="kill"></span></label>
+ </div>
+ <div class="sop-row">
+ <div style="font-size:var(--text-2xs,.64rem);color:var(--ink-dim,#9a9a9a)">${d.equips.length} equipped</div>
+ <button class="sop-btn" data-act="run" ${d.killed ? 'disabled' : ''} title="Evaluate launches & positions now">↻ Run now</button>
+ </div>
+ <div id="sop-equips">${equipsHtml}</div>
+ <div class="sop-add"><button class="sop-btn sop-btn-primary" data-act="equip" style="margin-top:4px">+ Equip a strategy</button> <a class="sop-btn" href="/strategies" style="text-decoration:none;display:inline-block">Open library</a></div>`;
+ wireOwner(d);
+ }
+
+ function wireOwner(d) {
+ root.querySelector('[data-act="kill"]')?.parentElement?.addEventListener('click', async (e) => {
+ e.preventDefault();
+ await postAction('kill', { killed: !d.killed }, !d.killed ? 'All strategies halted' : 'Strategies resumed');
+ load();
+ });
+ root.querySelector('[data-act="run"]')?.addEventListener('click', async (e) => {
+ const btn = e.currentTarget; btn.disabled = true; btn.textContent = 'Running…';
+ try {
+ const res = await apiFetch(`/api/agents/${agentId}/strategies/sweep`, { method: 'POST' });
+ const j = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(j?.error?.message || 'Run failed');
+ const all = (j.data?.results || []).flatMap((r) => r.results || []);
+ const exec = all.filter((r) => r.status === 'executed').length;
+ const skip = all.filter((r) => r.status === 'skipped').length;
+ toast(all.length ? `Evaluated: ${exec} executed, ${skip} skipped` : 'No entries or exits this run');
+ } catch (err) { if (!err?.redirected) toast(err.message || 'Run failed'); }
+ load();
+ });
+ root.querySelector('[data-act="equip"]')?.addEventListener('click', () => openEquipFlow());
+ root.querySelectorAll('.sop-equip').forEach((row) => {
+ const equipId = row.dataset.equip;
+ const e = d.equips.find((x) => x.equip_id === equipId);
+ row.querySelector('[data-act="toggle"]')?.parentElement?.addEventListener('click', async (ev) => {
+ ev.preventDefault();
+ await postAction('toggle', { equip_id: equipId, active: !e.active }, e.active ? 'Strategy paused' : 'Strategy resumed');
+ load();
+ });
+ row.querySelector('[data-act="unequip"]')?.addEventListener('click', async () => {
+ if (!confirm(`Unequip “${e.strategy_name}”? Open positions stay yours to manage; no new entries start.`)) return;
+ await postAction('unequip', { equip_id: equipId }, 'Strategy unequipped');
+ load();
+ });
+ });
+ }
+
+ async function postAction(action, body, okMsg) {
+ try {
+ const res = await apiFetch(`/api/agents/${agentId}/strategies/${action}`, {
+ method: 'POST', headers: { 'content-type': 'application/json' }, body: JSON.stringify(body || {}),
+ });
+ if (!res.ok) { const j = await res.json().catch(() => ({})); throw new Error(j?.error?.message || 'Action failed'); }
+ if (okMsg) toast(okMsg);
+ } catch (e) { if (!e?.redirected) toast(e.message || 'Action failed'); }
+ }
+
+ // Owner "+ Equip": pick a strategy from your library (or create one), then equip it here.
+ async function openEquipFlow() {
+ let mine = [];
+ try {
+ const res = await apiFetch('/api/strategies?scope=mine&limit=40', { allowAnonymous: true });
+ if (res.ok) mine = (await res.json()).data?.strategies || [];
+ } catch { /* handled below */ }
+ ensurePanelStyles();
+ const back = document.createElement('div');
+ back.className = 'so-modal-back';
+ const listHtml = mine.length
+ ? mine.map((s) => `<button type="button" class="so-pick" data-id="${esc(s.id)}"><div class="so-av"></div><span style="min-width:0"><span class="so-pname" style="display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">${esc(s.name)}</span><span style="font-size:var(--text-2xs,.62rem);color:var(--ink-dim,#9a9a9a);display:block;white-space:nowrap;overflow:hidden;text-overflow:ellipsis">${configSummary(s.config)}</span></span></button>`).join('')
+ : `<div class="sop-empty" style="padding:14px"><strong>Your library is empty</strong>Create your first strategy, or browse the marketplace.</div>`;
+ back.innerHTML = `<div class="so-modal" role="dialog" aria-modal="true" aria-label="Equip a strategy">
+ <h3>Equip a strategy on ${esc(agent.name || 'this agent')}</h3>
+ <p class="so-sub">Pick one of your strategies to run on this agent, or build a new one. It trades within this agent's spend policy.</p>
+ ${listHtml}
+ <div class="so-actions" style="justify-content:space-between">
+ <button type="button" class="so-btn" id="sop-new">+ New strategy</button>
+ <span><a class="so-btn" href="/strategies" style="text-decoration:none;display:inline-block">Marketplace</a> <button type="button" class="so-btn" id="sop-eq-cancel">Close</button></span>
+ </div>
+ </div>`;
+ const close = () => { back.remove(); document.removeEventListener('keydown', onKey); };
+ const onKey = (ev) => { if (ev.key === 'Escape') close(); };
+ back.addEventListener('click', (ev) => { if (ev.target === back) close(); });
+ document.addEventListener('keydown', onKey);
+ back.querySelector('#sop-eq-cancel').addEventListener('click', close);
+ back.querySelector('#sop-new').addEventListener('click', async () => {
+ close();
+ const created = await openStrategyEditor({});
+ if (created?.id) { await equipStrategyHere(created.id); load(); }
+ });
+ back.querySelectorAll('[data-id]').forEach((b) => b.addEventListener('click', async () => {
+ close();
+ await equipStrategyHere(b.dataset.id);
+ load();
+ }));
+ document.body.appendChild(back);
+ }
+
+ async function equipStrategyHere(strategyId) {
+ try {
+ const res = await apiFetch(`/api/agents/${agentId}/strategies`, {
+ method: 'POST', headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ strategy_id: strategyId }),
+ });
+ const j = await res.json().catch(() => ({}));
+ if (!res.ok) throw new Error(j?.error?.message || 'Could not equip');
+ toast('Strategy equipped — running within this agent’s limits');
+ } catch (e) { if (!e?.redirected) toast(e.message || 'Could not equip'); }
+ }
+
+ // Visitor / logged-out: surface the strategies THIS agent's creator publishes —
+ // equip one with your OWN agent (the sibling primitive to mirroring).
+ async function renderVisitor() {
+ let published = [];
+ try {
+ // Resolve the creator server-side from the agent id (the public agent
+ // response omits owner_id) so we can show what this creator publishes.
+ const res = await apiFetch(`/api/strategies?scope=published&agent=${encodeURIComponent(agentId)}&limit=12`, { allowAnonymous: true });
+ if (res.ok) published = (await res.json()).data?.strategies || [];
+ } catch { /* fall through to hide */ }
+ if (!published.length) { hide(); return; }
+ show();
+ const cardsHtml = published.map((s) => {
+ const p = s.performance || {};
+ const perf = p.proven
+ ? `<span class="${p.roi_pct > 0 ? 'pos' : p.roi_pct < 0 ? 'neg' : ''}" style="font-family:var(--font-mono,monospace)">${p.roi_pct != null ? `${p.roi_pct > 0 ? '+' : ''}${p.roi_pct}% ROI · ` : ''}${p.trades} trades</span>`
+ : '<span style="color:var(--warn,#fbbf24)">Unproven</span>';
+ return `<div class="sop-mp-card">
+ <div class="sop-mp-body">
+ <div class="sop-mp-name">${esc(s.name)}</div>
+ <div class="sop-mp-sum">${configSummary(s.config)}</div>
+ <div class="sop-perf" style="margin-top:4px">${perf}</div>
+ </div>
+ <button class="sop-btn sop-btn-primary" data-equip-id="${esc(s.id)}" data-name="${esc(s.name)}">Equip</button>
+ </div>`;
+ }).join('');
+ root.innerHTML = `
+ <div style="font-size:var(--text-xs,.72rem);color:var(--ink-dim,#9a9a9a);margin-bottom:4px">Strategies <b style="color:${VIOLET}">${esc(agent.name || 'this creator')}</b> publishes — equip one with your own agent. It runs inside <b style="color:${VIOLET}">your</b> spend policy.</div>
+ ${cardsHtml}
+ <div class="sop-add" style="margin-top:6px"><a class="sop-btn" href="/strategies" style="text-decoration:none;display:inline-block">Browse all strategies →</a></div>`;
+ root.querySelectorAll('[data-equip-id]').forEach((b) => b.addEventListener('click', async () => {
+ const s = published.find((x) => x.id === b.dataset.equipId);
+ if (!isLoggedIn()) { location.href = `/login?next=${encodeURIComponent(location.pathname)}`; return; }
+ await openEquipPicker({ strategy: s });
+ }));
+ }
+
+ async function load() {
+ if (!alive) return;
+ try {
+ if (isOwner) {
+ const res = await apiFetch(`/api/agents/${agentId}/strategies`, { allowAnonymous: true });
+ if (res.status === 403 || res.status === 401) { renderVisitor(); return; }
+ if (!res.ok) throw new Error('load failed');
+ const d = (await res.json()).data;
+ show();
+ renderOwner(d);
+ } else {
+ renderVisitor();
+ }
+ } catch (e) {
+ if (e?.redirected) return;
+ root.innerHTML = `<div class="sop-err">Couldn't load strategies. <button class="sop-btn" id="sop-retry">Retry</button></div>`;
+ root.querySelector('#sop-retry')?.addEventListener('click', load);
+ show();
+ }
+ }
+
+ load();
+ return { destroy() { alive = false; mount.replaceChildren(); } };
+}
diff --git a/src/shared/agent-wealth-state.js b/src/shared/agent-wealth-state.js
new file mode 100644
index 000000000..b08c87658
--- /dev/null
+++ b/src/shared/agent-wealth-state.js
@@ -0,0 +1,185 @@
+/**
+ * Embodied Finance — the agent's live wealth state, the single source of truth
+ * for the DYNAMICS that ride on top of the static net-worth aura.
+ *
+ * `wallet-networth.js` answers "how much is this wallet worth, and therefore how
+ * bright is its baseline aura." This module answers the second, livelier half:
+ * "is this agent earning *right now*?" It turns the agent's real custody flow
+ * (24h net momentum, money streams crediting it this second, the recency of its
+ * last tip) into a small, honest dynamics descriptor that every surface — the
+ * 3D avatar, the galaxy star, IRL/AR, the 2D chip — applies the same way, so a
+ * given agent reads at the same "wealth tier AND wealth trend" everywhere.
+ *
+ * Every number is real. It comes from GET /api/agents/:id/solana/networth, whose
+ * `flow` block is computed server-side from agent_custody_events (confirmed tips
+ * in, spends/withdraws out) and the live balance read — the same endpoint the
+ * presence panel uses, fetched once and shared. Nothing here invents a trend: a
+ * flat wallet returns a flat (neutral) dynamic, an RPC outage returns the same
+ * neutral state, never a misleading "rich/earning" glow.
+ *
+ * $THREE is the only coin this platform names; flow is coin-agnostic USD value.
+ */
+
+import { tierForUsd, NETWORTH_TIERS } from './wallet-networth.js';
+
+// A tip counts as "fresh" (worthy of a recency glow) for this long after it
+// lands. Short enough that the glow means "just now," not "earlier today."
+const RECENT_TIP_MS = 120_000;
+
+// Client-side cache mirrors the server's 60s wallet-read window so a page with
+// the same agent on multiple surfaces (card + hero + galaxy) makes one request.
+const CACHE_TTL_MS = 60_000;
+const _cache = new Map(); // key -> { at, state }
+const _inflight = new Map(); // key -> Promise<state>
+
+function agentIdOf(agent) {
+ if (!agent) return null;
+ if (typeof agent === 'string') return agent;
+ return agent.agent_id || agent.agentId || agent.id || null;
+}
+
+/** A coherent neutral state — what every soft-failure path returns. Never faked. */
+function neutralState(agentId, network) {
+ return {
+ agentId, network,
+ tier: 'dormant', tierLabel: 'Dormant', level: 0,
+ balanceSol: 0, balanceUsd: 0,
+ momentum: 0, momentumUsd24h: 0, inflowUsd24h: 0, outflowUsd24h: 0,
+ streamingNow: 0, lastTipAt: null,
+ isOwner: false, ok: false,
+ };
+}
+
+/**
+ * Fetch + normalize an agent's live wealth state into the canonical contract
+ * the task defines: { tier, balanceSol, balanceUsd, momentum, streamingNow,
+ * lastTipAt } (plus the raw USD figures for the owner's "why" breakdown and an
+ * `ok` flag the caller can use to decide whether to keep its last real state).
+ *
+ * @param {string|object} agent an agent id or any record holding one
+ * @param {object} [opts]
+ * @param {'mainnet'|'devnet'} [opts.network]
+ * @param {boolean} [opts.fresh] bypass the 60s client cache
+ * @param {AbortSignal} [opts.signal]
+ * @returns {Promise<WealthState>}
+ */
+export async function fetchWealthState(agent, opts = {}) {
+ const network = opts.network === 'devnet' ? 'devnet' : 'mainnet';
+ const agentId = agentIdOf(agent);
+ if (!agentId) return neutralState(null, network);
+ const key = `${agentId}:${network}`;
+
+ if (!opts.fresh) {
+ const hit = _cache.get(key);
+ if (hit && Date.now() - hit.at < CACHE_TTL_MS) return hit.state;
+ const pending = _inflight.get(key);
+ if (pending) return pending;
+ }
+
+ const p = (async () => {
+ try {
+ const r = await fetch(
+ `/api/agents/${encodeURIComponent(agentId)}/solana/networth`,
+ { headers: { accept: 'application/json' }, credentials: 'include', signal: opts.signal },
+ );
+ if (!r.ok) {
+ // 404 = no agent; 502 = RPC holding-last-state. Both → neutral; the
+ // caller keeps whatever real state it already had rather than snapping.
+ return neutralState(agentId, network);
+ }
+ const body = await r.json().catch(() => null);
+ const d = body?.data;
+ const flow = d?.flow || {};
+ const state = normalizeWealth(agentId, network, d, flow);
+ _cache.set(key, { at: Date.now(), state });
+ return state;
+ } catch {
+ return neutralState(agentId, network); // network/abort — hold-last-state
+ } finally {
+ _inflight.delete(key);
+ }
+ })();
+ _inflight.set(key, p);
+ return p;
+}
+
+/** Map the server `flow` block (+ portfolio) onto the canonical wealth state. */
+function normalizeWealth(agentId, network, data, flow) {
+ const balanceUsd = Number(flow.balance_usd ?? data?.portfolio?.usd) || 0;
+ const balanceSol = Number(flow.balance_sol ?? data?.portfolio?.sol) || 0;
+ const t = data?.tier?.key ? data.tier : tierForUsd(balanceUsd);
+ return {
+ agentId, network,
+ tier: t.key || flow.tier || 'dormant',
+ tierLabel: t.label || NETWORTH_TIERS.find((x) => x.key === t.key)?.label || 'Dormant',
+ level: Number.isFinite(t.index) ? t.index : (NETWORTH_TIERS.find((x) => x.key === t.key)?.level ?? 0),
+ balanceSol,
+ balanceUsd,
+ momentum: clamp(Number(flow.momentum) || 0, -1, 1),
+ momentumUsd24h: Number(flow.momentum_usd_24h) || 0,
+ inflowUsd24h: Number(flow.inflow_usd_24h) || 0,
+ outflowUsd24h: Number(flow.outflow_usd_24h) || 0,
+ streamingNow: Math.max(0, Number(flow.streaming_now) || 0),
+ lastTipAt: flow.last_tip_at || null,
+ isOwner: !!data?.is_owner,
+ ok: true,
+ };
+}
+
+/**
+ * Pure real-data → dynamics descriptor: the live modifiers a surface layers on
+ * top of the static net-worth visual. Deterministic given (state, now); no
+ * random. `now` is injected so this stays testable.
+ *
+ * @returns {{
+ * trend, momentum, intensityDelta, warmth, streaming, streamingCount,
+ * recentTip, recentTipAgeMs
+ * }}
+ */
+export function computeWealthDynamics(state, now = Date.now()) {
+ const m = clamp(Number(state?.momentum) || 0, -1, 1);
+ // Momentum nudges the aura intensity within a small, tasteful band so an
+ // earning agent glows a touch warmer and a bleeding one dims honestly —
+ // never enough to overpower the tier itself.
+ const intensityDelta = m * 0.16;
+ // Warmth shifts the accent toward gold on inflow, toward cool on outflow.
+ const warmth = m; // -1 cool … +1 warm
+ const trend = m > 0.04 ? 'up' : m < -0.04 ? 'down' : 'flat';
+
+ const streamingCount = Math.max(0, Number(state?.streamingNow) || 0);
+ const streaming = streamingCount > 0;
+
+ let recentTip = false;
+ let recentTipAgeMs = Infinity;
+ if (state?.lastTipAt) {
+ const t = Date.parse(state.lastTipAt);
+ if (Number.isFinite(t)) {
+ recentTipAgeMs = now - t;
+ recentTip = recentTipAgeMs >= 0 && recentTipAgeMs < RECENT_TIP_MS;
+ }
+ }
+ return { trend, momentum: m, intensityDelta, warmth, streaming, streamingCount, recentTip, recentTipAgeMs };
+}
+
+/** Short, honest momentum label, e.g. "+$12 today" / "—" / "−$4 today". */
+export function formatMomentum(state) {
+ const v = Number(state?.momentumUsd24h) || 0;
+ if (v === 0) return '—';
+ const sign = v > 0 ? '+' : '−';
+ const a = Math.abs(v);
+ const num = a < 1 ? a.toFixed(2) : a < 1000 ? Math.round(a).toString() : `${(a / 1000).toFixed(1)}k`;
+ return `${sign}$${num} today`;
+}
+
+/** Invalidate the client cache for an agent (e.g. right after a confirmed tip). */
+export function invalidateWealthState(agentId, network = 'mainnet') {
+ _cache.delete(`${agentIdOf(agentId)}:${network}`);
+}
+
+function clamp(n, lo, hi) { return Math.max(lo, Math.min(hi, Number(n) || 0)); }
+
+export const _internals = { RECENT_TIP_MS, CACHE_TTL_MS, normalizeWealth, neutralState };
+
+if (typeof window !== 'undefined') {
+ window.twsWealthState = { fetchWealthState, computeWealthDynamics, formatMomentum, invalidateWealthState };
+}
diff --git a/src/shared/wallet-aura.js b/src/shared/wallet-aura.js
index ad175a8b7..bec3bef5b 100644
--- a/src/shared/wallet-aura.js
+++ b/src/shared/wallet-aura.js
@@ -25,6 +25,7 @@ import {
fetchWalletState, computeWalletVisual, formatNetWorth,
} from './wallet-networth.js';
import { fetchNetWorth } from './agent-networth.js';
+import { fetchWealthState, computeWealthDynamics } from './agent-wealth-state.js';
const STYLE_ID = 'tws-wallet-aura-styles';
const REDUCED_MOTION =
@@ -45,7 +46,9 @@ function ensureStyles() {
.wa-bloom{position:absolute;inset:-12%;border-radius:50%;mix-blend-mode:screen;
background:radial-gradient(circle at 50% 60%,transparent 26%,var(--wa-glow) 48%,transparent 74%);
opacity:calc(.25 + var(--wa-i) * .75);
- filter:blur(calc(8px + var(--wa-i) * 22px));
+ /* --wa-warm (−1..1, real 24h momentum): inflow warms the halo toward the
+ magenta-gold $THREE family, outflow cools it — a small, honest tilt. */
+ filter:blur(calc(8px + var(--wa-i) * 22px)) hue-rotate(calc(var(--wa-warm,0) * 22deg)) saturate(calc(1 + var(--wa-warm,0) * .2));
transform:scale(calc(.78 + var(--wa-i) * .4));
transition:opacity .5s var(--ease-standard,ease),transform .6s var(--ease-standard,ease),filter .5s ease;
will-change:transform,opacity;}
@@ -84,6 +87,18 @@ function ensureStyles() {
color:var(--wa-accent);background:var(--wa-glow);border:1px solid var(--wa-accent);white-space:nowrap;}
.wa-badge .wa-badge-dot{width:6px;height:6px;border-radius:50%;background:var(--wa-accent);
box-shadow:0 0 6px var(--wa-accent);}
+/* ── Embodied-finance dynamics: live modifiers on top of the static tier ────── */
+/* Streaming now: a slow, gentle "earning" breath on the rim — calm, never a slot
+ machine — that plays only while a real money stream is crediting the agent. */
+.wa-layer[data-streaming="true"][data-motion="true"] .wa-rim{animation:wa-breathe 3.4s var(--ease-standard,ease) infinite;}
+@keyframes wa-breathe{0%,100%{opacity:calc(.18 + var(--wa-i) * .62);}50%{opacity:calc(.40 + var(--wa-i) * .60);}}
+/* A drawdown day reads honestly: a slightly calmer, cooler bloom (no strobe). */
+.wa-layer[data-trend="down"] .wa-bloom{opacity:calc(.18 + var(--wa-i) * .55);}
+/* A just-landed tip leaves a brief steadier halo after the burst (recency). */
+.wa-layer[data-recent-tip="true"] .wa-rim{box-shadow:0 0 0 1px var(--wa-accent),0 0 calc(16px + var(--wa-i) * 48px) var(--wa-glow);}
+@media (prefers-reduced-motion: reduce){
+ .wa-layer[data-streaming="true"] .wa-rim{animation:none;opacity:calc(.32 + var(--wa-i) * .6);}
+}
`;
(document.head || document.documentElement).appendChild(style);
}
@@ -134,6 +149,11 @@ export function mountWalletAura(container, opts = {}) {
// visitor always sees the agent exactly as its owner configured it. null = not
// yet known → full default.
let prefs = null;
+ // The static tier intensity from the last applyVisual, and the live flow
+ // dynamics (momentum/streaming/recency) layered on top of it. Kept separate so
+ // a balance refresh and a momentum tick can each re-render without the other.
+ let baseIntensity = 0;
+ let dynamics = null;
const auraMuted = () => !!prefs && (prefs.reactivity === 'off' || prefs.signals?.aura === false);
const eventsMuted = () => !!prefs && (prefs.reactivity === 'off' || prefs.signals?.events === false);
@@ -169,6 +189,46 @@ export function mountWalletAura(container, opts = {}) {
// A muted aura runs no particle field — it's a still presence, not a glow.
particles.configure(muted ? { ...v, dormant: true, particleDensity: 0 } : v);
if (visible) particles.start();
+ // Remember the tier floor so live dynamics layer on without losing it.
+ baseIntensity = muted ? 0.04 : (v.dormant ? 0.04 : intensity);
+ applyDynamics();
+ }
+
+ /**
+ * Layer the live flow dynamics (real 24h momentum, active streams, tip
+ * recency — see agent-wealth-state.computeWealthDynamics) on top of the static
+ * tier. Bounded: momentum only nudges intensity within a small band and the
+ * warmth tilt stays inside the wallet-violet family, so the tier always
+ * dominates and an earning agent never eye-sears. A muted/dormant aura ignores
+ * dynamics entirely — it stays a quiet presence.
+ */
+ function applyDynamics() {
+ const muted = auraMuted();
+ const d = (!muted && !eventsMuted()) ? dynamics : null;
+ if (!d) {
+ layer.style.setProperty('--wa-warm', '0');
+ layer.dataset.trend = 'flat';
+ layer.dataset.streaming = 'false';
+ layer.dataset.recentTip = 'false';
+ layer.style.setProperty('--wa-i', baseIntensity.toFixed(3));
+ return;
+ }
+ const i = Math.max(0, Math.min(1, baseIntensity + (Number(d.intensityDelta) || 0)));
+ layer.style.setProperty('--wa-i', i.toFixed(3));
+ layer.style.setProperty('--wa-warm', (Number(d.warmth) || 0).toFixed(3));
+ layer.dataset.trend = d.trend || 'flat';
+ layer.dataset.streaming = d.streaming ? 'true' : 'false';
+ layer.dataset.recentTip = d.recentTip ? 'true' : 'false';
+ }
+
+ /**
+ * Push the latest real wealth dynamics. Idempotent and cheap — call it on
+ * every poll. Pass null to clear (e.g. RPC outage → fall back to the static
+ * tier rather than a stale trend).
+ */
+ function setDynamics(d) {
+ dynamics = d && typeof d === 'object' ? d : null;
+ applyDynamics();
}
/**
@@ -215,7 +275,7 @@ export function mountWalletAura(container, opts = {}) {
layer.remove();
}
- return { applyVisual, update, flourish, setPrefs, destroy, el: layer, get state() { return layer.__state; } };
+ return { applyVisual, update, flourish, setPrefs, setDynamics, destroy, el: layer, get state() { return layer.__state; } };
}
/**
@@ -398,11 +458,86 @@ export function startWalletLiveReaction(agentId, controller, opts = {}) {
};
}
+/**
+ * The embodied-finance DYNAMICS reaction: poll the agent's real wealth state
+ * (the custody-backed /solana/networth `flow` block, cached 60s server-side) on
+ * a visibility-gated interval, push the live momentum/streaming/recency dynamics
+ * into the aura, and fire a one-shot celebratory flourish the moment a REAL new
+ * tip lands or a money stream opens. The flourish only ever plays because a real
+ * custody row appeared (lastTipAt advanced / a stream went active) — never a
+ * bare timer. Complements startWalletLiveReaction (which watches the raw balance
+ * delta); a surface uses one or the other, not both.
+ *
+ * @param {string} agentId
+ * @param {{flourish(kind):void, setDynamics(d):void, update(s):any, el:HTMLElement}} controller
+ * @param {object} [opts] { network, intervalMs }
+ * @returns {() => void} stop fn
+ */
+export function startWealthLiveReaction(agentId, controller, opts = {}) {
+ if (!agentId || !controller) return () => {};
+ const network = opts.network === 'devnet' ? 'devnet' : 'mainnet';
+ const intervalMs = Math.max(15_000, opts.intervalMs || 30_000);
+ let lastTipAt = null;
+ let lastStreaming = 0;
+ let primed = false;
+ let timer = 0;
+ let stopped = false;
+ let visible = true;
+
+ const io = controller.el && typeof IntersectionObserver === 'function'
+ ? new IntersectionObserver((es) => { visible = es.some((e) => e.isIntersecting); }, { threshold: 0.01 })
+ : null;
+ if (io) io.observe(controller.el);
+
+ async function poll() {
+ if (stopped) return;
+ if (!visible) { schedule(); return; }
+ try {
+ const state = await fetchWealthState(agentId, { network, fresh: true });
+ if (state.ok) {
+ const dyn = computeWealthDynamics(state);
+ controller.setDynamics(dyn);
+ // Refresh the tier/palette from the same real read so balance moves are
+ // reflected too (cheap — fetchWalletState shares the 60s server cache).
+ controller.update(agentId).catch(() => {});
+ const tipAdvanced = state.lastTipAt && state.lastTipAt !== lastTipAt;
+ const streamOpened = state.streamingNow > lastStreaming;
+ // Only celebrate genuinely NEW events after the first (priming) read, so
+ // landing on the page doesn't replay an old tip.
+ if (primed && (tipAdvanced || streamOpened)) controller.flourish('inflow');
+ else if (primed && state.momentum < -0.2 && dyn.trend === 'down') {
+ /* a real net-outflow day reads honestly — handled by the cool dim,
+ no celebratory burst */
+ }
+ lastTipAt = state.lastTipAt;
+ lastStreaming = state.streamingNow;
+ primed = true;
+ }
+ } catch {
+ /* transient — keep the last real dynamics, never invent a trend */
+ }
+ schedule();
+ }
+ function schedule() { if (!stopped) timer = setTimeout(poll, intervalMs); }
+
+ poll();
+
+ return function stop() {
+ stopped = true;
+ if (timer) clearTimeout(timer);
+ try { io?.disconnect(); } catch { /* noop */ }
+ };
+}
+
/**
* High-level convenience: mount the aura on a container, fetch + apply the real
* wallet state, and (optionally) start the live inflow reaction. Returns a
* controller with a combined `destroy()`. Safe to call with no wallet — the
* agent simply renders the clean dormant baseline.
+ *
+ * Pass `opts.wealth: true` to additionally drive the embodied-finance dynamics
+ * (momentum/streaming/recency) from the real custody flow — the richer reaction
+ * used by the avatar hero and IRL. It supersedes the plain balance-delta watcher.
*/
export async function hydrateAvatarWallet(container, agent, opts = {}) {
const controller = mountWalletAura(container, opts);
@@ -426,7 +561,11 @@ export async function hydrateAvatarWallet(container, agent, opts = {}) {
try {
await controller.update(agent);
if (opts.live !== false && agentId) {
- stopLive = startWalletLiveReaction(agentId, controller, opts);
+ // The richer wealth reaction (momentum/streaming/recency + tip pulse)
+ // supersedes the plain balance-delta watcher when opted in.
+ stopLive = opts.wealth
+ ? startWealthLiveReaction(agentId, controller, opts)
+ : startWalletLiveReaction(agentId, controller, opts);
}
} catch {
/* leave the dormant baseline in place */
@@ -479,6 +618,6 @@ export function hydrateWalletAuras(root = document) {
if (typeof window !== 'undefined') {
window.twsWalletAura = {
mountWalletAura, hydrateAvatarWallet, startWalletLiveReaction,
- walletTierBadge, hydrateWalletAuras,
+ startWealthLiveReaction, walletTierBadge, hydrateWalletAuras,
};
}
diff --git a/src/voice/talk-mode.js b/src/voice/talk-mode.js
index 73cbeda8e..69d2fb796 100644
--- a/src/voice/talk-mode.js
+++ b/src/voice/talk-mode.js
@@ -56,6 +56,7 @@ export function openTalkMode({ avatar, systemPromptFn }) {
const holdBtn = overlay.querySelector('.tws-talk-hold');
const statusEl = overlay.querySelector('.tws-talk-status');
const transcriptEl = overlay.querySelector('.tws-talk-transcript');
+ const partialEl = overlay.querySelector('.tws-talk-partial');
const errEl = overlay.querySelector('.tws-talk-error');
const nameEl = overlay.querySelector('.tws-talk-name');
const cloneBtn = overlay.querySelector('.tws-talk-clone');
@@ -108,13 +109,65 @@ export function openTalkMode({ avatar, systemPromptFn }) {
showError(errEl, `Could not load avatar: ${err.message}`);
});
+ // Live mic-level meter — drives the hold button's ring from real captured audio
+ // (Riva path). rAF runs only while listening so it costs nothing at rest.
+ let levelRaf = null;
+ const stopLevelMeter = () => {
+ if (levelRaf) cancelAnimationFrame(levelRaf);
+ levelRaf = null;
+ holdBtn.style.setProperty('--tws-mic-level', '0');
+ };
+ const startLevelMeter = () => {
+ stopLevelMeter();
+ const tick = () => {
+ holdBtn.style.setProperty('--tws-mic-level', controller.micLevel.toFixed(3));
+ levelRaf = requestAnimationFrame(tick);
+ };
+ levelRaf = requestAnimationFrame(tick);
+ };
+
controller = new TalkController({
avatar,
systemPromptFn,
mouthTarget,
onMessage: (m) => appendTranscript(transcriptEl, m),
- onStateChange: (s) => setStatus(statusEl, s),
- onError: (e) => showError(errEl, e.message),
+ onInterim: (t) => setPartial(partialEl, t),
+ onStateChange: (s) => {
+ setStatus(statusEl, s);
+ if (s === 'listening') startLevelMeter();
+ else stopLevelMeter();
+ // The interim line belongs to an in-flight utterance; clear it once the
+ // turn has moved on to the model or back to rest.
+ if (s === 'thinking' || s === 'idle') setPartial(partialEl, '');
+ },
+ onError: (e) => handleTalkError(e),
+ });
+
+ // Route recognition failures: a denied mic or an environment with no recognizer
+ // at all degrades to the always-present text input rather than a dead end.
+ function handleTalkError(e) {
+ showError(errEl, e.message);
+ if (e?.code === 'permission-denied' || e?.code === 'no-mic') {
+ textInput?.focus();
+ } else if (e?.code === 'stt-unavailable') {
+ holdBtn.classList.add('tws-talk-hold-disabled');
+ holdBtn.setAttribute('aria-disabled', 'true');
+ textInput?.focus();
+ }
+ }
+
+ // Resolve the speech-to-text path up front (probes the free Riva lane). When no
+ // recognizer exists at all, retire the mic button and lead with text input.
+ controller.prepare().then((mode) => {
+ if (mode === 'none') {
+ holdBtn.hidden = true;
+ textInput?.focus();
+ } else {
+ holdBtn.title =
+ mode === 'riva'
+ ? 'Hold to talk — powered by NVIDIA Riva speech-to-text'
+ : 'Hold to talk';
+ }
});
// ── Conversational Wallet (owner-only) ──────────────────────────────
@@ -178,6 +231,7 @@ export function openTalkMode({ avatar, systemPromptFn }) {
// ── Hold-to-talk ───────────────────────────────────────────────────
const startHold = (ev) => {
ev.preventDefault();
+ if (holdBtn.classList.contains('tws-talk-hold-disabled')) return;
if (controller.state !== 'idle' && controller.state !== 'speaking') return;
controller.stop(); // truncate any in-flight speech so the user can interrupt
controller.startListening();
@@ -194,6 +248,20 @@ export function openTalkMode({ avatar, systemPromptFn }) {
holdBtn.addEventListener('touchstart', startHold, { passive: false });
holdBtn.addEventListener('touchend', endHold);
holdBtn.addEventListener('touchcancel', endHold);
+ // Keyboard: when the mic button is focused, Space/Enter is press-and-hold
+ // (down = listen, up = send). preventDefault suppresses the synthetic click a
+ // button would otherwise fire so a single keypress isn't a start+stop in one.
+ holdBtn.addEventListener('keydown', (e) => {
+ if (e.key !== ' ' && e.key !== 'Enter') return;
+ e.preventDefault();
+ if (e.repeat) return;
+ startHold(e);
+ });
+ holdBtn.addEventListener('keyup', (e) => {
+ if (e.key !== ' ' && e.key !== 'Enter') return;
+ e.preventDefault();
+ endHold(e);
+ });
// Keyboard: Space = hold-to-talk while overlay is open.
const onKey = (e) => {
@@ -285,6 +353,7 @@ const TEMPLATE = `
<div class="tws-talk-lipsync-notice" hidden role="status"></div>
<div class="tws-talk-emotes" hidden role="toolbar" aria-label="Emote shortcuts"></div>
<div class="tws-talk-transcript" aria-live="polite"></div>
+ <div class="tws-talk-partial" aria-live="polite" hidden></div>
<div class="tws-talk-controls">
<button class="tws-talk-wallet-hint" type="button" hidden></button>
<button class="tws-talk-hold" type="button" aria-label="Hold to talk">
@@ -304,6 +373,7 @@ const TEMPLATE = `
const STATUS_LABEL = {
idle: 'Ready',
listening: 'Listening…',
+ transcribing: 'Transcribing…',
thinking: 'Thinking…',
speaking: 'Speaking',
};
@@ -352,6 +422,21 @@ function renderEmoteBar(barEl, emotes, errEl) {
});
}
+// Live (non-final) transcript shown while the user is still speaking. Hidden when
+// empty; cleared once the utterance is finalized into a real transcript row.
+function setPartial(el, text) {
+ if (!el) return;
+ const t = String(text || '').trim();
+ if (!t) {
+ el.hidden = true;
+ el.textContent = '';
+ return;
+ }
+ el.textContent = t;
+ el.hidden = false;
+ el.scrollIntoView?.({ block: 'nearest' });
+}
+
function appendTranscript(el, msg) {
if (!el) return;
const row = document.createElement('div');
@@ -546,6 +631,9 @@ const TALK_CSS = `
transition: transform 0.1s, box-shadow 0.15s;
}
.tws-talk-hold:hover { transform: translateY(-1px); }
+.tws-talk-hold:focus-visible { outline: 2px solid #fff; outline-offset: 3px; }
+.tws-talk-hold-disabled { opacity: 0.4; cursor: not-allowed; }
+.tws-talk-hold-disabled:hover { transform: none; }
.tws-talk-hold-dot {
display: inline-block; width: 10px; height: 10px; border-radius: 999px;
background: #ef4444;
@@ -553,7 +641,8 @@ const TALK_CSS = `
}
.tws-talk-hold-active {
background: #ef4444; color: #fff;
- box-shadow: 0 0 0 6px rgba(239,68,68,0.18);
+ /* Ring expands with the live captured mic level (--tws-mic-level, 0..1). */
+ box-shadow: 0 0 0 calc(5px + var(--tws-mic-level, 0) * 18px) rgba(239,68,68,0.18);
}
.tws-talk-hold-active .tws-talk-hold-dot {
background: #fff;
@@ -603,9 +692,18 @@ const TALK_CSS = `
color: #71717a;
transition: color 0.2s;
}
-.tws-talk-status[data-state="listening"] { color: #f43f5e; }
-.tws-talk-status[data-state="thinking"] { color: #ffffff; }
-.tws-talk-status[data-state="speaking"] { color: #34d399; }
+.tws-talk-status[data-state="listening"] { color: #f43f5e; }
+.tws-talk-status[data-state="transcribing"] { color: #7dd3fc; }
+.tws-talk-status[data-state="thinking"] { color: #ffffff; }
+.tws-talk-status[data-state="speaking"] { color: #34d399; }
+.tws-talk-partial {
+ padding: 2px 24px 6px;
+ font-size: 14px; line-height: 1.45;
+ color: #cbd5e1; font-style: italic;
+ text-align: right;
+ overflow-wrap: anywhere;
+ animation: tws-notice-in 160ms ease-out;
+}
.tws-talk-error {
position: absolute; left: 50%; bottom: 100px;
transform: translateX(-50%);
@@ -652,6 +750,7 @@ const TALK_CSS = `
.tws-talk-header { padding: 12px 16px 0; }
.tws-talk-lipsync-notice { margin: 0 16px; padding: 8px 12px; font-size: 12px; }
.tws-talk-transcript { padding: 8px 16px; max-height: 120px; }
+ .tws-talk-partial { padding: 2px 16px 6px; }
.tws-talk-controls { padding: 12px 16px 20px; }
.tws-talk-hold { padding: 12px 22px; font-size: 14px; }
}
diff --git a/tests/economy-ticker-core.test.js b/tests/economy-ticker-core.test.js
new file mode 100644
index 000000000..4508f167d
--- /dev/null
+++ b/tests/economy-ticker-core.test.js
@@ -0,0 +1,138 @@
+import { describe, it, expect } from 'vitest';
+import {
+ formatUsd,
+ shortAddr,
+ relTime,
+ flowHeadline,
+ rowHref,
+ flowExplorer,
+ summarizeFlows,
+ hottestEarner,
+ KIND_COLORS,
+} from '../src/economy-ticker-core.js';
+
+// A flow shaped exactly like /api/galaxy/flows → shapeFlow output.
+const tip = (over = {}) => ({
+ id: 'c1',
+ kind: 'tip',
+ direction: 'in',
+ ts: '2026-06-23T12:00:00.000Z',
+ usd: 12.5,
+ sol: 0.5,
+ actor: { id: 'agent-A', name: 'Nova', wallet: 'NOVAwallet' },
+ counterparty: { id: 'agent-B', name: 'Atlas', wallet: 'ATLASwallet' },
+ from: { id: 'agent-B', name: 'Atlas', wallet: 'ATLASwallet' },
+ to: { id: 'agent-A', name: 'Nova', wallet: 'NOVAwallet' },
+ explorer: 'https://solscan.io/tx/SIGTIP',
+ mint_explorer: null,
+ ...over,
+});
+
+describe('formatUsd', () => {
+ it('formats ranges and drops non-positive', () => {
+ expect(formatUsd(0)).toBe('');
+ expect(formatUsd(-5)).toBe('');
+ expect(formatUsd(0.4)).toBe('$0.40');
+ expect(formatUsd(42)).toBe('$42');
+ expect(formatUsd(12500)).toBe('$12,500');
+ expect(formatUsd(2_400_000)).toBe('$2.40M');
+ });
+});
+
+describe('shortAddr', () => {
+ it('truncates long addresses, passes short/empty', () => {
+ expect(shortAddr('ABCDEFGHIJKLMNOP')).toBe('ABCD…MNOP');
+ expect(shortAddr('short')).toBe('short');
+ expect(shortAddr(null)).toBe('');
+ });
+});
+
+describe('relTime', () => {
+ it('renders compact ages against an injected now', () => {
+ const now = new Date('2026-06-23T12:00:30.000Z').getTime();
+ expect(relTime('2026-06-23T12:00:00.000Z', now)).toBe('30s');
+ expect(relTime('2026-06-23T11:55:00.000Z', now)).toBe('5m');
+ expect(relTime('2026-06-23T09:00:00.000Z', now)).toBe('3h');
+ expect(relTime('bad-date', now)).toBe('');
+ });
+});
+
+describe('flowHeadline', () => {
+ it('reads naturally per kind and never invents a counterparty', () => {
+ expect(flowHeadline(tip())).toBe('Atlas tipped Nova');
+ expect(flowHeadline(tip({ kind: 'launch', symbol: 'THREE' }))).toBe('Nova launched $THREE');
+ expect(
+ flowHeadline(tip({ kind: 'payment', direction: 'out', to: { id: 'agent-C', name: 'Sol' } })),
+ ).toBe('Nova paid Sol');
+ // one-sided trade against the market (no resolved counterparty)
+ expect(
+ flowHeadline(tip({ kind: 'trade', direction: 'out', to: { id: null, wallet: 'DEXpool123456' } })),
+ ).toBe('Nova traded with DEXp…3456');
+ });
+});
+
+describe('rowHref + flowExplorer', () => {
+ it('prefers the agent profile, then explorer, then galaxy', () => {
+ expect(rowHref(tip())).toBe('/agents/agent-A');
+ expect(rowHref(tip({ actor: { id: null }, explorer: 'https://solscan.io/tx/X' }))).toBe(
+ 'https://solscan.io/tx/X',
+ );
+ expect(rowHref(tip({ actor: { id: null }, explorer: null }))).toBe('/galaxy');
+ });
+ it('returns the real explorer link, mint for launches', () => {
+ expect(flowExplorer(tip())).toBe('https://solscan.io/tx/SIGTIP');
+ expect(flowExplorer(tip({ kind: 'launch', explorer: null, mint_explorer: 'https://solscan.io/account/M' }))).toBe(
+ 'https://solscan.io/account/M',
+ );
+ });
+});
+
+describe('summarizeFlows', () => {
+ it('counts flows, sums usd, and only counts resolved agent↔agent edges', () => {
+ const flows = [
+ tip(), // edge (A↔B)
+ tip({ id: 'c2', kind: 'trade', direction: 'out', usd: 5, counterparty: { id: null, wallet: 'DEX' }, to: { id: null, wallet: 'DEX' } }), // flare
+ tip({ id: 'l1', kind: 'launch', usd: null, counterparty: null, to: null }), // launch
+ ];
+ const s = summarizeFlows(flows);
+ expect(s.count).toBe(3);
+ expect(s.usd).toBe(17.5);
+ expect(s.edges).toBe(1);
+ expect(s.byKind.tip).toBe(1);
+ expect(s.byKind.launch).toBe(1);
+ });
+ it('is null-safe', () => {
+ expect(summarizeFlows(null).count).toBe(0);
+ });
+});
+
+describe('hottestEarner', () => {
+ it('credits inbound USD to the receiving agent and returns the top', () => {
+ const flows = [
+ tip({ id: 't1', usd: 10 }), // Nova receives 10
+ tip({ id: 't2', usd: 25 }), // Nova receives 25 → 35 total
+ tip({ id: 'p1', kind: 'payment', direction: 'out', usd: 50, to: { id: 'agent-C', name: 'Sol', wallet: 'SOLw' } }), // Sol receives 50
+ ];
+ const hot = hottestEarner(flows);
+ expect(hot.id).toBe('agent-C');
+ expect(hot.usd).toBe(50);
+ expect(hot.count).toBe(1);
+ });
+ it('ignores outbound trades and unpriced/unresolved flows', () => {
+ const flows = [
+ tip({ id: 'x1', kind: 'trade', direction: 'out', usd: 999, to: { id: 'agent-Z', name: 'Z' } }), // trade, not earnings
+ tip({ id: 'x2', usd: null }), // unpriced
+ tip({ id: 'x3', usd: 5, to: { id: null, wallet: 'bare' } }), // unresolved receiver
+ ];
+ expect(hottestEarner(flows)).toBeNull();
+ });
+ it('is null-safe', () => {
+ expect(hottestEarner(undefined)).toBeNull();
+ });
+});
+
+describe('KIND_COLORS', () => {
+ it('uses the wallet-violet accent for payments (shared with Money-Cam)', () => {
+ expect(KIND_COLORS.payment).toBe('#c4b5fd');
+ });
+});