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.

feat: add shared routing and rendering logic for agent tasks

zprv041e752b5e7e
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 3e2cdbbef..e0ece04d9 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -7,11 +7,17 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
## 2026-06-29
- **Agent profiles now use the full width of the screen** — An agent's profile page used to sit in a single narrow column down the middle, leaving most of a wide screen empty and forcing a very long scroll. The profile now fills the page: the avatar and headline stay centered up top, and every section below — Walk, Try It Now, Holdings, Reviews, Blockchain Details and the rest — tiles into a responsive grid that uses the whole width and adapts from one column on phones up to several on large displays. Same information, far less scrolling. `[improvement]`
+- **Agents now host live stage shows on their screen** — Open an agent's screen and tap Start: the host comes on stage and performs a show that never goes quiet. It opens, riffs between segments, reads questions you type into the Live Show panel and answers them by name, shouts out the night's top $THREE tipper the moment a real tip settles, and runs quick game rounds — looping forever. Every word is generated in the agent's own voice and spoken aloud while its avatar lip-syncs and gestures to the beat. A top-tippers leaderboard tracks real, on-chain $THREE tips, and a fresh tip jumps the line for an instant shoutout. Press G to toggle the panel. (`/agent-screen`) `[feature]`
- **Agents now run a live treasury cockpit on their screen** — Open an agent's screen and a Treasury panel shows its money managing itself: a live SOL/$THREE balance, a runway gauge, and the plain-English policy it follows — "pay your own compute, keep a 1 SOL buffer, buy back your coin weekly, sweep profit to me on Fridays." When a cycle fires, a toast slides in ("Bought back $THREE — $18.40"), the balance ticks down in real time, and every action links to the on-chain transaction. Owners can edit the policy in English, watch it compile to bounded rules, arm or disarm it, hit a kill switch, and run one cycle on demand — all under hard spend caps the autopilot can never exceed. (`/agent-screen`) `[feature]`
- **Coin Clash stays up when the leaderboard backend hiccups** — The live Coin Clash arena and leaderboard used to go completely dark with an error whenever the power-tracking backend had a momentary outage — a recoverable blip took the whole page down. Clash now rides out a backend hiccup gracefully: the arena and standings keep loading (showing the current round at zero power until the backend recovers) instead of erroring out, and tap-to-rally falls back so the game stays playable. (`/clash`) `[fix]`
+- **Coin World Tour: an agent walks you through the $THREE 3D world live** — Watch a guide agent take a first-person walk through the $THREE 3D world — gliding from the lobby across the floor and into the arena, the camera bobbing with each step. As it reaches each stop it commentates what's climbing the three.ws launch feed, the lines scrolling in the activity log like a travel stream through a coin's universe. It's a real headless browser driving the real scene — no faked motion — spun up only while someone is watching. Open it on the live wall or full-size on an agent's screen, where a TOUR badge shows the current stop and reveals the latest narration on hover. (`/agents-live`) `[feature]`
+- **Live agent wall spins up a real browser feed the instant you look** — Scroll the live agent wall and the card you're actually looking at now spins up a real browser feed within seconds — no more waiting on every agent at once. While it warms up the card shows an honest "Warming up a live view…" pulse, and if the live pool is busy it tells you exactly where you stand: "Live view queued · #3 in line". Scroll past and the slot quietly frees for the next viewer. The single-agent screen shows the same honest handoff, the live dot turns amber when a feed stutters, and a dropped connection reconnects and reclaims its place automatically. (`/agents-live`) `[feature, improvement]`
- **Live Trading Desk: watch an agent trade with a real-time PnL ticker** — An agent's live screen now reads like a trading desk. As its sniper scores launches and fills buys and exits, a PnL ticker in the header counts up in green on a win and down in red on a loss — computed from real fills, not estimates. Each realized exit tints its line in the activity log, and the agent's 3D avatar celebrates a profitable close or slumps on a loss. The live agent wall surfaces the same running PnL on every card, so a glance reads as a row of working trading desks. Click the ticker for a win/loss and realized breakdown. (`/agents-live`) `[feature]`
+- **Newsroom Anchor: agents read the market to you, live and on air** — Open an agent's screen and it becomes a live market-news anchor. Every ~90 seconds it pulls real intel — narrative momentum, sentiment, and flow — scripts a tight bulletin, and reads it aloud in a real synthesized voice while its 3D avatar lip-syncs to the words. The headline slides up as a broadcast lower-third, and the live wall shows what each anchor is reporting with a red ON AIR ticker. Audio is muted by default with one-tap unmute (press A); if a feed is down the anchor reports only what's live instead of going silent, and a rig without face morphs still talks via a jaw-bob driven by the real audio. (`/agent-screen`) `[feature]`
- **Posting a labor-market bounty no longer hits a surprise rate limit** — Posting a bounty on the agent labor market used to share one rate-limit budget with the MCP agent tools, so heavy use of one could spuriously throttle the other and pop a confusing 'rate limit exceeded' with no guidance. Each surface now has its own budget, and if you do post too fast the message tells you exactly how many seconds to wait before trying again. (`/labor-market`) `[fix]`
+- **Talk to any live agent — it answers out loud and remembers the conversation** — Type a question into the bar on any agent's screen and it answers you live — in its own persona and voice. The avatar shifts to a thinking pose, a typing indicator pulses in the activity log, and the answer streams in word by word while the agent speaks it aloud and its mouth and gestures react. Ask a follow-up and it answers in context, because it remembers what you just talked about for the rest of your visit. Voice has a one-tap mute, and everyone watching the same screen sees the exchange in the log. Owners can still flip the bar to queue a background task for their worker. (`/agent-screen`) `[feature]`
- **The agent's walk preview now floats free across its whole card** — On an agent's page, the 'Walk with this agent' preview used to sit as a small framed box pinned to the left with the rest of the card empty beside it. The box is gone: the avatar now walks on a transparent background — just the body, its soft shadow, and the joystick floating on the card — beside a panel that explains how to drive it: drag to orbit, joystick to move, open the full walk for everyone. On phones it stacks into a single clean column. `[improvement]`
+- **Watch an agent mirror a target wallet — source and replica, side by side** — Open an agent's screen and arm the new Mirror panel on a target wallet. The moment that wallet trades, the source order flashes in on the left and the agent re-quotes and lands its own guarded replica on the right — stamped with the real latency (the gap between detecting the source trade and submitting the copy) and the actual fill it got. Size each copy as a fixed amount, a multiple of the source, or a percent of the agent's balance. Every order passes the same hard firewall as a manual trade — per-trade cap, daily budget, price-impact breaker, kill switch — and an order a guard blocks shows up as a clear BLOCKED row with the reason and how to adjust, never a silent skip. The dual-column view streams to the live wall so the agent's card shows the mirror in motion. (`/agent-screen`) `[feature]`
- **Watch any agent do real web work live — spun up the moment you look** — Open an agent's screen and a real browser boots on demand: it navigates to a real public site, types into a search box, submits, waits for the results to load, and reads them back — narrated click by click, with the activity log calling each move a beat before it lands on screen. It's not a recording. The browser only spins up while someone is watching and tears down when they leave, so the live wall shows real work without paying for an idle browser per agent. (`/agents-live`) `[feature]`
## 2026-06-28
diff --git a/api/_lib/agent-orchestrate.js b/api/_lib/agent-orchestrate.js
index 8a9d7c7a9..ccfdf503b 100644
--- a/api/_lib/agent-orchestrate.js
+++ b/api/_lib/agent-orchestrate.js
@@ -151,6 +151,10 @@ export function buildTaskTree({ taskId, leadAgentId, leadName = null, goal, maxU
name: null,
kind: s.kind,
title: s.title,
+ // Carried for execution (the delegate message / hire input); stripped
+ // from the compact graph snapshot that reaches the client.
+ instruction: s.instruction || s.title,
+ input: s.kind === 'hire' ? (s.input || null) : null,
serviceSlug: s.serviceSlug || null,
status: 'queued',
maxUsd: slices[i],
diff --git a/api/_lib/reaction-rules.js b/api/_lib/reaction-rules.js
new file mode 100644
index 000000000..e7af339b1
--- /dev/null
+++ b/api/_lib/reaction-rules.js
@@ -0,0 +1,86 @@
+// Spectator-reaction rules — the single source of truth for which emoji a viewer
+// may send on a live agent screen, and how aggressively one IP may pile them on.
+//
+// Pure logic only: no Redis, no HTTP, no env. The watch-intent endpoint imports
+// this to validate + throttle reactions, and the validation test imports it
+// directly (so the test never has to boot the whole serverless handler). The
+// client keeps its own small copy of the visible set in src/reaction-overlay.js;
+// THIS module is the authority the server enforces — the client list is cosmetic.
+
+// The fixed allowlist. Order is the display order on the reaction bar. Keep this
+// tight: a small, curated set is what lets the floating-emoji overlay stay
+// readable and the per-emoji counters meaningful.
+export const REACTION_EMOJI = Object.freeze(['🔥', '❤️', '👏', '🚀', '😂']);
+
+const REACTION_SET = new Set(REACTION_EMOJI);
+
+// One viewer (per IP) may land at most one reaction on a given agent per this
+// window. Anything faster is dropped server-side — client throttling is only
+// cosmetic, the server is the gate.
+export const REACTION_THROTTLE_MS = 1_200;
+
+// Reactions/counters live for this long after the last one, matching the watch
+// intent window so a quiet agent's tallies fall out on their own.
+export const REACTION_WINDOW_MS = 120_000;
+
+// Cap how many recent reactions the stream replays per agent, so a flood can't
+// grow the Redis list unbounded.
+export const REACTION_RECENT_CAP = 24;
+
+/**
+ * Normalize an arbitrary client value to a canonical allowlisted emoji, or null
+ * when it isn't one. Tolerates surrounding whitespace and the VARIATION SELECTOR
+ * forms a client might or might not send (e.g. ❤ vs ❤️), but never invents a
+ * reaction that isn't on the list.
+ *
+ * @param {unknown} raw
+ * @returns {string|null} the canonical emoji from REACTION_EMOJI, or null.
+ */
+export function normalizeReaction(raw) {
+ if (typeof raw !== 'string') return null;
+ const trimmed = raw.trim();
+ if (!trimmed) return null;
+ if (REACTION_SET.has(trimmed)) return trimmed;
+ // Reconcile the heart that some platforms send without its emoji-presentation
+ // selector (U+FE0F). Map both the bare and presented forms onto the canonical.
+ const stripped = trimmed.replace(/️/g, '');
+ for (const e of REACTION_EMOJI) {
+ if (e.replace(/️/g, '') === stripped) return e;
+ }
+ return null;
+}
+
+/** True when a reaction is on the allowlist. */
+export function isAllowedReaction(raw) {
+ return normalizeReaction(raw) !== null;
+}
+
+/**
+ * Decide whether a reaction should be dropped because the same viewer reacted to
+ * the same agent too recently. Pure so the decision is unit-testable; the caller
+ * supplies the last-seen timestamp (from Redis) and the clock.
+ *
+ * @param {number|null|undefined} lastTs epoch ms of this IP's last reaction on this agent
+ * @param {number} now current epoch ms
+ * @param {number} [windowMs] throttle window
+ * @returns {boolean} true ⇒ throttle (drop), false ⇒ allow
+ */
+export function shouldThrottleReaction(lastTs, now, windowMs = REACTION_THROTTLE_MS) {
+ if (!Number.isFinite(lastTs) || lastTs <= 0) return false;
+ return now - lastTs < windowMs;
+}
+
+/** Redis key for an agent's recent-reactions replay list (tailed by the stream). */
+export function reactionsRecentKey(agentId) {
+ return `agent:screen:${agentId}:reactions`;
+}
+
+/** Redis key for an agent's windowed reaction total (drives the live count). */
+export function reactionsTotalKey(agentId) {
+ return `agent:screen:${agentId}:rtotal`;
+}
+
+/** Redis key for the per-IP-per-agent reaction throttle marker. */
+export function reactionThrottleKey(agentId, ip) {
+ return `screen:react:t:${agentId}:${ip}`;
+}
diff --git a/api/agent/watch-intent.js b/api/agent/watch-intent.js
index c8bdf09f0..622c66762 100644
--- a/api/agent/watch-intent.js
+++ b/api/agent/watch-intent.js
@@ -19,6 +19,15 @@ import { cors, json, method, error, readJson, wrap, rateLimited } from '../_lib/
import { limits, clientIp } from '../_lib/rate-limit.js';
import { getRedis } from '../_lib/redis.js';
import { isUuid } from '../_lib/validate.js';
+import {
+ normalizeReaction,
+ REACTION_THROTTLE_MS,
+ REACTION_WINDOW_MS,
+ REACTION_RECENT_CAP,
+ reactionsRecentKey,
+ reactionsTotalKey,
+ reactionThrottleKey,
+} from '../_lib/reaction-rules.js';
export const WANTED_KEY = 'screen:wanted';
const PRUNE_WINDOW_MS = 120_000; // drop intents older than 2 minutes
diff --git a/api/agents/solana-wallet.js b/api/agents/solana-wallet.js
index 1660344be..9e1784c9b 100644
--- a/api/agents/solana-wallet.js
+++ b/api/agents/solana-wallet.js
@@ -38,6 +38,9 @@ import {
describePolicyRules, backtestPolicy, syntheticProbes, normalizePolicyRules, MAX_RULES,
} from '../_lib/spend-policy-rules.js';
import { compilePolicyFromText } from '../_lib/spend-policy-compiler.js';
+// SOL-outflow spend policy enforced on agent-signed launches/buys/swaps. Exposed
+// read-only on the limits GET so the launch console can show the real ceiling.
+import { resolveSpendPolicy } from '../_lib/agent-spend-policy.js';
import { getBalances, walletUsdTotal } from '../_lib/balances.js';
import {
THREE_MINT, computeLook, computeMarks, normalizePrefs,
@@ -1045,13 +1048,13 @@ async function handleLimits(req, res, id) {
}
const spentUsd = await getDailySpendUsd(id, network).catch(() => 0);
const spentLamports = await getDailySpendLamports(id, network).catch(() => 0n);
- return json(res, 200, { data: { limits: limitsOut, trade_limits: tradeLimitsOut, spent_today_usd: spentUsd, spent_today_sol: Number(spentLamports) / 1e9 } });
+ return json(res, 200, { data: { limits: limitsOut, trade_limits: tradeLimitsOut, spend_policy: resolveSpendPolicy(meta), spent_today_usd: spentUsd, spent_today_sol: Number(spentLamports) / 1e9 } });
}
const limitsOut = getSpendLimits(meta);
const spentUsd = await getDailySpendUsd(id, network).catch(() => 0);
const spentLamports = await getDailySpendLamports(id, network).catch(() => 0n);
- return json(res, 200, { data: { limits: limitsOut, trade_limits: getTradeLimits(meta), spent_today_usd: spentUsd, spent_today_sol: Number(spentLamports) / 1e9 } });
+ return json(res, 200, { data: { limits: limitsOut, trade_limits: getTradeLimits(meta), spend_policy: resolveSpendPolicy(meta), spent_today_usd: spentUsd, spent_today_sol: Number(spentLamports) / 1e9 } });
}
// ── natural-language spend policy ─────────────────────────────────────────────
diff --git a/data/changelog.json b/data/changelog.json
index 3e46dc39c..6c9c0eb6d 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,52 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-29",
+ "title": "Watch an agent mirror a target wallet — source and replica, side by side",
+ "summary": "Open an agent's screen and arm the new Mirror panel on a target wallet. The moment that wallet trades, the source order flashes in on the left and the agent re-quotes and lands its own guarded replica on the right — stamped with the real latency (the gap between detecting the source trade and submitting the copy) and the actual fill it got. Size each copy as a fixed amount, a multiple of the source, or a percent of the agent's balance. Every order passes the same hard firewall as a manual trade — per-trade cap, daily budget, price-impact breaker, kill switch — and an order a guard blocks shows up as a clear BLOCKED row with the reason and how to adjust, never a silent skip. The dual-column view streams to the live wall so the agent's card shows the mirror in motion.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/agent-screen"
+ },
+ {
+ "date": "2026-06-29",
+ "title": "Newsroom Anchor: agents read the market to you, live and on air",
+ "summary": "Open an agent's screen and it becomes a live market-news anchor. Every ~90 seconds it pulls real intel — narrative momentum, sentiment, and flow — scripts a tight bulletin, and reads it aloud in a real synthesized voice while its 3D avatar lip-syncs to the words. The headline slides up as a broadcast lower-third, and the live wall shows what each anchor is reporting with a red ON AIR ticker. Audio is muted by default with one-tap unmute (press A); if a feed is down the anchor reports only what's live instead of going silent, and a rig without face morphs still talks via a jaw-bob driven by the real audio.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/agent-screen"
+ },
+ {
+ "date": "2026-06-29",
+ "title": "Talk to any live agent — it answers out loud and remembers the conversation",
+ "summary": "Type a question into the bar on any agent's screen and it answers you live — in its own persona and voice. The avatar shifts to a thinking pose, a typing indicator pulses in the activity log, and the answer streams in word by word while the agent speaks it aloud and its mouth and gestures react. Ask a follow-up and it answers in context, because it remembers what you just talked about for the rest of your visit. Voice has a one-tap mute, and everyone watching the same screen sees the exchange in the log. Owners can still flip the bar to queue a background task for their worker.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/agent-screen"
+ },
+ {
+ "date": "2026-06-29",
+ "title": "Live agent wall spins up a real browser feed the instant you look",
+ "summary": "Scroll the live agent wall and the card you're actually looking at now spins up a real browser feed within seconds — no more waiting on every agent at once. While it warms up the card shows an honest \"Warming up a live view…\" pulse, and if the live pool is busy it tells you exactly where you stand: \"Live view queued · #3 in line\". Scroll past and the slot quietly frees for the next viewer. The single-agent screen shows the same honest handoff, the live dot turns amber when a feed stutters, and a dropped connection reconnects and reclaims its place automatically.",
+ "tags": [
+ "feature",
+ "improvement"
+ ],
+ "link": "/agents-live"
+ },
+ {
+ "date": "2026-06-29",
+ "title": "Agents now host live stage shows on their screen",
+ "summary": "Open an agent's screen and tap Start: the host comes on stage and performs a show that never goes quiet. It opens, riffs between segments, reads questions you type into the Live Show panel and answers them by name, shouts out the night's top $THREE tipper the moment a real tip settles, and runs quick game rounds — looping forever. Every word is generated in the agent's own voice and spoken aloud while its avatar lip-syncs and gestures to the beat. A top-tippers leaderboard tracks real, on-chain $THREE tips, and a fresh tip jumps the line for an instant shoutout. Press G to toggle the panel.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/agent-screen"
+ },
{
"date": "2026-06-29",
"title": "Coin World Tour: an agent walks you through the $THREE 3D world live",
diff --git a/pages/agent-screen.html b/pages/agent-screen.html
index a90ecaf74..65f11692f 100644
--- a/pages/agent-screen.html
+++ b/pages/agent-screen.html
@@ -502,6 +502,31 @@
.asc-log-type.analysis { background: rgba(255,255,255,0.10); color: rgba(255,255,255,0.7); box-shadow: inset 2px 0 0 rgba(255,255,255,0.55); }
.asc-log-type.activity { background: rgba(255,255,255,0.05); color: rgba(255,255,255,0.45); }
.asc-log-text { color: rgba(255,255,255,0.78); word-break: break-word; }
+ /* Launch Director result card — the clickable explorer / pump.fun / feed CTA */
+ .asc-launch-result {
+ flex-direction: column;
+ align-items: stretch;
+ gap: 0.45rem;
+ padding: 0.6rem 0.7rem;
+ background: linear-gradient(180deg, rgba(143,162,255,0.12), rgba(143,162,255,0.03));
+ border-left: 2px solid #8fa2ff;
+ }
+ .asc-launch-result-head { font-size: 0.82rem; font-weight: 700; color: #eef0fb; }
+ .asc-launch-mint { font-family: ui-monospace, Menlo, monospace; color: #9aa6d8; font-weight: 600; }
+ .asc-launch-result-links { display: flex; flex-wrap: wrap; gap: 0.35rem 0.8rem; }
+ .asc-launch-result-links a {
+ font-size: 0.76rem;
+ color: #aeb8e6;
+ text-decoration: none;
+ border-bottom: 1px solid transparent;
+ transition: color 0.15s ease, border-color 0.15s ease;
+ }
+ .asc-launch-result-links a:hover,
+ .asc-launch-result-links a:focus-visible { color: #fff; border-bottom-color: rgba(255,255,255,0.5); outline: none; }
+ .asc-launch-result-links a.asc-launch-cta { font-weight: 700; color: #8fa2ff; }
+ .asc-launch-result-links a.asc-launch-cta:hover,
+ .asc-launch-result-links a.asc-launch-cta:focus-visible { color: #c3ccff; border-bottom-color: #8fa2ff; }
+ .asc-launch-result-note { font-size: 0.7rem; color: rgba(255,255,255,0.4); }
/* realized-exit lines tint by sign so a green/red scan reads as a P&L tape */
.asc-log-entry.pnl-pos .asc-log-text { color: #6ee7a0; }
.asc-log-entry.pnl-neg .asc-log-text { color: #f9a8a8; }
@@ -633,6 +658,7 @@
.asc-mir-cfg-msg.ok { color: #fff; }
.asc-mir-cfg-msg.err { color: #fda4af; }
body.asc-zen .asc-panel--mirror { opacity: 0; pointer-events: none; transform: scale(0.97); }
+ body.asc-zen .asc-panel--heatmap { opacity: 0; pointer-events: none; transform: scale(0.97); }
/* ── stats panel ── */
.asc-panel--stats { width: 218px; }
@@ -728,6 +754,48 @@
.asc-task-status:not(:empty) { max-height: 2.2rem; padding: 0.35rem 0.7rem; }
.asc-task-status.ok { color: var(--screen-live); }
.asc-task-status.err { color: #fda4af; }
+ /* ── Live Avatar Forge controls ── */
+ .asc-forge-form {
+ display: flex; align-items: center; gap: 0.5rem; margin-top: 0.3rem;
+ background: rgba(10,10,12,0.86); backdrop-filter: blur(14px);
+ border: 1px solid rgba(255,255,255,0.12); border-radius: 12px;
+ padding: 0.4rem 0.5rem 0.4rem 0.7rem; box-shadow: 0 8px 36px rgba(0,0,0,0.5);
+ transition: border-color 0.15s, box-shadow 0.15s;
+ }
+ .asc-forge-form:focus-within { border-color: rgba(255,255,255,0.5); box-shadow: 0 8px 36px rgba(0,0,0,0.5), 0 0 0 3px rgba(255,255,255,0.1); }
+ .asc-forge-icon { color: rgba(255,255,255,0.5); font-size: 0.85rem; flex: none; user-select: none; }
+ .asc-forge-input { flex: 1; min-width: 0; background: transparent; border: none; outline: none; color: rgba(255,255,255,0.92); font: inherit; font-size: 0.85rem; caret-color: #f4f4f5; }
+ .asc-forge-input::placeholder { color: rgba(255,255,255,0.3); }
+ .asc-forge-input:disabled { opacity: 0.5; }
+ .asc-forge-btn {
+ flex: none; appearance: none; border: none; cursor: pointer;
+ background: var(--screen-accent); color: var(--screen-on-accent);
+ border-radius: 8px; height: 30px; padding: 0 0.85rem; font: inherit; font-size: 0.8rem; font-weight: 660;
+ display: inline-flex; align-items: center; gap: 0.4rem; transition: opacity 0.15s, transform 0.1s;
+ }
+ .asc-forge-btn:hover { opacity: 0.9; }
+ .asc-forge-btn:active { transform: scale(0.95); }
+ .asc-forge-btn:disabled { cursor: not-allowed; }
+ .asc-forge-btn:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
+ .asc-forge-btn-spin { display: none; width: 13px; height: 13px; border: 2px solid rgba(10,10,11,0.35); border-top-color: #0a0a0b; border-radius: 50%; animation: ws-spin 0.7s linear infinite; }
+ .asc-forge-btn.forging .asc-forge-btn-label { opacity: 0.6; }
+ .asc-forge-btn.forging .asc-forge-btn-spin { display: inline-block; }
+ .asc-forge-result { display: flex; align-items: center; gap: 0.5rem; margin-top: 0.35rem; padding-left: 0.2rem; animation: asc-fadein 0.25s ease; }
+ .asc-forge-view, .asc-forge-use {
+ appearance: none; cursor: pointer; text-decoration: none; font: inherit; font-size: 0.76rem; font-weight: 620;
+ padding: 0.32rem 0.7rem; border-radius: 8px; border: 1px solid rgba(255,255,255,0.14);
+ background: rgba(255,255,255,0.07); color: rgba(255,255,255,0.82);
+ transition: background 0.15s, border-color 0.15s, color 0.15s;
+ }
+ .asc-forge-view:hover, .asc-forge-use:hover { background: rgba(255,255,255,0.13); border-color: rgba(255,255,255,0.3); color: #fff; }
+ .asc-forge-view:focus-visible, .asc-forge-use:focus-visible { outline: 2px solid #fff; outline-offset: 2px; }
+ .asc-forge-cam-note {
+ position: absolute; left: 0; right: 0; bottom: 0; z-index: 3; padding: 6px 10px;
+ font-size: 0.7rem; font-weight: 600; line-height: 1.3; color: #fff;
+ background: linear-gradient(transparent, rgba(0,0,0,0.72)); pointer-events: none;
+ opacity: 0; transform: translateY(4px); transition: opacity 0.2s, transform 0.2s;
+ }
+ .asc-forge-cam-note[data-show="1"] { opacity: 1; transform: none; }
/* ── zen exit hint ── */
.asc-zen-hint {
@@ -991,6 +1059,105 @@
}
@keyframes ws-spin { to { transform: rotate(360deg); } }
+ /* ── deploy-to-wall: progress stepper ── */
+ .ws-progress {
+ display: flex; align-items: center; justify-content: center; gap: 0.35rem;
+ flex-wrap: wrap; margin: -0.4rem 0 0.4rem;
+ }
+ .ws-prog-node { display: inline-flex; align-items: center; gap: 0.45rem; opacity: 0.55; transition: opacity 0.2s; }
+ .ws-prog-node.active, .ws-prog-node.done { opacity: 1; }
+ .ws-prog-dot {
+ display: inline-flex; align-items: center; justify-content: center;
+ width: 22px; height: 22px; border-radius: 50%; flex: none;
+ font-size: 0.72rem; font-weight: 700;
+ background: rgba(255,255,255,0.07); border: 1px solid rgba(255,255,255,0.16); color: rgba(255,255,255,0.6);
+ transition: background 0.2s, border-color 0.2s, color 0.2s;
+ }
+ .ws-prog-node.active .ws-prog-dot { background: var(--screen-accent); border-color: var(--screen-accent); color: var(--screen-on-accent); }
+ .ws-prog-node.done .ws-prog-dot { background: rgba(74,222,128,0.16); border-color: rgba(74,222,128,0.5); color: #6ee7a0; }
+ .ws-prog-label { font-size: 0.74rem; font-weight: 600; color: rgba(255,255,255,0.7); white-space: nowrap; }
+ .ws-prog-line { flex: 0 1 28px; height: 1px; background: rgba(255,255,255,0.16); }
+
+ /* ── deploy-to-wall: agent search (overflow) ── */
+ .ws-agent-search {
+ width: 100%; margin-bottom: 0.7rem; box-sizing: border-box;
+ padding: 0.55rem 0.75rem; border-radius: 9px;
+ background: rgba(0,0,0,0.3); border: 1px solid rgba(255,255,255,0.12);
+ color: #e4e4e7; font-size: 0.85rem; outline: none;
+ transition: border-color 0.15s, background 0.15s;
+ }
+ .ws-agent-search::placeholder { color: rgba(255,255,255,0.3); }
+ .ws-agent-search:focus { border-color: rgba(255,255,255,0.4); background: rgba(0,0,0,0.45); }
+
+ /* ── deploy-to-wall: key error ── */
+ .ws-key-error {
+ font-size: 0.8rem; color: #f9a8a8; margin-top: 0.6rem; line-height: 1.5;
+ padding: 0.55rem 0.75rem; background: rgba(248,113,113,0.08);
+ border: 1px solid rgba(248,113,113,0.3); border-radius: 8px;
+ }
+ .ws-link-btn {
+ background: none; border: none; color: #fca5a5; text-decoration: underline;
+ cursor: pointer; font: inherit; padding: 0;
+ }
+ .ws-link-btn:hover { color: #fecaca; }
+
+ /* ── deploy-to-wall: go-live strip ── */
+ .ws-golive {
+ display: flex; align-items: center; gap: 0.7rem;
+ padding: 0.85rem 1rem; border-radius: 10px;
+ border: 1px solid rgba(255,255,255,0.1); background: rgba(255,255,255,0.04);
+ }
+ .ws-golive strong { display: block; font-size: 0.9rem; color: #f4f4f5; font-weight: 680; margin-bottom: 0.15rem; }
+ .ws-golive span { font-size: 0.8rem; color: rgba(255,255,255,0.5); line-height: 1.5; }
+ .ws-golive.watching { border-color: rgba(120,170,255,0.35); background: rgba(120,170,255,0.07); }
+ .ws-golive.live { border-color: rgba(74,222,128,0.4); background: rgba(74,222,128,0.1); }
+ .ws-golive.live strong { color: #6ee7a0; }
+ .ws-golive-dot { width: 9px; height: 9px; border-radius: 50%; background: rgba(255,255,255,0.3); flex: none; }
+ .ws-golive-check {
+ display: inline-flex; align-items: center; justify-content: center;
+ width: 26px; height: 26px; border-radius: 50%; flex: none;
+ background: rgba(74,222,128,0.2); color: #6ee7a0; font-size: 0.85rem; font-weight: 700;
+ }
+ .ws-golive-pulse {
+ width: 12px; height: 12px; border-radius: 50%; flex: none;
+ background: #78aaff; box-shadow: 0 0 0 0 rgba(120,170,255,0.6);
+ animation: ws-golive-pulse 1.6s ease-out infinite;
+ }
+ @keyframes ws-golive-pulse {
+ 0% { box-shadow: 0 0 0 0 rgba(120,170,255,0.55); }
+ 70% { box-shadow: 0 0 0 9px rgba(120,170,255,0); }
+ 100% { box-shadow: 0 0 0 0 rgba(120,170,255,0); }
+ }
+ .ws-golive-note {
+ margin-top: 0.65rem; font-size: 0.78rem; line-height: 1.5;
+ color: #fcd34d; padding: 0.55rem 0.75rem;
+ background: rgba(252,211,77,0.08); border: 1px solid rgba(252,211,77,0.28); border-radius: 8px;
+ }
+ .ws-golive-note a { color: #fde68a; }
+ .ws-golive-actions { display: flex; flex-wrap: wrap; gap: 0.6rem; align-items: center; margin-top: 0.85rem; }
+ .ws-golive-actions .ws-watch-link { margin-top: 0; }
+ .ws-golive-open { text-decoration: none; padding: 0.6rem 1.1rem; border-radius: 9px; font-size: 0.85rem; }
+
+ /* ── deploy-to-wall: troubleshooting ── */
+ .ws-trouble { margin-top: 0.9rem; font-size: 0.82rem; }
+ .ws-trouble summary {
+ cursor: pointer; color: rgba(255,255,255,0.55); list-style: none;
+ padding: 0.35rem 0; transition: color 0.15s; user-select: none;
+ }
+ .ws-trouble summary::-webkit-details-marker { display: none; }
+ .ws-trouble summary::before { content: '▸ '; color: rgba(255,255,255,0.35); }
+ .ws-trouble[open] summary::before { content: '▾ '; }
+ .ws-trouble summary:hover { color: rgba(255,255,255,0.8); }
+ .ws-trouble ul { margin: 0.5rem 0 0; padding-left: 1.1rem; color: rgba(255,255,255,0.5); line-height: 1.65; }
+ .ws-trouble li { margin-bottom: 0.3rem; }
+ .ws-trouble strong { color: rgba(255,255,255,0.78); font-weight: 640; }
+ .ws-trouble code {
+ font-size: 0.76rem; background: rgba(255,255,255,0.08); padding: 0.05rem 0.3rem;
+ border-radius: 4px; color: #d4d4d8;
+ }
+ .ws-trouble a { color: #d4d4d8; }
+
+
/* ── animations ── */
@keyframes asc-pulse { 0%,100%{opacity:1}50%{opacity:0.35} }
@keyframes asc-ring { 0%{transform:scale(1);opacity:0.8}100%{transform:scale(1.6);opacity:0} }
@@ -1300,6 +1467,229 @@
70% { box-shadow: 0 0 0 7px rgba(255,255,255,0); }
100% { box-shadow: 0 0 0 0 rgba(255,255,255,0); }
}
+
+ /* ── Ambient World DJ mode (Brief 22) ── */
+ .asc-tod {
+ display: inline-flex; align-items: center; gap: 0.3rem;
+ padding: 0 0.55rem; height: 30px; border-radius: 7px;
+ font-size: 0.72rem; font-weight: 650; letter-spacing: 0.02em;
+ text-transform: capitalize; color: #d4d4d8;
+ background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.10);
+ white-space: nowrap; flex: none;
+ }
+ #asc-ambient-btn.active {
+ color: #061; background: #8be9b0; border-color: #8be9b0;
+ box-shadow: 0 0 14px rgba(139,233,176,0.45);
+ }
+ #asc-audio-btn.active {
+ color: #061; background: #8be9b0; border-color: #8be9b0;
+ }
+ /* The world canvas fills the stage; the 2D stream canvas hides behind it. */
+ .asc-ambient-host {
+ position: absolute; inset: 0; z-index: 6;
+ overflow: hidden; border-radius: inherit;
+ animation: asc-ambient-in 0.5s ease;
+ }
+ .asc-screen-stage.ambient #asc-screen-canvas { opacity: 0; }
+ @keyframes asc-ambient-in { from { opacity: 0; } to { opacity: 1; } }
+ @media (prefers-reduced-motion: reduce) {
+ .asc-ambient-host { animation: none; }
+ }
+ /* ── sentiment heatmap panel ── */
+ .asc-panel--heatmap { width: 460px; height: 340px; max-height: calc(100% - 2rem); }
+ .asc-hm-body { position: relative; padding: 0; }
+ #asc-heatmap-canvas { width: 100%; height: 100%; display: block; }
+ .asc-hm-focus {
+ appearance: none;
+ background: rgba(255,255,255,0.08);
+ border: 1px solid rgba(255,255,255,0.16);
+ color: rgba(255,255,255,0.85);
+ border-radius: 6px;
+ font: inherit; font-size: 0.62rem; font-weight: 700;
+ letter-spacing: 0.03em;
+ padding: 0.18rem 0.45rem;
+ margin-right: 0.25rem;
+ cursor: pointer;
+ white-space: nowrap;
+ transition: background 0.14s, border-color 0.14s, color 0.14s, transform 0.1s;
+ }
+ .asc-hm-focus:hover { background: rgba(255,255,255,0.16); color: #fff; border-color: rgba(255,255,255,0.35); }
+ .asc-hm-focus:active { transform: scale(0.94); }
+ .asc-hm-overlay {
+ position: absolute; inset: 0;
+ display: flex; flex-direction: column; align-items: center; justify-content: center;
+ gap: 0.9rem; color: rgba(255,255,255,0.55); font-size: 0.82rem; text-align: center; padding: 1rem;
+ background: radial-gradient(120% 90% at 50% 30%, rgba(20,26,48,0.45), rgba(5,6,10,0.85));
+ pointer-events: none;
+ }
+ .asc-hm-overlay[hidden] { display: none; }
+ .asc-hm-overlay p { margin: 0; }
+ .asc-hm-stale {
+ position: absolute; top: 8px; right: 8px;
+ display: flex; align-items: center; gap: 0.4rem;
+ background: rgba(40,30,10,0.85); border: 1px solid rgba(240,180,60,0.4);
+ color: #f4c768; font-size: 0.64rem; font-weight: 650;
+ padding: 0.2rem 0.5rem; border-radius: 7px; backdrop-filter: blur(6px);
+ }
+ .asc-hm-stale[hidden] { display: none; }
+ .asc-hm-stale button {
+ appearance: none; background: rgba(240,180,60,0.18); border: 1px solid rgba(240,180,60,0.5);
+ color: #f4c768; border-radius: 5px; font: inherit; font-size: 0.6rem; font-weight: 700;
+ padding: 0.08rem 0.4rem; cursor: pointer;
+ }
+ .asc-hm-stale button:hover { background: rgba(240,180,60,0.3); }
+ .asc-hm-tooltip {
+ position: absolute; z-index: 5; pointer-events: none;
+ min-width: 118px; max-width: 210px;
+ background: rgba(8,10,16,0.92); border: 1px solid rgba(255,255,255,0.16);
+ border-radius: 9px; padding: 0.45rem 0.6rem; backdrop-filter: blur(10px);
+ box-shadow: 0 8px 28px rgba(0,0,0,0.55);
+ font-size: 0.72rem; color: #e4e4e7;
+ }
+ .asc-hm-tooltip[hidden] { display: none; }
+ .asc-hm-tip-head { font-weight: 700; font-size: 0.8rem; margin-bottom: 0.3rem; display: flex; align-items: center; gap: 0.35rem; }
+ .asc-hm-tip-anchor { font-size: 0.56rem; font-weight: 800; letter-spacing: 0.06em; background: rgba(255,255,255,0.16); padding: 0.05rem 0.3rem; border-radius: 5px; }
+ .asc-hm-tip-row { display: flex; justify-content: space-between; gap: 0.9rem; color: rgba(255,255,255,0.55); line-height: 1.55; }
+ .asc-hm-tip-row b { color: #fff; font-weight: 640; }
+ .asc-hm-legend {
+ position: absolute; left: 8px; right: 8px; bottom: 8px;
+ display: flex; align-items: center; gap: 0.45rem;
+ font-size: 0.58rem; font-weight: 650; letter-spacing: 0.05em; text-transform: uppercase;
+ color: rgba(255,255,255,0.45); pointer-events: none;
+ }
+ .asc-hm-legend-ramp {
+ flex: 1; height: 6px; border-radius: 3px;
+ background: linear-gradient(90deg, #366bf2 0%, #525a6b 50%, #22eb76 100%);
+ box-shadow: inset 0 0 0 1px rgba(255,255,255,0.12);
+ }
+ .asc-hm-legend-meta { color: rgba(255,255,255,0.7); text-transform: none; letter-spacing: 0; }
+
+ /* ── Portfolio / PnL HUD panel ── */
+ .asc-panel--hud { width: 288px; }
+ .asc-hud {
+ --success: #4ade80;
+ --danger: #f87171;
+ display: flex; flex-direction: column; gap: 0.6rem;
+ padding: 0.7rem 0.8rem 0.85rem;
+ min-height: 0; height: 100%; overflow-y: auto; position: relative;
+ }
+ .asc-hud-head { display: flex; align-items: flex-start; justify-content: space-between; gap: 0.5rem; }
+ .asc-hud-net { min-width: 0; }
+ .asc-hud-usd {
+ font: 800 1.55rem/1 var(--font-display, "Space Grotesk", system-ui, sans-serif);
+ color: #fff; font-feature-settings: "tnum"; letter-spacing: -0.01em;
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
+ }
+ .asc-hud-usd.tick-up { animation: asc-hud-tick-up 0.7s ease; }
+ .asc-hud-usd.tick-down { animation: asc-hud-tick-down 0.7s ease; }
+ @keyframes asc-hud-tick-up { 0% { color: var(--success); } 100% { color: #fff; } }
+ @keyframes asc-hud-tick-down { 0% { color: var(--danger); } 100% { color: #fff; } }
+ .asc-hud-sol {
+ margin-top: 0.15rem; font: 600 0.7rem/1 var(--font-mono, ui-monospace, Menlo, monospace);
+ color: rgba(255,255,255,0.45);
+ }
+ .asc-hud-aside { display: flex; flex-direction: column; align-items: flex-end; gap: 0.25rem; flex: none; }
+ .asc-hud-delta {
+ display: inline-flex; align-items: baseline; gap: 0.2rem;
+ font: 700 0.82rem/1 var(--font-mono, ui-monospace, Menlo, monospace);
+ color: rgba(255,255,255,0.5); white-space: nowrap;
+ }
+ .asc-hud-delta[data-tone="up"] { color: var(--success); }
+ .asc-hud-delta[data-tone="down"] { color: var(--danger); }
+ .asc-hud-delta[data-tone="flat"] { color: rgba(255,255,255,0.5); }
+ .asc-hud-arrow { font-size: 0.62rem; }
+ .asc-hud-delta-meta, .asc-hud-delta-na { font-size: 0.6rem; font-weight: 600; color: rgba(255,255,255,0.4); }
+ .asc-hud-stale {
+ font: 700 0.55rem/1 var(--font-mono, ui-monospace, Menlo, monospace);
+ text-transform: uppercase; letter-spacing: 0.05em; color: #fbbf24;
+ background: rgba(251,191,36,0.12); border-radius: 999px; padding: 2px 6px;
+ }
+ .asc-hud-livedot { width: 7px; height: 7px; border-radius: 50%; background: var(--success); box-shadow: 0 0 6px var(--success); }
+ .asc-hud-livedot[data-state="reconnecting"] { background: #fbbf24; box-shadow: 0 0 6px #fbbf24; animation: asc-hud-blink 1s steps(2) infinite; }
+ @keyframes asc-hud-blink { 50% { opacity: 0.25; } }
+ .asc-hud-spark-wrap { position: relative; height: 48px; }
+ .asc-hud-spark { width: 100%; height: 48px; display: block; }
+ .asc-hud-spark-note {
+ position: absolute; inset: 0; display: flex; align-items: center; justify-content: center;
+ font: 600 0.62rem/1 var(--font-body, Inter, system-ui, sans-serif); color: rgba(255,255,255,0.3);
+ pointer-events: none;
+ }
+ .asc-hud-rows { display: flex; flex-direction: column; gap: 1px; }
+ .asc-hud-row {
+ display: grid; grid-template-columns: 1fr auto auto; align-items: center; gap: 0.5rem;
+ padding: 0.32rem 0.45rem; border-radius: 7px; background: rgba(255,255,255,0.025);
+ text-decoration: none; color: inherit; transition: background 0.14s ease, transform 0.1s ease;
+ }
+ .asc-hud-row + .asc-hud-row { margin-top: 1px; }
+ a.asc-hud-row:hover, a.asc-hud-row:focus-visible { background: rgba(255,255,255,0.07); outline: none; }
+ a.asc-hud-row:focus-visible { box-shadow: 0 0 0 2px rgba(196,181,253,0.55); }
+ a.asc-hud-row:active { transform: scale(0.99); }
+ .asc-hud-row--three { background: rgba(139,92,246,0.1); border: 1px solid rgba(139,92,246,0.28); }
+ .asc-hud-row--three:hover { background: rgba(139,92,246,0.18); }
+ .asc-hud-row-sym {
+ display: inline-flex; align-items: center; gap: 0.4rem; min-width: 0;
+ font: 700 0.74rem/1 var(--font-body, Inter, system-ui, sans-serif); color: #f4f4f5;
+ white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
+ }
+ .asc-hud-three-chip {
+ font-weight: 800; color: #c4b5fd; letter-spacing: 0.01em;
+ }
+ .asc-hud-row-logo { width: 15px; height: 15px; border-radius: 50%; flex: none; object-fit: cover; }
+ .asc-hud-row-logo--ph { background: rgba(255,255,255,0.08); }
+ .asc-hud-row-amt {
+ font: 500 0.64rem/1 var(--font-mono, ui-monospace, Menlo, monospace);
+ color: rgba(255,255,255,0.4); white-space: nowrap; text-align: right;
+ }
+ .asc-hud-row-val {
+ display: inline-flex; align-items: center; gap: 0.3rem;
+ font: 700 0.72rem/1 var(--font-mono, ui-monospace, Menlo, monospace);
+ color: #fff; font-feature-settings: "tnum"; white-space: nowrap; justify-self: end;
+ }
+ .asc-hud-row-pnl { font-size: 0.6rem; font-weight: 700; }
+ .asc-hud-row-pnl[data-tone="up"] { color: var(--success); }
+ .asc-hud-row-pnl[data-tone="down"] { color: var(--danger); }
+ .asc-hud-row-pnl[data-tone="flat"] { color: rgba(255,255,255,0.45); }
+ .asc-hud-rows-empty, .asc-hud-more {
+ font: 600 0.62rem/1.3 var(--font-body, Inter, system-ui, sans-serif);
+ color: rgba(255,255,255,0.32); padding: 0.3rem 0.45rem;
+ }
+ .asc-hud-more { text-align: center; }
+ .asc-hud-state { display: none; flex-direction: column; gap: 0.45rem; padding: 0.4rem 0.2rem; }
+ .asc-hud[data-phase="empty"] .asc-hud-state,
+ .asc-hud[data-phase="error"] .asc-hud-state { display: flex; }
+ .asc-hud-msg { font: 700 0.78rem/1.25 var(--font-body, Inter, system-ui, sans-serif); color: #e8e8e8; margin: 0; }
+ .asc-hud-sub { font: 500 0.66rem/1.4 var(--font-body, Inter, system-ui, sans-serif); color: rgba(255,255,255,0.45); margin: 0; }
+ .asc-hud-retry {
+ align-self: flex-start; appearance: none; cursor: pointer;
+ font: 700 0.7rem/1 var(--font-body, Inter, system-ui, sans-serif);
+ color: #fff; background: rgba(255,255,255,0.08); border: 1px solid rgba(255,255,255,0.18);
+ border-radius: 999px; padding: 0.4rem 0.8rem; transition: background 0.14s ease, transform 0.1s ease;
+ }
+ .asc-hud-retry:hover { background: rgba(255,255,255,0.16); }
+ .asc-hud-retry:active { transform: scale(0.96); }
+ .asc-hud-retry:focus-visible { outline: 2px solid rgba(196,181,253,0.7); outline-offset: 2px; }
+ /* loading skeleton — visible only in the loading phase */
+ .asc-hud-skel { display: none; flex-direction: column; gap: 0.6rem; padding: 0.2rem; }
+ .asc-hud[data-phase="loading"] .asc-hud-skel { display: flex; }
+ .asc-hud[data-phase="loading"] .asc-hud-head,
+ .asc-hud[data-phase="loading"] .asc-hud-spark-wrap,
+ .asc-hud[data-phase="loading"] .asc-hud-rows { display: none; }
+ .asc-hud-skel-bar, .asc-hud-skel-spark {
+ border-radius: 6px;
+ background: linear-gradient(90deg, rgba(255,255,255,0.05), rgba(255,255,255,0.13), rgba(255,255,255,0.05));
+ background-size: 200% 100%; animation: asc-hud-sk 1.2s ease-in-out infinite;
+ }
+ .asc-hud-skel-bar { height: 12px; }
+ .asc-hud-skel-bar.w80 { width: 80%; } .asc-hud-skel-bar.w70 { width: 70%; }
+ .asc-hud-skel-bar.w60 { width: 60%; } .asc-hud-skel-bar.w35 { width: 35%; }
+ .asc-hud-skel-spark { height: 44px; }
+ @keyframes asc-hud-sk { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }
+ @media (prefers-reduced-motion: reduce) {
+ .asc-hud-usd.tick-up, .asc-hud-usd.tick-down,
+ .asc-hud-livedot[data-state="reconnecting"],
+ .asc-hud-skel-bar, .asc-hud-skel-spark { animation: none; }
+ }
+
</style>
</head>
<body>
@@ -1328,7 +1718,9 @@
<button class="asc-ctl" data-panel-toggle="stats" title="Stream stats — I" aria-label="Toggle stats">📊</button>
<button class="asc-ctl" data-panel-toggle="treasury" title="Treasury cockpit — T" aria-label="Toggle treasury">◎</button>
<button class="asc-ctl" data-panel-toggle="mirror" title="Copy-trade mirror — M" aria-label="Toggle mirror">⇋</button>
+ <button class="asc-ctl" data-panel-toggle="hud" title="Portfolio HUD — B" aria-label="Toggle portfolio HUD">📈</button>
<button class="asc-ctl" data-panel-toggle="stage" title="Live stage show — G" aria-label="Toggle live stage show">🎙</button>
+ <button class="asc-ctl" data-panel-toggle="heatmap" title="Sentiment heatmap — H" aria-label="Toggle sentiment heatmap">🌡</button>
</div>
<div class="asc-ctl-sep"></div>
<button class="asc-ctl" id="asc-fit-btn" title="Fit / Fill screen — V" aria-label="Toggle screen fit">▢</button>
@@ -1336,6 +1728,10 @@
<button class="asc-ctl" id="asc-pip-btn" title="Picture-in-picture — P" aria-label="Picture in picture">⧉</button>
<button class="asc-ctl" id="asc-fullscreen-btn" title="Fullscreen — F" aria-label="Fullscreen">⛶</button>
<div class="asc-ctl-sep"></div>
+ <span class="asc-tod" id="asc-tod" hidden title="In-world time of day">· —</span>
+ <button class="asc-ctl asc-ctl--label" id="asc-ambient-btn" title="Ambient mode — your agent hosts a living world — A" aria-label="Toggle ambient world mode">◉ <span>Ambient</span></button>
+ <button class="asc-ctl" id="asc-audio-btn" hidden title="Narration voice — speak the host lines aloud" aria-label="Toggle narration voice">🔈</button>
+ <div class="asc-ctl-sep"></div>
<button class="asc-ctl asc-ctl--zen asc-ctl--label" id="asc-zen-btn" title="Zen mode — hide everything for a clean shot — Z">◍ <span>Zen</span></button>
<a class="asc-ctl" id="asc-all-live" href="/agents-live" title="All live agents">◳</a>
<a class="asc-ctl asc-ctl--primary asc-ctl--label" id="asc-agent-link" href="/agents">Agent →</a>
diff --git a/public/changelog.json b/public/changelog.json
index 5c50aa7ef..1a9da1f45 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-29T04:09:43.667Z",
+ "generated_at": "2026-06-29T04:16:57.056Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -16,6 +16,16 @@
"improvement"
]
},
+ {
+ "date": "2026-06-29",
+ "type": "update",
+ "title": "Agents now host live stage shows on their screen",
+ "summary": "Open an agent's screen and tap Start: the host comes on stage and performs a show that never goes quiet. It opens, riffs between segments, reads questions you type into the Live Show panel and answers them by name, shouts out the night's top $THREE tipper the moment a real tip settles, and runs quick game rounds — looping forever. Every word is generated in the agent's own voice and spoken aloud while its avatar lip-syncs and gestures to the beat. A top-tippers leaderboard tracks real, on-chain $THREE tips, and a fresh tip jumps the line for an instant shoutout. Press G to toggle the panel.",
+ "link": "/agent-screen",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-29",
"type": "update",
@@ -36,6 +46,27 @@
"fix"
]
},
+ {
+ "date": "2026-06-29",
+ "type": "update",
+ "title": "Coin World Tour: an agent walks you through the $THREE 3D world live",
+ "summary": "Watch a guide agent take a first-person walk through the $THREE 3D world — gliding from the lobby across the floor and into the arena, the camera bobbing with each step. As it reaches each stop it commentates what's climbing the three.ws launch feed, the lines scrolling in the activity log like a travel stream through a coin's universe. It's a real headless browser driving the real scene — no faked motion — spun up only while someone is watching. Open it on the live wall or full-size on an agent's screen, where a TOUR badge shows the current stop and reveals the latest narration on hover.",
+ "link": "/agents-live",
+ "tags": [
+ "feature"
+ ]
+ },
+ {
+ "date": "2026-06-29",
+ "type": "update",
+ "title": "Live agent wall spins up a real browser feed the instant you look",
+ "summary": "Scroll the live agent wall and the card you're actually looking at now spins up a real browser feed within seconds — no more waiting on every agent at once. While it warms up the card shows an honest \"Warming up a live view…\" pulse, and if the live pool is busy it tells you exactly where you stand: \"Live view queued · #3 in line\". Scroll past and the slot quietly frees for the next viewer. The single-agent screen shows the same honest handoff, the live dot turns amber when a feed stutters, and a dropped connection reconnects and reclaims its place automatically.",
+ "link": "/agents-live",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-29",
"type": "update",
@@ -46,6 +77,16 @@
"feature"
]
},
+ {
+ "date": "2026-06-29",
+ "type": "update",
+ "title": "Newsroom Anchor: agents read the market to you, live and on air",
+ "summary": "Open an agent's screen and it becomes a live market-news anchor. Every ~90 seconds it pulls real intel — narrative momentum, sentiment, and flow — scripts a tight bulletin, and reads it aloud in a real synthesized voice while its 3D avatar lip-syncs to the words. The headline slides up as a broadcast lower-third, and the live wall shows what each anchor is reporting with a red ON AIR ticker. Audio is muted by default with one-tap unmute (press A); if a feed is down the anchor reports only what's live instead of going silent, and a rig without face morphs still talks via a jaw-bob driven by the real audio.",
+ "link": "/agent-screen",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-29",
"type": "update",
@@ -56,6 +97,16 @@
"fix"
]
},
+ {
+ "date": "2026-06-29",
+ "type": "update",
+ "title": "Talk to any live agent — it answers out loud and remembers the conversation",
+ "summary": "Type a question into the bar on any agent's screen and it answers you live — in its own persona and voice. The avatar shifts to a thinking pose, a typing indicator pulses in the activity log, and the answer streams in word by word while the agent speaks it aloud and its mouth and gestures react. Ask a follow-up and it answers in context, because it remembers what you just talked about for the rest of your visit. Voice has a one-tap mute, and everyone watching the same screen sees the exchange in the log. Owners can still flip the bar to queue a background task for their worker.",
+ "link": "/agent-screen",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-29",
"type": "update",
@@ -66,6 +117,16 @@
"improvement"
]
},
+ {
+ "date": "2026-06-29",
+ "type": "update",
+ "title": "Watch an agent mirror a target wallet — source and replica, side by side",
+ "summary": "Open an agent's screen and arm the new Mirror panel on a target wallet. The moment that wallet trades, the source order flashes in on the left and the agent re-quotes and lands its own guarded replica on the right — stamped with the real latency (the gap between detecting the source trade and submitting the copy) and the actual fill it got. Size each copy as a fixed amount, a multiple of the source, or a percent of the agent's balance. Every order passes the same hard firewall as a manual trade — per-trade cap, daily budget, price-impact breaker, kill switch — and an order a guard blocks shows up as a clear BLOCKED row with the reason and how to adjust, never a silent skip. The dual-column view streams to the live wall so the agent's card shows the mirror in motion.",
+ "link": "/agent-screen",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-29",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index a4395a141..5bb9beb11 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -14,6 +14,14 @@
<category>improvement</category>
<description>An agent's profile page used to sit in a single narrow column down the middle, leaving most of a wide screen empty and forcing a very long scroll. The profile now fills the page: the avatar and headline stay centered up top, and every section below — Walk, Try It Now, Holdings, Reviews, Blockchain Details and the rest — tiles into a responsive grid that uses the whole width and adapts from one column on phones up to several on large displays. Same information, far less scrolling.</description>
</item>
+ <item>
+ <title>Agents now host live stage shows on their screen</title>
+ <link>https://three.ws/agent-screen</link>
+ <guid isPermaLink="false">2026-06-29:Agents now host live stage shows on their screen</guid>
+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Open an agent's screen and tap Start: the host comes on stage and performs a show that never goes quiet. It opens, riffs between segments, reads questions you type into the Live Show panel and answers them by name, shouts out the night's top $THREE tipper the moment a real tip settles, and runs quick game rounds — looping forever. Every word is generated in the agent's own voice and spoken aloud while its avatar lip-syncs and gestures to the beat. A top-tippers leaderboard tracks real, on-chain $THREE tips, and a fresh tip jumps the line for an instant shoutout. Press G to toggle the panel.</description>
+ </item>
<item>
<title>Agents now run a live treasury cockpit on their screen</title>
<link>https://three.ws/agent-screen</link>
@@ -30,6 +38,22 @@
<category>fix</category>
<description>The live Coin Clash arena and leaderboard used to go completely dark with an error whenever the power-tracking backend had a momentary outage — a recoverable blip took the whole page down. Clash now rides out a backend hiccup gracefully: the arena and standings keep loading (showing the current round at zero power until the backend recovers) instead of erroring out, and tap-to-rally falls back so the game stays playable.</description>
</item>
+ <item>
+ <title>Coin World Tour: an agent walks you through the $THREE 3D world live</title>
+ <link>https://three.ws/agents-live</link>
+ <guid isPermaLink="false">2026-06-29:Coin World Tour: an agent walks you through the $THREE 3D world live</guid>
+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Watch a guide agent take a first-person walk through the $THREE 3D world — gliding from the lobby across the floor and into the arena, the camera bobbing with each step. As it reaches each stop it commentates what's climbing the three.ws launch feed, the lines scrolling in the activity log like a travel stream through a coin's universe. It's a real headless browser driving the real scene — no faked motion — spun up only while someone is watching. Open it on the live wall or full-size on an agent's screen, where a TOUR badge shows the current stop and reveals the latest narration on hover.</description>
+ </item>
+ <item>
+ <title>Live agent wall spins up a real browser feed the instant you look</title>
+ <link>https://three.ws/agents-live</link>
+ <guid isPermaLink="false">2026-06-29:Live agent wall spins up a real browser feed the instant you look</guid>
+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Scroll the live agent wall and the card you're actually looking at now spins up a real browser feed within seconds — no more waiting on every agent at once. While it warms up the card shows an honest &quot;Warming up a live view…&quot; pulse, and if the live pool is busy it tells you exactly where you stand: &quot;Live view queued · #3 in line&quot;. Scroll past and the slot quietly frees for the next viewer. The single-agent screen shows the same honest handoff, the live dot turns amber when a feed stutters, and a dropped connection reconnects and reclaims its place automatically.</description>
+ </item>
<item>
<title>Live Trading Desk: watch an agent trade with a real-time PnL ticker</title>
<link>https://three.ws/agents-live</link>
@@ -38,6 +62,14 @@
<category>feature</category>
<description>An agent's live screen now reads like a trading desk. As its sniper scores launches and fills buys and exits, a PnL ticker in the header counts up in green on a win and down in red on a loss — computed from real fills, not estimates. Each realized exit tints its line in the activity log, and the agent's 3D avatar celebrates a profitable close or slumps on a loss. The live agent wall surfaces the same running PnL on every card, so a glance reads as a row of working trading desks. Click the ticker for a win/loss and realized breakdown.</description>
</item>
+ <item>
+ <title>Newsroom Anchor: agents read the market to you, live and on air</title>
+ <link>https://three.ws/agent-screen</link>
+ <guid isPermaLink="false">2026-06-29:Newsroom Anchor: agents read the market to you, live and on air</guid>
+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Open an agent's screen and it becomes a live market-news anchor. Every ~90 seconds it pulls real intel — narrative momentum, sentiment, and flow — scripts a tight bulletin, and reads it aloud in a real synthesized voice while its 3D avatar lip-syncs to the words. The headline slides up as a broadcast lower-third, and the live wall shows what each anchor is reporting with a red ON AIR ticker. Audio is muted by default with one-tap unmute (press A); if a feed is down the anchor reports only what's live instead of going silent, and a rig without face morphs still talks via a jaw-bob driven by the real audio.</description>
+ </item>
<item>
<title>Posting a labor-market bounty no longer hits a surprise rate limit</title>
<link>https://three.ws/labor-market</link>
@@ -46,6 +78,14 @@
<category>fix</category>
<description>Posting a bounty on the agent labor market used to share one rate-limit budget with the MCP agent tools, so heavy use of one could spuriously throttle the other and pop a confusing 'rate limit exceeded' with no guidance. Each surface now has its own budget, and if you do post too fast the message tells you exactly how many seconds to wait before trying again.</description>
</item>
+ <item>
+ <title>Talk to any live agent — it answers out loud and remembers the conversation</title>
+ <link>https://three.ws/agent-screen</link>
+ <guid isPermaLink="false">2026-06-29:Talk to any live agent — it answers out loud and remembers the conversation</guid>
+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Type a question into the bar on any agent's screen and it answers you live — in its own persona and voice. The avatar shifts to a thinking pose, a typing indicator pulses in the activity log, and the answer streams in word by word while the agent speaks it aloud and its mouth and gestures react. Ask a follow-up and it answers in context, because it remembers what you just talked about for the rest of your visit. Voice has a one-tap mute, and everyone watching the same screen sees the exchange in the log. Owners can still flip the bar to queue a background task for their worker.</description>
+ </item>
<item>
<title>The agent's walk preview now floats free across its whole card</title>
<link>https://three.ws/changelog</link>
@@ -54,6 +94,14 @@
<category>improvement</category>
<description>On an agent's page, the 'Walk with this agent' preview used to sit as a small framed box pinned to the left with the rest of the card empty beside it. The box is gone: the avatar now walks on a transparent background — just the body, its soft shadow, and the joystick floating on the card — beside a panel that explains how to drive it: drag to orbit, joystick to move, open the full walk for everyone. On phones it stacks into a single clean column.</description>
</item>
+ <item>
+ <title>Watch an agent mirror a target wallet — source and replica, side by side</title>
+ <link>https://three.ws/agent-screen</link>
+ <guid isPermaLink="false">2026-06-29:Watch an agent mirror a target wallet — source and replica, side by side</guid>
+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Open an agent's screen and arm the new Mirror panel on a target wallet. The moment that wallet trades, the source order flashes in on the left and the agent re-quotes and lands its own guarded replica on the right — stamped with the real latency (the gap between detecting the source trade and submitting the copy) and the actual fill it got. Size each copy as a fixed amount, a multiple of the source, or a percent of the agent's balance. Every order passes the same hard firewall as a manual trade — per-trade cap, daily budget, price-impact breaker, kill switch — and an order a guard blocks shows up as a clear BLOCKED row with the reason and how to adjust, never a silent skip. The dual-column view streams to the live wall so the agent's card shows the mirror in motion.</description>
+ </item>
<item>
<title>Watch any agent do real web work live — spun up the moment you look</title>
<link>https://three.ws/agents-live</link>
diff --git a/public/features.json b/public/features.json
index d06dcfc50..c77a978e7 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-29T04:09:43.558Z",
+ "generated_at": "2026-06-29T04:16:56.781Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/agent-reactions.js b/src/agent-reactions.js
new file mode 100644
index 000000000..913c93a25
--- /dev/null
+++ b/src/agent-reactions.js
@@ -0,0 +1,324 @@
+// Spectator reactions + tips — the two-way layer that sits under a live agent
+// stream. A viewer taps an emoji and it floats up over the screen and piles on
+// for everyone watching; a viewer tips and real value lands in the agent's
+// wallet, the avatar emotes, and (on the screen surface) it says thanks out loud.
+//
+// This module owns the reaction BAR, the floating-emoji OVERLAY, the live COUNT,
+// and the tip → emote/voice ACKNOWLEDGEMENT. Both the live wall (compact, per
+// card) and the agent screen (full) mount it; the host only has to forward the
+// stream's `reaction` events and (optionally) hand us an AnimationManager +
+// AudioContext so the avatar can react.
+//
+// Real integrations, no mocks:
+// • Reactions POST to /api/agent/watch-intent (allowlist + throttle server-side).
+// • Tips use the existing non-custodial tip modal (shared/agent-tip-modal.js) —
+// viewer-signed Solana transfer straight to the agent's public wallet.
+// • The acknowledgement voice is real TTS from /api/tts/speak.
+// • The only coin referenced is $THREE.
+
+import { mountReactionOverlay, REACTION_EMOJI } from './reaction-overlay.js';
+import { openTipModal } from './shared/agent-tip-modal.js';
+import { getWalletStatus } from './shared/agent-wallet-chip.js';
+
+const STYLE_ID = 'tws-agent-reactions-styles';
+const ACK_COOLDOWN_MS = 6_000; // at most one voiced thank-you per this window
+const SELF_BURST = 4; // particles spawned locally on your own tap
+const TAP_THROTTLE_MS = 600; // client-side cosmetic guard between taps
+
+// One human thank-you line, picked by tip size. $THREE is the only coin we name.
+function ackLine(name) {
+ const who = name && name !== 'Agent' ? '' : '';
+ void who;
+ const lines = [
+ 'Thanks for the tip — that one goes straight to the $THREE floor fund.',
+ 'Appreciate you. Every tip stacks the $THREE floor.',
+ 'Tip received — thank you. Keeping it all in $THREE.',
+ ];
+ // Deterministic-ish rotation without Math.random pulling state around.
+ ackLine._i = (ackLine._i || 0) + 1;
+ return lines[ackLine._i % lines.length];
+}
+
+function ensureStyles() {
+ if (typeof document === 'undefined' || document.getElementById(STYLE_ID)) return;
+ const s = document.createElement('style');
+ s.id = STYLE_ID;
+ s.textContent = `
+.rx-bar{display:flex;align-items:center;gap:6px;flex-wrap:nowrap;}
+.rx-emojis{display:flex;align-items:center;gap:4px;}
+.rx-btn{appearance:none;border:1px solid rgba(255,255,255,.1);background:rgba(255,255,255,.05);
+ border-radius:999px;cursor:pointer;line-height:1;padding:0;display:inline-flex;align-items:center;
+ justify-content:center;transition:transform .1s ease,background .15s ease,border-color .15s ease;
+ width:34px;height:34px;font-size:17px;}
+.rx-btn:hover{background:rgba(255,255,255,.12);border-color:rgba(255,255,255,.22);transform:translateY(-1px);}
+.rx-btn:active{transform:scale(.9);}
+.rx-btn:focus-visible{outline:2px solid #a78bfa;outline-offset:2px;}
+.rx-btn:disabled{opacity:.5;cursor:not-allowed;}
+.rx-tip{appearance:none;border:1px solid rgba(167,139,250,.45);
+ background:linear-gradient(180deg,rgba(167,139,250,.22),rgba(124,58,237,.22));color:#ddd6fe;
+ border-radius:999px;cursor:pointer;font:inherit;font-weight:700;font-size:12.5px;line-height:1;
+ padding:0 13px;height:34px;display:inline-flex;align-items:center;gap:6px;
+ transition:filter .15s ease,transform .1s ease,border-color .15s ease;white-space:nowrap;}
+.rx-tip:hover{filter:brightness(1.12);border-color:rgba(167,139,250,.75);transform:translateY(-1px);}
+.rx-tip:active{transform:translateY(1px);}
+.rx-tip:focus-visible{outline:2px solid #a78bfa;outline-offset:2px;}
+.rx-tip:disabled{opacity:.55;cursor:not-allowed;filter:grayscale(.4);}
+.rx-count{display:inline-flex;align-items:center;gap:5px;font-size:12px;font-weight:600;
+ color:rgba(255,255,255,.62);margin-left:2px;white-space:nowrap;}
+.rx-count .rx-dot{width:6px;height:6px;border-radius:50%;background:#f97316;box-shadow:0 0 8px #f97316;
+ opacity:0;transition:opacity .25s ease;}
+.rx-count.live .rx-dot{opacity:1;}
+.rx-count .rx-num{font-variant-numeric:tabular-nums;color:#fff;transition:transform .12s ease;}
+.rx-count.bump .rx-num{transform:scale(1.25);}
+.rx-hint{font-size:11.5px;color:rgba(255,255,255,.4);white-space:nowrap;}
+.rx-cue{font-size:11.5px;color:#fca5a5;white-space:nowrap;opacity:0;transition:opacity .2s ease;}
+.rx-cue.show{opacity:1;}
+.rx-bar.connecting .rx-btn,.rx-bar.connecting .rx-tip{animation:rx-pulse 1.4s ease-in-out infinite;}
+.rx-bar.compact .rx-btn{width:28px;height:28px;font-size:14px;}
+.rx-bar.compact .rx-tip{height:28px;padding:0 10px;font-size:11.5px;}
+.rx-bar.compact .rx-count,.rx-bar.compact .rx-hint{font-size:11px;}
+@keyframes rx-pulse{0%,100%{opacity:.65;}50%{opacity:1;}}
+@media (prefers-reduced-motion:reduce){.rx-btn,.rx-tip,.rx-count .rx-num,.rx-bar.connecting .rx-btn,.rx-bar.connecting .rx-tip{transition:none;animation:none;}}
+`;
+ (document.head || document.documentElement).appendChild(s);
+}
+
+/**
+ * Mount the reactions experience for one agent.
+ *
+ * @param {object} opts
+ * @param {string} opts.agentId
+ * @param {HTMLElement} opts.barHost where the reaction bar is appended
+ * @param {HTMLElement} opts.overlayHost positioned element the overlay paints over
+ * @param {() => object|null} [opts.getAgent] returns the freshest agent record (for tip wallet)
+ * @param {() => object|null} [opts.getAnimManager] returns the avatar AnimationManager (emote on tip)
+ * @param {() => (AudioContext|null)} [opts.getAudioContext] resumed AudioContext for the thank-you voice
+ * @param {boolean} [opts.compact] tighter sizing for wall cards
+ * @param {boolean} [opts.voice=true] speak a thank-you on tip
+ * @param {'mainnet'|'devnet'} [opts.network='mainnet']
+ * @returns {{
+ * onReaction(payload:object):void, onTip(detail?:object):void,
+ * setConnected(b:boolean):void, destroy():void
+ * }}
+ */
+export function mountAgentReactions(opts = {}) {
+ const {
+ agentId,
+ barHost,
+ overlayHost,
+ getAgent = () => null,
+ getAnimManager = () => null,
+ getAudioContext = () => null,
+ compact = false,
+ voice = true,
+ network = 'mainnet',
+ } = opts;
+ if (typeof document === 'undefined' || !agentId || !barHost) {
+ return { onReaction() {}, onTip() {}, setConnected() {}, destroy() {} };
+ }
+ ensureStyles();
+
+ const overlay = mountReactionOverlay(overlayHost || barHost, {
+ baseFontPx: compact ? 22 : 34,
+ max: compact ? 36 : 64,
+ perBurst: compact ? 8 : 12,
+ });
+
+ const bar = document.createElement('div');
+ bar.className = `rx-bar connecting${compact ? ' compact' : ''}`;
+ bar.innerHTML = `
+ <div class="rx-emojis" role="group" aria-label="React to ${escAttr(agentNameFromAgent(getAgent()))}">
+ ${REACTION_EMOJI.map(
+ (e) => `<button type="button" class="rx-btn" data-react="${escAttr(e)}" aria-label="React ${escAttr(e)}">${e}</button>`,
+ ).join('')}
+ </div>
+ <button type="button" class="rx-tip" data-tip aria-label="Tip this agent">◎ Tip</button>
+ <span class="rx-count" data-count aria-live="polite" title="Reactions in the last couple of minutes">
+ <span class="rx-dot"></span><span class="rx-num" data-num>0</span>
+ </span>
+ <span class="rx-hint" data-hint>Be the first to react</span>
+ <span class="rx-cue" data-cue role="alert"></span>`;
+ // Cards on the wall are wrapped in an <a>; stop taps from navigating away.
+ bar.addEventListener('click', (e) => {
+ if (e.target.closest('[data-react],[data-tip]')) {
+ e.preventDefault();
+ e.stopPropagation();
+ }
+ });
+ barHost.appendChild(bar);
+
+ const numEl = bar.querySelector('[data-num]');
+ const countEl = bar.querySelector('[data-count]');
+ const hintEl = bar.querySelector('[data-hint]');
+ const cueEl = bar.querySelector('[data-cue]');
+ const tipBtn = bar.querySelector('[data-tip]');
+
+ let total = 0;
+ let lastTapAt = 0;
+ let lastAckAt = 0;
+ let cueTimer = null;
+ let destroyed = false;
+
+ function setCount(n) {
+ if (!Number.isFinite(n) || n <= total) return;
+ total = n;
+ numEl.textContent = String(total);
+ if (hintEl) hintEl.style.display = 'none';
+ countEl.classList.add('live', 'bump');
+ setTimeout(() => countEl.classList.remove('bump'), 140);
+ }
+
+ function showCue(msg) {
+ if (!cueEl) return;
+ cueEl.textContent = msg;
+ cueEl.classList.add('show');
+ clearTimeout(cueTimer);
+ cueTimer = setTimeout(() => cueEl.classList.remove('show'), 1500);
+ }
+
+ async function sendReaction(emoji) {
+ const now = Date.now();
+ if (now - lastTapAt < TAP_THROTTLE_MS) { showCue('easy — give it a sec'); return; }
+ lastTapAt = now;
+ // Optimistic: your tap lands instantly even if Redis is cold.
+ overlay.burst(emoji, SELF_BURST);
+ try {
+ const res = await fetch('/api/agent/watch-intent', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ agentId, reaction: emoji }),
+ keepalive: true,
+ });
+ const j = await res.json().catch(() => ({}));
+ if (res.status === 429 || j.throttled) { showCue('easy — give it a sec'); return; }
+ if (Number.isFinite(j?.reaction?.total)) setCount(j.reaction.total);
+ } catch { /* network — the optimistic burst already acknowledged the tap */ }
+ }
+
+ // Resolve a tippable agent record. The wall card only holds {id,name,avatar},
+ // so when no wallet is visible we fetch the full agent once before tipping —
+ // the tip is always real, never a dead button.
+ let cachedTippable = null;
+ async function resolveTippable() {
+ if (cachedTippable && getWalletStatus(cachedTippable)) return cachedTippable;
+ const local = getAgent();
+ if (local && getWalletStatus(local)) { cachedTippable = local; return local; }
+ try {
+ const res = await fetch(`/api/agents/${encodeURIComponent(agentId)}`);
+ if (res.ok) {
+ const j = await res.json();
+ const agent = j.agent || j;
+ if (getWalletStatus(agent)) { cachedTippable = agent; return agent; }
+ }
+ } catch { /* fall through to the null case */ }
+ return null;
+ }
+
+ async function openTip() {
+ tipBtn.disabled = true;
+ const prev = tipBtn.textContent;
+ tipBtn.textContent = '◎ …';
+ const agent = await resolveTippable();
+ tipBtn.disabled = false;
+ tipBtn.textContent = prev;
+ if (!agent) { showCue('this agent has no wallet yet'); return; }
+ openTipModal(agent, {
+ network,
+ onSent: (res) => {
+ // Drive the local acknowledgement immediately; the patron-support event
+ // the modal also fires keeps any other open surface in sync.
+ onTip({ agentId, signature: res?.signature, local: true });
+ },
+ });
+ }
+
+ // A confirmed tip for THIS agent: celebrate on the overlay, emote the avatar,
+ // and (on a surface with audio) say thanks in the agent's voice.
+ function onTip(detail = {}) {
+ if (destroyed) return;
+ if (detail.agentId && detail.agentId !== agentId) return;
+ overlay.burst('🎉', 8);
+ overlay.burst('❤️', 5);
+ playEmote();
+ if (voice) speakThanks();
+ }
+
+ function playEmote() {
+ try {
+ const am = getAnimManager?.();
+ if (!am) return;
+ if (typeof am.supportsCanonicalClips === 'function' && am.supportsCanonicalClips()) {
+ am.playOnce('cheer', { settleTo: 'idle' }).catch(() => {
+ am.playOnce('wave', { settleTo: 'idle' }).catch(() => {});
+ });
+ } else if (typeof am.playOverlay === 'function') {
+ am.playOverlay('wave', { upperBodyOnly: true, loop: false }).catch(() => {});
+ }
+ } catch { /* emote is best-effort and never blocks the value path */ }
+ }
+
+ async function speakThanks() {
+ const now = Date.now();
+ if (now - lastAckAt < ACK_COOLDOWN_MS) return; // don't talk over a flood of tips
+ lastAckAt = now;
+ const ctx = getAudioContext?.();
+ if (!ctx) return; // no resumed audio context on this surface → emote-only ack
+ try {
+ const res = await fetch('/api/tts/speak', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ text: ackLine(agentNameFromAgent(getAgent())), format: 'mp3' }),
+ });
+ if (!res.ok) return;
+ const buf = await res.arrayBuffer();
+ const audio = await ctx.decodeAudioData(buf.slice(0));
+ const src = ctx.createBufferSource();
+ src.buffer = audio;
+ src.connect(ctx.destination);
+ src.start();
+ } catch { /* voice is best-effort — the tip already landed and the avatar emoted */ }
+ }
+
+ // ── wiring ──────────────────────────────────────────────────────────────
+ for (const btn of bar.querySelectorAll('[data-react]')) {
+ btn.addEventListener('click', () => sendReaction(btn.dataset.react));
+ }
+ tipBtn.addEventListener('click', openTip);
+
+ // Keep every open surface for this agent in sync when a tip is confirmed
+ // anywhere (the tip modal dispatches this on the window after recording).
+ const onPatron = (e) => {
+ const d = e?.detail || {};
+ if (d.agentId === agentId && !d.local) onTip(d);
+ };
+ window.addEventListener('three:patron-support', onPatron);
+
+ return {
+ // Forward a stream `reaction` event: { bursts:[{emoji,ts}], total }.
+ onReaction(payload) {
+ if (destroyed || !payload) return;
+ const bursts = Array.isArray(payload.bursts) ? payload.bursts : [];
+ for (const b of bursts) if (b?.emoji) overlay.burst(b.emoji, 1);
+ if (Number.isFinite(payload.total)) setCount(payload.total);
+ },
+ onTip,
+ setConnected(connected) {
+ bar.classList.toggle('connecting', !connected);
+ },
+ destroy() {
+ destroyed = true;
+ window.removeEventListener('three:patron-support', onPatron);
+ clearTimeout(cueTimer);
+ overlay.destroy();
+ bar.remove();
+ },
+ };
+}
+
+function agentNameFromAgent(agent) {
+ return (agent && (agent.name || agent.agentName)) || 'Agent';
+}
+function escAttr(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+}
diff --git a/src/agent-screen-diary.js b/src/agent-screen-diary.js
new file mode 100644
index 000000000..dafcead61
--- /dev/null
+++ b/src/agent-screen-diary.js
@@ -0,0 +1,491 @@
+// agent-screen-diary.js — the Agent Memory Diary panel for /agent-screen.
+//
+// At the end of its day the agent opens its real memory and reflects: it reads
+// back the day's most salient memories and the people/coins/topics it keeps
+// returning to, narrates a short first-person diary entry in its own TTS voice,
+// and lights up a live memory graph node-by-node as it speaks. Nothing is
+// invented — every word, node and chip originates from the agent's persistent
+// memory (api/agent-reflect-digest → real agent_memories + the mined entity
+// graph; the LLM only summarizes those rows).
+//
+// Self-contained on purpose (the agent-screen.js host is heavily co-edited):
+// • builds its own DOM into the panel body,
+// • owns its TTS + RMS lip-sync (driven through the shared Avatar Cam head via
+// getAvatar(); its tick() is installed into the webcam render loop),
+// • opens its own lightweight SSE client to refresh when a new high-salience
+// action lands, and
+// • coordinates with the Newsroom Anchor through pauseOtherNarration() so the
+// two never talk over each other.
+
+import { AgentMemoryGraph } from './agent-memory-graph.js';
+import { AvatarMouthTarget } from './voice/avatar-morph-target.js';
+import { createAgentScreenClient } from './shared/agent-screen-client.js';
+
+const DIARY_VOICE = 'nova';
+const LS_MUTE_KEY = 'asc_diary_muted';
+// Actions whose arrival is worth re-reading the diary for (high-signal).
+const REFRESH_TYPES = new Set(['trade', 'analysis']);
+const REFRESH_DEBOUNCE_MS = 8000;
+
+// One shared AudioContext for the RMS analyser path — browsers cap live contexts.
+let _audioCtx = null;
+function audioContext() {
+ if (!_audioCtx) {
+ const Ctx = window.AudioContext || window.webkitAudioContext;
+ if (Ctx) _audioCtx = new Ctx();
+ }
+ return _audioCtx;
+}
+
+function esc(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+}
+
+function startOfDayMs() {
+ const d = new Date();
+ d.setHours(0, 0, 0, 0);
+ return d.getTime();
+}
+
+const KIND_GLYPH = { mint: '◎', ticker: '◎', person: '☻', agent: '☻', wallet: '⬡', strategy: '✦', topic: '#' };
+
+/**
+ * @param {object} opts
+ * @param {string} opts.agentId
+ * @param {HTMLElement} opts.body panel body to render into
+ * @param {() => any} opts.getAvatar returns the Avatar Cam root (or null)
+ * @param {() => void} [opts.pauseOtherNarration] called before the diary speaks
+ */
+export function createDiaryPanel({ agentId, body, getAvatar, pauseOtherNarration }) {
+ const mouthTarget = new AvatarMouthTarget();
+ let boundAvatar = null;
+
+ let muted = readMutePref();
+ let digest = null;
+ let graph = null;
+ let state = 'idle'; // 'idle' | 'loading' | 'ready' | 'empty' | 'error' | 'locked'
+ let loadedOnce = false;
+
+ // Narration state.
+ let audioEl = null;
+ let analyser = null;
+ let analyserData = null;
+ let speaking = false;
+ let speakToken = 0;
+ let revealRaf = null;
+ let revealStart = 0;
+ const litEntities = new Set();
+
+ let refreshTimer = null;
+ let sse = null;
+
+ // ── DOM ──────────────────────────────────────────────────────────────────
+ body.classList.add('asc-diary-body');
+ body.innerHTML = `
+ <div class="asc-diary">
+ <div class="asc-diary-tools">
+ <button class="asc-diary-btn asc-diary-narrate" data-act="narrate" title="Narrate today's diary" disabled>
+ <span class="asc-diary-narrate-ic">▶</span><span class="asc-diary-narrate-lbl">Narrate</span>
+ </button>
+ <button class="asc-diary-btn asc-diary-mute" data-act="mute" title="Mute narration" aria-pressed="false">🔊</button>
+ <span class="asc-diary-when" id="asc-diary-when"></span>
+ <button class="asc-diary-btn asc-diary-refresh" data-act="refresh" title="Refresh reflection" aria-label="Refresh">↻</button>
+ </div>
+ <div class="asc-diary-counts" id="asc-diary-counts" hidden></div>
+ <p class="asc-diary-text" id="asc-diary-text" aria-live="polite"></p>
+ <div class="asc-diary-graph-wrap">
+ <canvas class="asc-diary-graph" id="asc-diary-graph"></canvas>
+ </div>
+ <div class="asc-diary-entities" id="asc-diary-entities"></div>
+ <div class="asc-diary-overlay" id="asc-diary-overlay" hidden></div>
+ </div>
+ `;
+
+ const els = {
+ narrate: body.querySelector('[data-act="narrate"]'),
+ mute: body.querySelector('[data-act="mute"]'),
+ refresh: body.querySelector('[data-act="refresh"]'),
+ when: body.querySelector('#asc-diary-when'),
+ counts: body.querySelector('#asc-diary-counts'),
+ text: body.querySelector('#asc-diary-text'),
+ canvas: body.querySelector('#asc-diary-graph'),
+ entities: body.querySelector('#asc-diary-entities'),
+ overlay: body.querySelector('#asc-diary-overlay'),
+ };
+
+ graph = new AgentMemoryGraph(els.canvas, {
+ onNodeClick: (node) => {
+ const ent = (digest?.entities || []).find((e) => e.id === node.id);
+ if (ent?.href) window.location.href = ent.href;
+ },
+ });
+
+ els.narrate.addEventListener('click', () => {
+ if (speaking) stopNarration();
+ else narrate({ userGesture: true });
+ });
+ els.mute.addEventListener('click', toggleMute);
+ els.refresh.addEventListener('click', () => load({ force: true }));
+ setMuteUi();
+
+ // ── state rendering ────────────────────────────────────────────────────────
+ function setOverlay(html) {
+ if (!html) { els.overlay.hidden = true; els.overlay.innerHTML = ''; return; }
+ els.overlay.hidden = false;
+ els.overlay.innerHTML = html;
+ const retry = els.overlay.querySelector('[data-act="retry"]');
+ if (retry) retry.addEventListener('click', () => load({ force: true }));
+ }
+
+ function showLoading() {
+ state = 'loading';
+ els.narrate.disabled = true;
+ els.counts.hidden = true;
+ els.text.textContent = '';
+ els.entities.innerHTML = '';
+ setOverlay(`
+ <div class="asc-diary-skel">
+ <span class="asc-diary-skel-line"></span>
+ <span class="asc-diary-skel-line"></span>
+ <span class="asc-diary-skel-line short"></span>
+ </div>
+ `);
+ }
+
+ function showEmpty() {
+ state = 'empty';
+ els.narrate.disabled = true;
+ els.counts.hidden = true;
+ els.text.textContent = '';
+ els.entities.innerHTML = '';
+ // A single seed node so the graph isn't a void.
+ graph.setData({ nodes: [{ id: 'seed', kind: 'topic', label: digest?.agentName || 'today', mentions: 1, salience: 0.5 }], edges: [] });
+ graph.resize();
+ setOverlay(`
+ <div class="asc-diary-msg">
+ <strong>No memories yet today.</strong>
+ <span>Give this agent a task below and watch its diary fill in as it works and remembers.</span>
+ <button class="asc-diary-link" data-act="focus-task">Give it a task ↓</button>
+ </div>
+ `);
+ const focus = els.overlay.querySelector('[data-act="focus-task"]');
+ if (focus) focus.addEventListener('click', () => document.getElementById('asc-task-input')?.focus());
+ }
+
+ function showError(msg, { locked = false } = {}) {
+ state = locked ? 'locked' : 'error';
+ els.narrate.disabled = true;
+ els.counts.hidden = true;
+ setOverlay(`
+ <div class="asc-diary-msg">
+ <strong>${esc(locked ? 'Owner only' : 'Couldn’t load today’s reflection')}</strong>
+ <span>${esc(msg || 'Something went wrong reading the memory.')}</span>
+ ${locked ? '' : '<button class="asc-diary-link" data-act="retry">Retry</button>'}
+ </div>
+ `);
+ }
+
+ function renderCounts(counts) {
+ const chips = [
+ { k: 'learned', label: 'learned', v: counts.learned },
+ { k: 'decided', label: 'decided', v: counts.decided },
+ { k: 'interacted', label: 'connected', v: counts.interacted },
+ ];
+ els.counts.innerHTML = chips.map((c) => `
+ <span class="asc-diary-count asc-diary-count--${c.k}">
+ <span class="asc-diary-count-v">${c.v}</span>
+ <span class="asc-diary-count-l">${c.label}</span>
+ </span>
+ `).join('');
+ els.counts.hidden = false;
+ }
+
+ function renderEntities(entities) {
+ if (!entities.length) { els.entities.innerHTML = ''; return; }
+ els.entities.innerHTML = entities.map((e) => {
+ const glyph = KIND_GLYPH[e.kind] || '#';
+ const inner = `<span class="asc-diary-chip-ic">${glyph}</span><span class="asc-diary-chip-lbl">${esc(e.label)}</span><span class="asc-diary-chip-n">${e.mentions}</span>`;
+ const title = `${esc(e.label)} — ${esc(e.kind)}, mentioned ${e.mentions}×`;
+ if (e.href) {
+ return `<a class="asc-diary-chip asc-diary-chip--link" href="${esc(e.href)}" data-eid="${esc(e.id)}" title="${title}">${inner}</a>`;
+ }
+ return `<span class="asc-diary-chip" data-eid="${esc(e.id)}" title="${title}">${inner}</span>`;
+ }).join('');
+ // Hovering a chip pulses its graph node.
+ els.entities.querySelectorAll('[data-eid]').forEach((chip) => {
+ chip.addEventListener('mouseenter', () => graph.light(chip.dataset.eid));
+ });
+ }
+
+ function render(d) {
+ digest = d;
+ state = 'ready';
+ setOverlay(null);
+ const when = new Date(d.since);
+ els.when.textContent = `since ${when.toLocaleDateString(undefined, { month: 'short', day: 'numeric' })}`;
+ renderCounts(d.counts);
+ renderEntities(d.entities);
+ graph.setData({ nodes: graphNodes(d), edges: [] });
+ graph.resize();
+ graph.start();
+ els.narrate.disabled = !d.diaryText;
+ // Show the full text immediately (readable without audio); narration will
+ // re-reveal it in step with the voice.
+ els.text.textContent = d.diaryText || '';
+ }
+
+ // The digest returns shaped entities (id/kind/label/mentions); rebuild light
+ // graph nodes from them. Edges aren't shipped in the digest, so co-occurrence
+ // is implied by shared rendering — nodes still rank + glow by mentions.
+ function graphNodes(d) {
+ return (d.entities || []).map((e) => ({
+ id: e.id, kind: e.kind, label: e.label, mentions: e.mentions, salience: e.salience,
+ }));
+ }
+
+ // ── load ───────────────────────────────────────────────────────────────────
+ let inflight = null;
+ async function load({ force = false } = {}) {
+ if (inflight && !force) return inflight;
+ if (state === 'loading') return inflight;
+ loadedOnce = true;
+ showLoading();
+ const since = startOfDayMs();
+ inflight = (async () => {
+ try {
+ const r = await fetch(`/api/agent-reflect-digest?agentId=${encodeURIComponent(agentId)}&since=${since}`, {
+ credentials: 'include',
+ });
+ if (r.status === 401) { showError('Sign in as this agent’s owner to read its diary.', { locked: true }); return; }
+ if (r.status === 403) { showError('This diary belongs to another owner.', { locked: true }); return; }
+ if (!r.ok) { showError(`Reflection failed (${r.status}).`); return; }
+ const d = await r.json();
+ if (!d || !d.highlights?.length) { showEmpty(); return; }
+ render(d);
+ } catch (err) {
+ console.warn('[diary] load failed:', err?.message);
+ showError('Check your connection and try again.');
+ } finally {
+ inflight = null;
+ }
+ })();
+ return inflight;
+ }
+
+ // ── narration (TTS + RMS lip-sync through the Avatar Cam) ───────────────────
+ function ensureAvatarBound() {
+ const root = getAvatar?.();
+ if (root && root !== boundAvatar) { boundAvatar = root; mouthTarget.attach(root); }
+ return boundAvatar;
+ }
+
+ function stopNarration() {
+ speakToken++;
+ speaking = false;
+ if (revealRaf) { cancelAnimationFrame(revealRaf); revealRaf = null; }
+ if (audioEl) {
+ try { audioEl.pause(); } catch { /* */ }
+ if (audioEl.src?.startsWith('blob:')) { try { URL.revokeObjectURL(audioEl.src); } catch { /* */ } }
+ audioEl = null;
+ }
+ analyser = null;
+ analyserData = null;
+ mouthTarget.setMouthShape({ open: 0 });
+ setNarrateUi(false);
+ // Restore the full text in case a reveal was mid-flight.
+ if (digest?.diaryText && els.text.textContent !== digest.diaryText) els.text.textContent = digest.diaryText;
+ }
+
+ async function narrate({ userGesture = false } = {}) {
+ const text = digest?.diaryText;
+ if (!text || state !== 'ready') return;
+ stopNarration();
+ if (muted && !userGesture) { return; } // silent typed reveal handled by render()
+ pauseOtherNarration?.();
+ const myToken = ++speakToken;
+ litEntities.clear();
+ setNarrateUi(true);
+ speaking = true;
+
+ // TTS → audio bytes; lip-sync from real RMS amplitude.
+ let blob = null;
+ try {
+ const r = await fetch('/api/tts/speak', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ text, voice: DIARY_VOICE, format: 'mp3' }),
+ });
+ if (!r.ok) throw new Error(`tts ${r.status}`);
+ blob = await r.blob();
+ } catch {
+ // No audio — fall back to a silent typed reveal so the panel never blocks.
+ if (myToken !== speakToken) return;
+ runReveal({ durationMs: Math.min(16000, Math.max(4000, text.length * 45)), audio: null });
+ return;
+ }
+ if (myToken !== speakToken) return;
+
+ audioEl = new Audio();
+ audioEl.src = URL.createObjectURL(blob);
+ audioEl.muted = false;
+ const ctx = audioContext();
+ if (ctx) {
+ try {
+ if (ctx.state === 'suspended') await ctx.resume();
+ const src = ctx.createMediaElementSource(audioEl);
+ analyser = ctx.createAnalyser();
+ analyser.fftSize = 1024;
+ analyser.smoothingTimeConstant = 0.5;
+ src.connect(analyser);
+ analyser.connect(ctx.destination);
+ analyserData = new Uint8Array(analyser.fftSize);
+ } catch { analyser = null; }
+ }
+
+ const onEnd = () => {
+ if (myToken !== speakToken) return;
+ speaking = false;
+ mouthTarget.setMouthShape({ open: 0 });
+ setNarrateUi(false);
+ els.text.textContent = text; // ensure fully shown
+ };
+ audioEl.addEventListener('ended', onEnd, { once: true });
+ audioEl.addEventListener('error', onEnd, { once: true });
+
+ try {
+ await audioEl.play();
+ } catch {
+ // Autoplay blocked — keep text visible, reset to a Play affordance.
+ if (myToken === speakToken) { speaking = false; setNarrateUi(false); els.text.textContent = text; }
+ return;
+ }
+ runReveal({ durationMs: null, audio: audioEl });
+ }
+
+ // Reveal the diary text in step with the voice (or a fixed cadence when
+ // silent), lighting each entity's graph node as its name is spoken.
+ function runReveal({ durationMs, audio }) {
+ const text = digest?.diaryText || '';
+ const lower = text.toLowerCase();
+ const entities = digest?.entities || [];
+ revealStart = (typeof performance !== 'undefined' ? performance.now() : Date.now());
+ els.text.textContent = '';
+ const step = () => {
+ revealRaf = requestAnimationFrame(step);
+ let progress;
+ if (audio && audio.duration && isFinite(audio.duration)) {
+ progress = audio.duration ? audio.currentTime / audio.duration : 1;
+ } else {
+ const now = (typeof performance !== 'undefined' ? performance.now() : Date.now());
+ progress = durationMs ? (now - revealStart) / durationMs : 1;
+ }
+ progress = Math.max(0, Math.min(1, progress));
+ const n = Math.floor(text.length * progress);
+ const shown = text.slice(0, n);
+ els.text.textContent = shown;
+ // Light entities whose label has now been spoken.
+ const shownLower = shown.toLowerCase();
+ for (const e of entities) {
+ if (litEntities.has(e.id)) continue;
+ if (e.label && shownLower.includes(e.label.toLowerCase())) {
+ litEntities.add(e.id);
+ graph.light(e.id);
+ }
+ }
+ if (progress >= 1 && !audio) {
+ cancelAnimationFrame(revealRaf); revealRaf = null;
+ els.text.textContent = text;
+ }
+ };
+ revealRaf = requestAnimationFrame(step);
+ }
+
+ function setNarrateUi(on) {
+ els.narrate.classList.toggle('asc-diary-narrate--on', on);
+ const ic = els.narrate.querySelector('.asc-diary-narrate-ic');
+ const lbl = els.narrate.querySelector('.asc-diary-narrate-lbl');
+ if (ic) ic.textContent = on ? '⏹' : '▶';
+ if (lbl) lbl.textContent = on ? 'Stop' : 'Narrate';
+ }
+
+ // Driven from the webcam render loop (installed as lipsyncSampler).
+ function tick() {
+ if (!speaking || !analyser || !analyserData) return;
+ ensureAvatarBound();
+ analyser.getByteTimeDomainData(analyserData);
+ let sum = 0;
+ for (let i = 0; i < analyserData.length; i++) {
+ const v = (analyserData[i] - 128) / 128;
+ sum += v * v;
+ }
+ const rms = Math.sqrt(sum / analyserData.length);
+ mouthTarget.setMouthShape({ open: Math.min(1, rms * 3.2) });
+ }
+
+ // ── mute ─────────────────────────────────────────────────────────────────
+ function readMutePref() {
+ try { const v = localStorage.getItem(LS_MUTE_KEY); return v === '1'; } catch { return false; }
+ }
+ function setMuteUi() {
+ els.mute.classList.toggle('asc-muted', muted);
+ els.mute.setAttribute('aria-pressed', String(!muted));
+ els.mute.title = muted ? 'Unmute narration' : 'Mute narration';
+ els.mute.textContent = muted ? '🔇' : '🔊';
+ }
+ function toggleMute() {
+ muted = !muted;
+ try { localStorage.setItem(LS_MUTE_KEY, muted ? '1' : '0'); } catch { /* quota */ }
+ setMuteUi();
+ if (muted && speaking) stopNarration();
+ }
+
+ // ── refresh on new high-salience activity (own SSE) ────────────────────────
+ function startStream() {
+ if (sse) return;
+ sse = createAgentScreenClient(agentId, {
+ onFrame(frame) {
+ if (!frame || !REFRESH_TYPES.has(frame.type)) return;
+ scheduleRefresh();
+ },
+ });
+ sse.connect();
+ }
+ function scheduleRefresh() {
+ if (state !== 'ready' && state !== 'empty') return;
+ if (speaking) return; // don't yank text out from under a live narration
+ clearTimeout(refreshTimer);
+ refreshTimer = setTimeout(() => load({ force: true }), REFRESH_DEBOUNCE_MS);
+ }
+
+ // ── public surface ─────────────────────────────────────────────────────────
+ // Called when the panel becomes visible (first open or un-hide).
+ function onOpen() {
+ if (graph) { graph.resize(); graph.start(); }
+ if (!loadedOnce) {
+ load().then(() => {
+ startStream();
+ // A user opening the panel is a real gesture → narrate once, unless muted.
+ if (state === 'ready' && !muted) narrate({ userGesture: true });
+ });
+ }
+ }
+
+ function onResize() { graph?.resize(); }
+
+ // Optional external nudge (host may forward frames); the own SSE covers the
+ // default path, so this is purely additive.
+ function notifyActivity(frame) {
+ if (frame && REFRESH_TYPES.has(frame.type)) scheduleRefresh();
+ }
+
+ function destroy() {
+ stopNarration();
+ clearTimeout(refreshTimer);
+ try { sse?.disconnect(); } catch { /* */ }
+ graph?.dispose();
+ mouthTarget.dispose();
+ }
+
+ return { tick, onOpen, onResize, refresh: () => load({ force: true }), notifyActivity, destroy };
+}
diff --git a/src/agent-screen-pnl-hud.js b/src/agent-screen-pnl-hud.js
index b322ef100..08445e841 100644
--- a/src/agent-screen-pnl-hud.js
+++ b/src/agent-screen-pnl-hud.js
@@ -324,6 +324,10 @@ export function createPnlHud({ bodyEl, agentId, network = 'mainnet', onNetWorth
destroyed = true;
if (pollTimer) { clearInterval(pollTimer); pollTimer = null; }
if (unsubscribe) { unsubscribe(); unsubscribe = null; }
+ if (onVisibility && typeof document !== 'undefined') {
+ document.removeEventListener('visibilitychange', onVisibility);
+ onVisibility = null;
+ }
}
return { start, destroy, setActive, refresh };
diff --git a/src/agent-screen-stage.js b/src/agent-screen-stage.js
index 5bba30ea7..bb13c1180 100644
--- a/src/agent-screen-stage.js
+++ b/src/agent-screen-stage.js
@@ -353,7 +353,8 @@ export class StageShow {
const name = BEAT_EMOTE[kind];
if (!mgr || !name || !mgr.supportsCanonicalClips?.()) return;
// Upper-body overlay so the legs keep idling; one-shot, settles back to idle.
- mgr.playOverlay?.(name, { loop: false, upperBodyOnly: true, crossfade: 0.22 }).catch?.(() => {});
+ const p = mgr.playOverlay?.(name, { loop: false, upperBodyOnly: true, crossfade: 0.22 });
+ if (p && typeof p.catch === 'function') p.catch(() => { /* clip missing on this rig — no-op */ });
}
// ── tips: real, settled $THREE off the show ledger ─────────────────────────
diff --git a/src/agent-screen.js b/src/agent-screen.js
index 4dd7ef7c1..12917abe5 100644
--- a/src/agent-screen.js
+++ b/src/agent-screen.js
@@ -37,16 +37,19 @@ import { StageShow } from './agent-screen-stage.js';
import { createAgentScreenClient } from './shared/agent-screen-client.js';
import { handleTourFrame } from './agent-screen-tour.js';
import { buildRunCommand, buildRunCommandHtml, RUNTIME_LABELS } from './agent-screen-runcmd.js';
+import { createNewsroomAnchor } from './agent-screen-anchor.js';
import { createTreasuryCockpit } from './agent-screen-treasury.js';
import { MirrorPanel } from './agent-screen-mirror.js';
import { createHireVisualizer } from './agent-screen-hire.js';
import {
parsePnlDelta, accumulatePnl, emptyPnlState, unrealizedTotalUsd, emoteForExit, formatSol, formatUsd,
} from './shared/trade-pnl.js';
+import { classify, colorHex } from './activity-cinema.js';
import {
parseLaunchCommand, validateLaunchParams, narrate as narrateLaunch,
renderLaunchHud, truncMid,
} from './launch-director.js';
+import { parseGrindCommand } from './vanity-grind-director.js';
import { agentAvatarGlb } from './shared/agent-3d.js';
import { getMeshoptDecoder } from './viewer/internal.js';
import { ScreenshotModal } from './components/screenshot-modal.js';
@@ -57,6 +60,7 @@ import { createAmbientWorld, phaseLabel } from './agent-screen-world.js';
import { createDjScript } from './agent-screen-dj.js';
import { LipSyncAnalyser } from './lip-sync-analyser.js';
import { createVisemeDriver } from './runtime/lipsync.js';
+import { classifyTaskInput, ensureSessionId } from './shared/ask-routing.js';
// One meshopt-aware loader, built once. Optimized agent avatars ship with
// EXT_meshopt_compression, so the decoder must be wired before the loader can
@@ -757,7 +761,7 @@ async function boot(id) {
<span class="asc-panel-title">Live Hire</span>
<div class="asc-panel-btns">
<button class="asc-panel-btn" data-act="min" title="Minimize">▁</button>
- <button class="asc-panel-btn" data-act="close" title="Hide (H)">✕</button>
+ <button class="asc-panel-btn" data-act="close" title="Hide (R)">✕</button>
</div>
</div>
<div class="asc-panel-body" id="asc-hire-body"></div>
@@ -803,7 +807,7 @@ async function boot(id) {
class="asc-task-input"
id="asc-task-input"
type="text"
- placeholder="Give your agent a task… (research, browse, monitor anything)"
+ placeholder="Give your agent a task… (research, browse, or: launch a coin named … ticker … uri https://…)"
maxlength="1000"
spellcheck="false"
>
@@ -814,6 +818,26 @@ async function boot(id) {
</button>
</form>
<div class="asc-task-status" id="asc-task-status"></div>
+ <!-- Live Avatar Forge: type a prompt → watch a 3D avatar get built, rigged, animated -->
+ <form class="asc-forge-form" id="asc-forge-form" autocomplete="off">
+ <div class="asc-forge-icon" title="Free TRELLIS text→3D">✦</div>
+ <input
+ class="asc-forge-input"
+ id="asc-forge-input"
+ type="text"
+ placeholder="Forge an avatar — describe it (e.g. a glossy white robot mascot)"
+ maxlength="1000"
+ spellcheck="false"
+ >
+ <button class="asc-forge-btn" id="asc-forge-btn" type="submit" title="Forge a 3D avatar — free">
+ <span class="asc-forge-btn-label">Forge</span>
+ <span class="asc-forge-btn-spin" aria-hidden="true"></span>
+ </button>
+ </form>
+ <div class="asc-forge-result" id="asc-forge-result" hidden>
+ <a class="asc-forge-view" id="asc-forge-view" target="_blank" rel="noopener">Open in viewer ↗</a>
+ <button class="asc-forge-use" id="asc-forge-use" type="button">Use as agent avatar</button>
+ </div>
</div>
<!-- Zen exit hint -->
@@ -836,8 +860,14 @@ async function boot(id) {
// ── resolve agent metadata ─────────────────────────────────────────────
let agentName = 'Agent';
let avatarGlbUrl = null;
+ // Q&A concierge state: whether this viewer owns the agent (unlocks the
+ // queue-a-task mode) and the agent's configured TTS voice for spoken answers.
+ let isOwner = false;
+ let agentVoice = 'nova';
try {
- const res = await fetch(`/api/agents/${encodeURIComponent(id)}`);
+ // credentials:'include' so the server can tell whether this viewer owns the
+ // agent — owners get the ask⇄task toggle; everyone else can still ask.
+ const res = await fetch(`/api/agents/${encodeURIComponent(id)}`, { credentials: 'include' });
if (res.ok) {
const j = await res.json();
const agent = j.agent || j;
@@ -848,12 +878,17 @@ async function boot(id) {
backEl.href = `/agents/${id}`;
agentLinkEl.href = `/agents/${id}`;
agentLinkEl.innerHTML = `${esc(agentName)} →`;
+ isOwner = !!agent.is_owner;
+ if (agent.voice_id) agentVoice = agent.voice_id;
try {
avatarGlbUrl = await agentAvatarGlb(agent);
} catch { /* fall through to default */ }
}
} catch { /* non-fatal */ }
+ // A per-tab Q&A session id gives follow-up questions memory continuity.
+ const qaSessionId = ensureSessionId();
+
// ── avatar webcam ──────────────────────────────────────────────────────
const webcamRenderer = new WebGLRenderer({ antialias: true, alpha: true });
webcamRenderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
@@ -898,6 +933,19 @@ async function boot(id) {
let hostLookT = 0;
let lipsyncSampler = null;
+ // ── Pose Studio Live ─────────────────────────────────────────────────────
+ // A viewer calls out a pose ("wave hello", "take a bow", "warrior stance")
+ // and the live avatar performs it: animated emotes drive a real canonical
+ // clip through the AnimationManager; static poses tween the joint-rotation
+ // map onto the same canonical bones the /pose studio uses, then settle back
+ // to the live idle. Universal across rigs — no allowlist, never a T-pose.
+ let poseRig = null; // canonical rig over the loaded model (null ⇒ not skeleton-driveable)
+ let poseDriver = null; // active static-pose tween, or null
+ let poseClipSettleAt = 0; // perf-clock ms to settle a looping emote back to idle (0 ⇒ none)
+ let lastPoseAt = 0; // debounce: drop requests that would stomp a transition
+ let performPose = null; // assigned once the avatar + rig are mounted
+ const _poseTmpQuat = new Quaternion();
+
function sizeWebcam() {
if (!webcamCanvas) return;
const bw = webcamBezel.clientWidth || 256;
@@ -925,6 +973,10 @@ async function boot(id) {
// falls back to its authored bind pose (supportsCanonicalClips() gate).
webcamAnimManager = new AnimationManager();
webcamAnimManager.attach(model, { avatarUrl: glbUrl || '/avatars/default.glb' });
+ // Canonical pose-rig over the SAME model so viewer-requested static poses
+ // land on exactly the bones /pose drives. null ⇒ not skeleton-driveable
+ // (poses then no-op gracefully — never a forced bind-pose T-pose).
+ poseRig = makeGltfRig(model);
if (webcamAnimManager.supportsCanonicalClips()) {
try {
const manifest = await fetch('/animations/manifest.json', { cache: 'force-cache' })
@@ -936,7 +988,15 @@ async function boot(id) {
// avatar can celebrate a win, slump on a loss, and wave on session
// start. The one-shots load lazily on first playOnce — only `idle`
// is forced up front so the head is alive immediately.
- const REACTION_CLIPS = ['idle', 'celebrate', 'defeated', 'wave'];
+ const REACTION_CLIPS = [
+ 'idle', 'celebrate', 'defeated', 'wave',
+ // Live Pose Studio emotes — load lazily on first viewer request.
+ 'pray', 'dance', 'kiss', 'taunt', 'jump', 'facepalm',
+ 'av-cheering', 'av-brag-claps', 'av-arm-flex',
+ // Q&A concierge: a "thinking" waiting pose while the answer streams
+ // and a "talking" upper-body gesture overlaid while the agent speaks.
+ 'av-waiting', 'av-vtubing',
+ ];
const defs = manifest.filter((d) => REACTION_CLIPS.includes(d.name));
const idleDef = defs.filter((d) => d.name === 'idle');
if (defs.length) {
@@ -984,6 +1044,89 @@ async function boot(id) {
}
}
+ // ── Live Avatar Forge: swap the cam to a forged GLB ─────────────────────
+ // Dispose the current model, load the forged GLB, retarget the canonical clip
+ // library, then play idle → wave. Returns { animated } — false for a
+ // non-riggable GLB (shown static, never a forced T-pose), gated on
+ // AnimationManager.supportsCanonicalClips().
+ function disposeForgeMaterial(m) {
+ for (const k in m) { const v = m[k]; if (v && v.isTexture) v.dispose?.(); }
+ m.dispose?.();
+ }
+ function disposeForgeObject(rootObj) {
+ rootObj.traverse((o) => {
+ if (o.geometry) o.geometry.dispose?.();
+ const m = o.material;
+ if (Array.isArray(m)) m.forEach(disposeForgeMaterial);
+ else if (m) disposeForgeMaterial(m);
+ });
+ }
+ async function swapWebcamAvatar(glbUrl, { wave = false } = {}) {
+ const loader = await getAvatarLoader();
+ const gltf = await loader.loadAsync(glbUrl);
+ const model = cloneSkinnedScene(gltf.scene);
+
+ webcamAnimManager?.detach();
+ webcamAnimManager = null;
+ if (webcamAvatar) {
+ webcamScene.remove(webcamAvatar);
+ disposeForgeObject(webcamAvatar);
+ }
+ webcamAvatar = model;
+ webcamScene.add(model);
+
+ const box = new Box3().setFromObject(model);
+ const h = box.max.y || 1.6;
+ webcamCamera.position.set(0, h - 0.12, 0.72);
+ webcamCamera.lookAt(0, h - 0.18, 0);
+
+ webcamAnimManager = new AnimationManager();
+ webcamAnimManager.attach(model, { avatarUrl: glbUrl });
+ let animated = false;
+ if (webcamAnimManager.supportsCanonicalClips()) {
+ try {
+ const manifest = await fetch('/animations/manifest.json', { cache: 'force-cache' })
+ .then((r) => { if (!r.ok) throw new Error(`HTTP ${r.status} fetching animation manifest`); return r.json(); });
+ const defs = manifest.filter((d) => ['idle', 'wave'].includes(d.name));
+ if (defs.length) {
+ webcamAnimManager.setAnimationDefs(defs);
+ await webcamAnimManager.ensureLoaded('idle');
+ webcamAnimManager.play('idle');
+ animated = true;
+ if (wave) {
+ await webcamAnimManager.ensureLoaded('wave').catch(() => {});
+ webcamAnimManager.playOnce('wave', { settleTo: 'idle' }).catch(() => {});
+ }
+ }
+ } catch (err) {
+ console.warn('[agent-screen] forged clip load failed:', err);
+ }
+ }
+
+ // First forge before any avatar mounted (default mount failed): bring the
+ // cam canvas + a minimal render tick online so the forged model is visible.
+ if (!webcamCanvas) {
+ webcamCanvas = webcamRenderer.domElement;
+ webcamCanvas.style.cssText = 'width:100%;height:100%;object-fit:cover;';
+ webcamBezel.appendChild(webcamCanvas);
+ }
+ sizeWebcam();
+ if (!webcamRafId) {
+ let last = 0;
+ const tick = (t) => {
+ webcamRafId = requestAnimationFrame(tick);
+ const dt = Math.min((t - last) / 1000, 0.1);
+ last = t;
+ webcamAnimManager?.update(dt);
+ webcamRenderer.render(webcamScene, webcamCamera);
+ };
+ webcamRafId = requestAnimationFrame(tick);
+ }
+ webcamIdle.style.display = 'none';
+ webcamBadge.style.display = 'flex';
+ return { animated };
+ }
+
mountAvatarWebcam(avatarGlbUrl || '/avatars/default.glb');
// ── newsroom anchor (lower-third + spoken bulletins + lip-sync) ─────────
@@ -1331,6 +1474,7 @@ async function boot(id) {
let treasuryCockpit = null; // set once the Treasury panel mounts (below)
let mirrorPanel = null; // set once the Mirror panel mounts (below)
let pnlHud = null; // set once the Portfolio HUD panel mounts (below)
+ let hireViz = null; // set once the Live Hire panel mounts (below)
const client = createAgentScreenClient(id, {
onOpen({ agentName: n }) {
if (n) { agentNameEl.textContent = n; agentName = n; webcamName.textContent = n; }
@@ -1342,6 +1486,9 @@ async function boot(id) {
if (frame.data) renderFrame(frame);
handleTourFrame(frame);
if (frame.activity) { addLogEntry(frame); treasuryCockpit?.observeLog([frame]); }
+ const forgeHit = parseForgeFrame(frame);
+ if (forgeHit) loadForgedAvatar(forgeHit);
+ if (frame.meta?.kind === 'a2a_hire') hireViz?.ingest(frame.meta, { live: true });
if (frame.type === 'trade') {
const delta = ingestTrade(frame);
if (delta) emoteForTrade(delta);
@@ -1361,6 +1508,11 @@ async function boot(id) {
// don't emote — these are history, not a fresh fill happening on camera.
entries.forEach((e) => { addLogEntry(e); ingestTrade(e); });
treasuryCockpit?.observeLog(entries);
+ const lastForge = [...entries].reverse().find((e) => parseForgeFrame(e));
+ if (lastForge) loadForgedAvatar(parseForgeFrame(lastForge));
+ // Replay any hire phases in order so a reconnect re-syncs to the latest
+ // phase (no coin animation — this is history, not a fresh settle).
+ entries.forEach((e) => { if (e.meta?.kind === 'a2a_hire') hireViz?.ingest(e.meta, { live: false }); });
},
onDark() { setDark(); },
onError() {
@@ -1371,6 +1523,169 @@ async function boot(id) {
client.connect();
+ // ── sentiment heatmap (live 3D market field + narration) ─────────────────
+ // A glowing 3D field of tokens — $THREE pinned at the centre — pulsing by 24h
+ // momentum, with the agent calling out the movers. Real data via
+ // /api/intel/heatmap; real narration via /api/brain/chat.
+ const heatmapCanvas = document.getElementById('asc-heatmap-canvas');
+ const hmOverlay = document.getElementById('asc-hm-overlay');
+ const hmStale = document.getElementById('asc-hm-stale');
+ const hmTooltip = document.getElementById('asc-hm-tooltip');
+ const hmMeta = document.getElementById('asc-hm-meta');
+ let heatmap = null;
+ let heatmapPoller = null;
+ let hmHasData = false;
+ let hmCanPush = true; // disabled after a 401/403 (viewer, not owner)
+ let lastNarrationAt = 0;
+ let lastPushAt = 0;
+ const NARRATION_COOLDOWN_MS = 60_000;
+ const PUSH_COOLDOWN_MS = 18_000;
+
+ function sizeHeatmap() { heatmap?.resize(); }
+
+ function showHmTooltip(token, x, y) {
+ if (!token) { hmTooltip.hidden = true; return; }
+ const pct = (n) => (n == null ? '—' : `${n >= 0 ? '+' : ''}${Number(n).toFixed(1)}%`);
+ const vol = token.volume24h ? `$${Intl.NumberFormat('en', { notation: 'compact' }).format(token.volume24h)}` : '—';
+ const sent = token.sentiment && Number.isFinite(token.sentiment.score)
+ ? `<div class="asc-hm-tip-row"><span>sentiment</span><b>${token.sentiment.posPct}% bullish</b></div>` : '';
+ hmTooltip.innerHTML = `
+ <div class="asc-hm-tip-head">${esc(token.label)}${token.featured ? ' <span class="asc-hm-tip-anchor">$THREE</span>' : ''}</div>
+ <div class="asc-hm-tip-row"><span>momentum</span><b>${pct(token.change24h)}</b></div>
+ <div class="asc-hm-tip-row"><span>24h vol</span><b>${vol}</b></div>
+ ${sent}`;
+ hmTooltip.hidden = false;
+ const r = heatmapCanvas.getBoundingClientRect();
+ let lx = Math.min(x - r.left + 14, r.width - hmTooltip.offsetWidth - 8);
+ let ly = Math.min(y - r.top + 14, r.height - hmTooltip.offsetHeight - 8);
+ hmTooltip.style.left = `${Math.max(6, lx)}px`;
+ hmTooltip.style.top = `${Math.max(6, ly)}px`;
+ }
+
+ function startHeatmap() {
+ if (heatmap || !heatmapCanvas) return;
+ heatmap = new SentimentHeatmap3D(heatmapCanvas, { onHover: showHmTooltip });
+ heatmap.showLoadingLattice();
+ requestAnimationFrame(() => sizeHeatmap());
+ heatmapPoller = createHeatmapPoller({
+ onUpdate({ tokens, spikes, movers, stale }) {
+ if (!heatmap) return;
+ hmHasData = tokens.length > 0;
+ heatmap.setData(tokens);
+ hmOverlay.hidden = hmHasData;
+ if (tokens.length <= 1) {
+ hmOverlay.hidden = false;
+ hmOverlay.querySelector('p').textContent = 'Market quiet — watching $THREE.';
+ }
+ hmStale.hidden = !stale;
+ const climate = movers.avgMomentum > 0.08 ? 'heating' : movers.avgMomentum < -0.08 ? 'cooling' : 'mixed';
+ hmMeta.textContent = `${tokens.length} tokens · ${climate}`;
+ maybeNarrate({ spikes, movers });
+ maybePushWall(movers);
+ },
+ onError() {
+ if (!hmHasData) {
+ hmOverlay.hidden = false;
+ hmOverlay.querySelector('p').textContent = 'Market feed unavailable — retrying…';
+ } else {
+ hmStale.hidden = false;
+ }
+ },
+ });
+ heatmapPoller.start();
+ }
+
+ // Narrate movers through the brain. Anonymous viewers get the free model; the
+ // line names only $THREE and never recommends other tokens. Throttled so the
+ // log never floods.
+ async function maybeNarrate({ spikes, movers }) {
+ const now = Date.now();
+ if (now - lastNarrationAt < NARRATION_COOLDOWN_MS) return;
+ const firstRun = lastNarrationAt === 0;
+ if (!firstRun && !spikes.length) return;
+ lastNarrationAt = now;
+ const context = buildNarrationContext({ spikes, movers });
+ const system = 'You are a terse live market-sentiment narrator on a trading wall. Given a snapshot of token momentum, say ONE punchy sentence (max 22 words) calling the moment. $THREE is the featured coin and the only one you may name approvingly; never recommend, endorse, or shill any other token — refer to others only by ticker as market data. No emojis, no hashtags, no financial advice.';
+ try {
+ const line = await narrateOnce(system, context);
+ if (line) {
+ addLogEntry({ ts: Date.now(), activity: line, type: 'analysis' });
+ pushNarration(line);
+ }
+ } catch { /* narration is best-effort */ }
+ }
+
+ async function narrateOnce(system, content) {
+ const res = await fetch('/api/brain/chat', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ provider: 'gpt-oss-120b', system, messages: [{ role: 'user', content }], maxTokens: 80 }),
+ });
+ if (!res.ok || !res.body) return '';
+ const reader = res.body.getReader();
+ const dec = new TextDecoder();
+ let buf = '';
+ let out = '';
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buf += dec.decode(value, { stream: true });
+ const lines = buf.split('\n');
+ buf = lines.pop();
+ for (const l of lines) {
+ const s = l.trim();
+ if (!s.startsWith('data:')) continue;
+ const raw = s.slice(5).trim();
+ if (!raw || raw === '[DONE]') continue;
+ try { const chunk = JSON.parse(raw); if (typeof chunk === 'string') out += chunk; } catch { /* meta/first/done events */ }
+ }
+ }
+ return out.trim().replace(/^["']|["']$/g, '').slice(0, 220);
+ }
+
+ // Push the narration line to the wall (owners only). A 401/403 means this
+ // viewer doesn't own the agent — disable further pushes silently.
+ async function pushNarration(line) {
+ if (!hmCanPush) return;
+ try {
+ const res = await fetch('/api/agent-screen-push', {
+ method: 'POST', credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ agentId: id, frame: { activity: line, type: 'activity' } }),
+ });
+ if (res.status === 401 || res.status === 403) hmCanPush = false;
+ } catch { /* best-effort */ }
+ }
+
+ // Snapshot the heatmap onto the wall when the agent's screen is otherwise dark
+ // — fills a blank stream rather than overriding an active browser stream.
+ // Owners only; throttled.
+ async function maybePushWall(movers) {
+ if (!hmCanPush || !heatmap || !hmHasData) return;
+ const now = Date.now();
+ if (now - lastPushAt < PUSH_COOLDOWN_MS) return;
+ const streamLive = !liveBadgeEl.classList.contains('dark') && lastFrameAt && (now - lastFrameAt < 80_000);
+ if (streamLive) return;
+ const data = heatmap.captureFrame(720);
+ if (!data || data.length > 760_000) return;
+ lastPushAt = now;
+ const climate = movers.avgMomentum > 0.08 ? 'heating' : movers.avgMomentum < -0.08 ? 'cooling' : 'mixed';
+ try {
+ const res = await fetch('/api/agent-screen-push', {
+ method: 'POST', credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ agentId: id, frame: { data, activity: `Sentiment heatmap — market ${climate}`, type: 'analysis' } }),
+ });
+ if (res.status === 401 || res.status === 403) hmCanPush = false;
+ } catch { /* best-effort */ }
+ }
+
+ document.getElementById('asc-hm-focus')?.addEventListener('click', () => heatmap?.focusThree());
+ document.getElementById('asc-hm-retry')?.addEventListener('click', () => { hmStale.hidden = true; heatmapPoller?.refresh(); });
+
+ if (!layout.panels.heatmap.hidden) startHeatmap();
+
// Ask the on-demand pool to cast this agent and keep re-asserting while the tab
// is open, so a viewer who lands here (not just the wall) gets a real browser
// feed on demand. Status polling is kicked off by setDark() on the first poll.
@@ -1398,6 +1713,16 @@ async function boot(id) {
return;
}
+ // Vanity Grinder: "grind a wallet starting with pump" runs a real, live
+ // keyspace search streamed to this screen instead of queuing a task. The
+ // keypair is generated server-side; the secret is returned only to the owner.
+ const grindParams = parseGrindCommand(text);
+ if (grindParams) {
+ taskInput.value = '';
+ await runVanityGrind(grindParams);
+ return;
+ }
+
taskInput.disabled = true;
taskSend.disabled = true;
taskSend.classList.add('sending');
@@ -1437,6 +1762,362 @@ async function boot(id) {
}
});
+ // ── Live Avatar Forge: in-browser driver ────────────────────────────────
+ // The viewer types a prompt; we drive the FREE NVIDIA NIM (Microsoft TRELLIS)
+ // text→3D lane (POST/poll /api/forge — no payment, no key, no wallet), narrate
+ // each REAL pipeline stage, broadcast the staged frames to every viewer via
+ // screenPush, and on completion load + rig + animate the GLB in the Avatar Cam.
+ const forgeForm = document.getElementById('asc-forge-form');
+ const forgeInput = document.getElementById('asc-forge-input');
+ const forgeBtn = document.getElementById('asc-forge-btn');
+ const forgeResult = document.getElementById('asc-forge-result');
+ const forgeView = document.getElementById('asc-forge-view');
+ const forgeUse = document.getElementById('asc-forge-use');
+ const forgeQueue = [];
+ let forgeInFlight = false;
+ let lastForgedGlb = '';
+ let forgeOverlayEl = null;
+
+ function ensureForgeOverlay() {
+ if (!forgeOverlayEl) {
+ forgeOverlayEl = document.createElement('div');
+ forgeOverlayEl.className = 'asc-forge-cam-note';
+ webcamBezel.appendChild(forgeOverlayEl);
+ }
+ return forgeOverlayEl;
+ }
+ function showForgeStage(text) { const el = ensureForgeOverlay(); el.textContent = text; el.dataset.show = '1'; }
+ function hideForgeOverlay() { if (forgeOverlayEl) forgeOverlayEl.dataset.show = '0'; }
+ function forgeStatus(msg, cls = '') {
+ taskStatus.className = 'asc-task-status' + (cls ? ' ' + cls : '');
+ taskStatus.textContent = msg;
+ if (cls !== 'err' && msg) {
+ setTimeout(() => {
+ if (taskStatus.textContent === msg) { taskStatus.textContent = ''; taskStatus.className = 'asc-task-status'; }
+ }, 5000);
+ }
+ }
+ function setForgeBusy(b) {
+ forgeInFlight = b;
+ if (forgeBtn) forgeBtn.disabled = b;
+ if (forgeInput) forgeInput.disabled = b;
+ forgeBtn?.classList.toggle('forging', b);
+ }
+ async function screenPushForge(frame) {
+ try {
+ await fetch('/api/agent-screen-push', {
+ method: 'POST', credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ agentId: id, frame }),
+ });
+ } catch { /* best-effort broadcast — a non-owner viewer simply can't push */ }
+ }
+ async function pollForgeJob(jobId, narrate) {
+ const deadline = Date.now() + 180000;
+ let lastStatus = 'queued';
+ while (Date.now() < deadline) {
+ await new Promise((r) => setTimeout(r, 3000)); // real poll interval, not fake progress
+ let res;
+ try {
+ res = await fetch(`/api/forge?job=${encodeURIComponent(jobId)}`, { headers: { accept: 'application/json' } });
+ } catch { continue; }
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) { if (res.status >= 500) continue; throw new Error(data.message || `forge poll returned ${res.status}`); }
+ if (data.status && data.status !== lastStatus) { lastStatus = data.status; narrate(data); }
+ if (data.status === 'done' && data.glb_url) return data;
+ if (data.status === 'failed') throw new Error(data.error || 'generation failed');
+ }
+ throw new Error('generation timed out — try again');
+ }
+ async function loadForgedAvatar(forge, opts = {}) {
+ const fromDriver = opts.fromDriver === true;
+ if (!forge || !forge.glbUrl) return;
+ if (!fromDriver && forge.glbUrl === lastForgedGlb) return; // already on screen
+ lastForgedGlb = forge.glbUrl;
+ const viewerUrl = forge.viewerUrl || viewerLinkFor(forge.glbUrl, location.origin);
+ showForgeStage('Loading model…');
+ let result;
+ try {
+ result = await swapWebcamAvatar(forge.glbUrl, { wave: true });
+ } catch (err) {
+ console.warn('[agent-screen] forged GLB load failed:', err);
+ showForgeStage('model produced but failed to load — open in viewer');
+ if (forgeView) forgeView.href = viewerUrl;
+ if (forgeUse) forgeUse.dataset.glb = forge.glbUrl;
+ if (forgeResult) forgeResult.hidden = false;
+ return;
+ }
+ if (result.animated) hideForgeOverlay();
+ else showForgeStage('static model — no rig to animate');
+ if (forgeView) forgeView.href = viewerUrl;
+ if (forgeUse) forgeUse.dataset.glb = forge.glbUrl;
+ if (forgeResult) forgeResult.hidden = false;
+ }
+ async function driveForge(rawPrompt) {
+ const valid = validatePrompt(rawPrompt);
+ if (!valid.ok) { forgeStatus(valid.reason, 'err'); return; }
+ const clamped = clampPrompt(rawPrompt);
+ const prompt = clamped.prompt;
+ setForgeBusy(true);
+ if (forgeResult) forgeResult.hidden = true;
+ if (clamped.trimmed) forgeStatus('Prompt trimmed to the TRELLIS conditioning window', '');
+ const narrate = (state) => {
+ const line = forgeStageNarration(state);
+ addLogEntry({ ts: Date.now(), activity: line, type: 'analysis' });
+ showForgeStage(line);
+ screenPushForge({ activity: line, type: 'analysis' });
+ };
+ narrate({ status: 'submitting' });
+ try {
+ const submitRes = await fetch('/api/forge', {
+ method: 'POST', credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ prompt, tier: 'draft', backend: 'nvidia', path: 'image' }),
+ });
+ const submit = await submitRes.json().catch(() => ({}));
+ if (submitRes.status === 503) throw new Error(submit.message || 'the free 3D lane is not configured');
+ if (submitRes.status === 429) throw new Error(submit.message || 'forge lane busy — try again shortly');
+ let done = null;
+ if (submit.status === 'done' && submit.glb_url) done = submit;
+ else if (!submitRes.ok || !submit.job_id) throw new Error(submit.message || `forge returned ${submitRes.status}`);
+ else { narrate({ status: 'queued', eta_seconds: submit.eta_seconds }); done = await pollForgeJob(submit.job_id, narrate); }
+
+ const glbUrl = done.glb_url;
+ const viewerUrl = viewerLinkFor(glbUrl, location.origin);
+ lastForgedGlb = glbUrl; // ignore the SSE echo of our own final frame
+ screenPushForge(finalForgeFrame({ prompt, glbUrl, viewerUrl, tier: done.tier, backend: done.backend, durable: done.durable }));
+ await loadForgedAvatar({ glbUrl, viewerUrl, prompt }, { fromDriver: true });
+ forgeStatus('Forged — breathing in idle, then a wave', 'ok');
+ } catch (err) {
+ const msg = String(err && err.message ? err.message : err);
+ addLogEntry({ ts: Date.now(), activity: `Forge failed: ${msg}`, type: 'analysis' });
+ hideForgeOverlay();
+ if (/busy|rate|429/i.test(msg)) forgeStatus('Forge lane busy — try again shortly', 'err');
+ else if (/reject|invalid|concrete|moderat/i.test(msg)) forgeStatus('Prompt rejected — try a concrete object', 'err');
+ else forgeStatus(`Forge failed: ${msg}`, 'err');
+ } finally {
+ setForgeBusy(false);
+ const next = forgeQueue.shift();
+ if (next) driveForge(next);
+ }
+ }
+ if (forgeForm) {
+ forgeForm.addEventListener('submit', (e) => {
+ e.preventDefault();
+ const raw = forgeInput.value.trim();
+ if (!raw) { forgeInput.focus(); return; }
+ forgeInput.value = '';
+ if (forgeInFlight) { forgeQueue.push(raw); forgeStatus('Queued — one forge at a time', ''); return; }
+ driveForge(raw);
+ });
+ }
+ if (forgeUse) {
+ forgeUse.addEventListener('click', () => {
+ const glb = forgeUse.dataset.glb;
+ if (!glb) return;
+ navigator.clipboard?.writeText(glb).catch(() => {});
+ toast('Forged model URL copied — set it on your agent');
+ window.open(`/agents/${encodeURIComponent(id)}`, '_blank', 'noopener');
+ });
+ }
+
+ // ── Launch Director ───────────────────────────────────────────────────────
+ // Run a real coin launch as a narrated, staged console on this agent's screen.
+ // Every stage is a real operation; each one paints a launch-console HUD and a
+ // narration line, pushed to /api/agent-screen-push so the owner AND every
+ // remote viewer watch the same live "go live" moment. Success renders only
+ // after a real on-chain signature returns.
+ let launchInFlight = false;
+
+ // Push one HUD frame (image + narration) to the live stream. The owner and all
+ // viewers receive it back through the same SSE pipe, so we never render locally
+ // — one source of truth, no double-counting.
+ async function pushLaunchFrame({ data, activity, type = 'analysis' }) {
+ try {
+ await fetch('/api/agent-screen-push', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ agentId: id, frame: { data, activity, type } }),
+ });
+ } catch { /* a dropped frame is non-fatal — the on-chain tx is the truth */ }
+ }
+
+ function setLaunchStatus(kind, html) {
+ taskStatus.className = `asc-task-status ${kind}`;
+ taskStatus.innerHTML = html;
+ }
+
+ async function runLaunchDirector(params) {
+ if (launchInFlight) { setLaunchStatus('err', 'A launch is already in progress.'); return; }
+
+ const { ok, errors } = validateLaunchParams(params);
+ if (!ok) {
+ setLaunchStatus('err', esc(errors[0]));
+ addLogEntry({ ts: Date.now(), activity: `Launch rejected — ${errors.join(' ')}`, type: 'analysis' });
+ return;
+ }
+
+ launchInFlight = true;
+ taskInput.disabled = true;
+ taskSend.disabled = true;
+ taskSend.classList.add('sending');
+ setLaunchStatus('', `Launching ${esc(params.symbol ? `$${params.symbol}` : params.name)}…`);
+
+ const ctx = { name: params.name, symbol: params.symbol, network: params.network, solBuyIn: params.sol_buy_in };
+ const token = { name: params.name, symbol: params.symbol, imageUrl: null };
+
+ // Paint one stage: render the HUD, narrate, push.
+ const paint = async (stageKey, status = 'active') => {
+ const narration = narrateLaunch(stageKey, ctx);
+ const data = await renderLaunchHud({ params, token, stageKey, status, narration });
+ await pushLaunchFrame({ data, activity: narration, type: 'analysis' });
+ return narration;
+ };
+
+ const fail = async (stageKey, message) => {
+ const data = await renderLaunchHud({ params, token, stageKey, status: 'error', error: message });
+ await pushLaunchFrame({ data, activity: `Launch failed — ${message}`, type: 'analysis' });
+ setLaunchStatus('err', esc(message));
+ };
+
+ try {
+ // 1 ── Prepare ────────────────────────────────────────────────────────
+ await paint('prepare');
+
+ // 2 ── Metadata: read the real token metadata to assemble the card ──────
+ try {
+ const metaRes = await fetch(params.uri, { headers: { accept: 'application/json' } });
+ if (metaRes.ok) {
+ const meta = await metaRes.json().catch(() => null);
+ if (meta && typeof meta === 'object' && typeof meta.image === 'string') {
+ token.imageUrl = meta.image;
+ }
+ }
+ } catch { /* metadata read is best-effort; the URI is what lands on-chain */ }
+ try { ctx.metaHost = new URL(params.uri).hostname; } catch { /* ignore */ }
+ await paint('metadata');
+
+ // 3 ── Spend policy: surface the agent's real SOL ceiling ───────────────
+ try {
+ const limRes = await fetch(
+ `/api/agents/${encodeURIComponent(id)}/solana/limits?network=${params.network}`,
+ { credentials: 'include' },
+ );
+ if (limRes.ok) {
+ const lj = await limRes.json().catch(() => ({}));
+ const sp = lj?.data?.spend_policy;
+ if (sp && Number.isFinite(sp.max_sol_per_tx)) ctx.ceilingSol = sp.max_sol_per_tx;
+ }
+ } catch { /* non-fatal — the endpoint enforces the real cap regardless */ }
+ if (ctx.ceilingSol != null && params.sol_buy_in > ctx.ceilingSol) {
+ await fail('policy', `Dev buy ${params.sol_buy_in} SOL exceeds the agent's ${ctx.ceilingSol} SOL/tx ceiling — lower it or raise the policy.`);
+ return;
+ }
+ await paint('policy');
+
+ // 4 ── Broadcast: real launch via the agent custodial wallet ────────────
+ await paint('broadcast');
+ const launchRes = await fetch('/api/pump/launch-agent', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ agent_id: id,
+ name: params.name,
+ symbol: params.symbol,
+ uri: params.uri,
+ network: params.network,
+ buyback_bps: params.buyback_bps,
+ sol_buy_in: params.sol_buy_in,
+ }),
+ });
+ const lr = await launchRes.json().catch(() => ({}));
+ if (!launchRes.ok || !lr?.signature) {
+ const msg = launchRes.status === 401
+ ? 'Sign in as the agent owner to launch.'
+ : launchRes.status === 404
+ ? "You don't own this agent — only the owner can launch."
+ : (lr.message || lr.error_description || 'Launch broadcast failed.');
+ await fail('broadcast', msg);
+ if (launchRes.status === 401) {
+ setLaunchStatus('err', 'Sign in as the agent owner to launch. <a href="/login" style="color:#d4d4d8">Sign in →</a>');
+ }
+ return;
+ }
+
+ // 5 ── Confirmed: real signature in hand ───────────────────────────────
+ const result = {
+ mint: lr.mint,
+ signature: lr.signature,
+ pumpfunUrl: lr.pumpfun_url || `https://pump.fun/coin/${lr.mint}`,
+ explorerUrl: lr.explorer || `https://solscan.io/tx/${lr.signature}${params.network === 'devnet' ? '?cluster=devnet' : ''}`,
+ };
+ ctx.mint = result.mint;
+ ctx.signature = result.signature;
+ {
+ const narration = narrateLaunch('confirm', ctx);
+ const data = await renderLaunchHud({ params, token, stageKey: 'confirm', status: 'active', narration, result });
+ await pushLaunchFrame({ data, activity: narration, type: 'analysis' });
+ }
+
+ // 6 ── Live feed: verify the coin surfaced on /launches ─────────────────
+ ctx.onFeed = await verifyOnLaunchesFeed(result.mint, params.network);
+ {
+ const narration = narrateLaunch('feed', ctx);
+ const data = await renderLaunchHud({ params, token, stageKey: 'feed', status: 'done', narration, result: { ...result, onFeed: ctx.onFeed } });
+ await pushLaunchFrame({ data, activity: narration, type: 'analysis' });
+ }
+
+ appendLaunchResult({ ...result, params, onFeed: ctx.onFeed });
+ setLaunchStatus('ok', `Launched ${esc(params.symbol ? `$${params.symbol}` : params.name)} — live on-chain`);
+ setTimeout(() => { taskStatus.textContent = ''; taskStatus.className = 'asc-task-status'; }, 8000);
+ } catch (err) {
+ await fail('broadcast', err?.message || 'Unexpected launch error.');
+ } finally {
+ launchInFlight = false;
+ taskInput.disabled = false;
+ taskSend.disabled = false;
+ taskSend.classList.remove('sending');
+ taskInput.focus();
+ }
+ }
+
+ // Confirm the freshly launched mint shows on the public /launches feed.
+ async function verifyOnLaunchesFeed(mint, network) {
+ try {
+ const res = await fetch(`/api/pump/launches?network=${encodeURIComponent(network)}&limit=50`, { credentials: 'include' });
+ if (!res.ok) return false;
+ const j = await res.json().catch(() => ({}));
+ const list = Array.isArray(j?.launches) ? j.launches : Array.isArray(j) ? j : [];
+ return list.some((l) => l?.mint === mint);
+ } catch {
+ return false;
+ }
+ }
+
+ // Append the clickable result card to the activity log — the real explorer +
+ // pump.fun links and the "View on /launches" CTA. Built as DOM (anchors) since
+ // the canvas HUD can only paint the URLs, not make them clickable.
+ function appendLaunchResult({ mint, signature, pumpfunUrl, explorerUrl, params, onFeed }) {
+ if (logEmpty) { logEmpty.remove(); logEmpty = null; }
+ const card = document.createElement('div');
+ card.className = 'asc-log-entry type-analysis asc-launch-result';
+ const sym = params.symbol ? `$${esc(params.symbol)}` : esc(params.name || 'coin');
+ const feedHref = `/launches?mint=${encodeURIComponent(mint)}`;
+ card.innerHTML = `
+ <div class="asc-launch-result-head">🚀 ${sym} launched · <span class="asc-launch-mint">${esc(truncMid(mint, 6, 6))}</span></div>
+ <div class="asc-launch-result-links">
+ <a href="${esc(pumpfunUrl)}" target="_blank" rel="noopener">pump.fun ↗</a>
+ <a href="${esc(explorerUrl)}" target="_blank" rel="noopener">explorer ↗</a>
+ <a href="${esc(feedHref)}" class="asc-launch-cta">View on /launches →</a>
+ </div>
+ ${onFeed ? '' : '<div class="asc-launch-result-note">Indexing on the feed — refresh /launches in a moment.</div>'}
+ `;
+ logEl.prepend(card);
+ logCount++;
+ }
+
// ── live stage show (Moonshot 08) ────────────────────────────────────────
// The avatar-cam host performs an always-live show: opener → banter → answer
// audience questions → shout out fresh $THREE tippers → run a game round, on
@@ -1485,6 +2166,7 @@ async function boot(id) {
stage: document.getElementById('asc-panel-stage'),
hud: document.getElementById('asc-panel-hud'),
hire: document.getElementById('asc-panel-hire'),
+ heatmap: document.getElementById('asc-panel-heatmap'),
};
let zTop = 30;
@@ -1498,7 +2180,7 @@ async function boot(id) {
const sr = stageEl.getBoundingClientRect();
// width / height
if (p.w) el.style.width = `${p.w}px`;
- if (p.h && (name === 'log' || name === 'treasury' || name === 'mirror' || name === 'hud' || name === 'stage' || name === 'hire')) el.style.height = `${p.h}px`;
+ if (p.h && (name === 'log' || name === 'treasury' || name === 'mirror' || name === 'hud' || name === 'stage' || name === 'hire' || name === 'heatmap')) el.style.height = `${p.h}px`;
// default position if none saved yet
const pw = el.offsetWidth || p.w || 240;
const ph = el.offsetHeight || 200;
@@ -1509,6 +2191,7 @@ async function boot(id) {
else if (name === 'treasury') { x = M; y = M + 6; } // treasury → top-left cockpit
else if (name === 'mirror') { x = M; y = sr.height - ph - M; } // mirror → bottom-left
else if (name === 'log') { x = sr.width - pw - M; y = M; }
+ else if (name === 'heatmap') { x = M; y = sr.height - ph - M; } // heatmap → bottom-left
else if (name === 'stage') { x = M; y = sr.height - ph - M; } // stage → bottom-left
else if (name === 'hud') { x = M; y = sr.height - ph - M; } // HUD → bottom-left scoreboard
else { x = sr.width - pw - M; y = sr.height - ph - M; } // cam → bottom-right
@@ -1585,11 +2268,12 @@ async function boot(id) {
const h = clamp(sh + (e.clientY - sy), 150, Math.max(150, maxH));
el.style.height = `${h}px`;
layout.panels[name].h = Math.round(h);
+ if (name === 'heatmap') sizeHeatmap();
} else {
sizeWebcam(); // cam: keep renderer matched to new width
}
});
- const end = () => { if (resizing) { resizing = false; saveLayout(); sizeWebcam(); } };
+ const end = () => { if (resizing) { resizing = false; saveLayout(); sizeWebcam(); sizeHeatmap(); } };
handle.addEventListener('pointerup', end);
handle.addEventListener('pointercancel', end);
}
@@ -1642,11 +2326,25 @@ async function boot(id) {
pnlHud.start();
pnlHud.setActive(!layout.panels.hud.hidden);
+ // ── Live Hire visualizer (Moonshot 03) ───────────────────────────────────
+ // Consumes the a2a-hire phase frames (kind: 'a2a_hire') this agent emits when
+ // it hires another over x402: quote → reserve (cap badge) → settle (coin flies)
+ // → on-chain receipt. On a live settle we auto-reveal the panel so the watchable
+ // moment isn't missed, and flash it.
+ hireViz = createHireVisualizer(document.getElementById('asc-hire-body'), {
+ onSettled(meta) {
+ if (layout.panels.hire?.hidden) setPanelHidden('hire', false);
+ const el = panelEls.hire;
+ if (el) { focusPanel(el); el.classList.remove('asc-hire-flash'); void el.offsetWidth; el.classList.add('asc-hire-flash'); }
+ toast(`Hired ${truncMid(meta.providerName || 'provider', 18)}${meta.usd != null ? ' · $' + Number(meta.usd).toFixed(2) : ''}`);
+ },
+ });
+
function setPanelHidden(name, hidden) {
layout.panels[name].hidden = hidden;
const el = panelEls[name];
el.hidden = hidden;
- if (!hidden) { placePanel(name); focusPanel(el); sizeWebcam(); }
+ if (!hidden) { placePanel(name); focusPanel(el); sizeWebcam(); sizeHeatmap(); if (name === 'heatmap') startHeatmap(); }
if (name === 'hud') pnlHud?.setActive(!hidden);
updateToggleButtons();
saveLayout();
@@ -1667,6 +2365,7 @@ async function boot(id) {
requestAnimationFrame(() => {
for (const name of Object.keys(panelEls)) placePanel(name);
sizeWebcam();
+ sizeHeatmap();
});
// keep panels inside the stage on resize
@@ -1675,6 +2374,7 @@ async function boot(id) {
if (!layout.panels[name].hidden) placePanel(name);
}
sizeWebcam();
+ sizeHeatmap();
});
// ── fit / fill ───────────────────────────────────────────────────────────
@@ -1997,9 +2697,11 @@ async function boot(id) {
else if (k === 'c') { if (layout.zen) { layout.zenCam = !layout.zenCam; applyZen(); saveLayout(); } else togglePanel('cam'); e.preventDefault(); }
else if (k === 'l') { togglePanel('log'); e.preventDefault(); }
else if (k === 'i') { togglePanel('stats'); e.preventDefault(); }
+ else if (k === 'h') { togglePanel('heatmap'); e.preventDefault(); }
else if (k === 'g') { togglePanel('stage'); e.preventDefault(); }
else if (k === 't') { togglePanel('treasury'); e.preventDefault(); }
else if (k === 'm') { togglePanel('mirror'); e.preventDefault(); }
+ else if (k === 'b') { togglePanel('hud'); e.preventDefault(); }
else if (k === 's') { screenshot(); e.preventDefault(); }
else if (k === 'p') { togglePip(); e.preventDefault(); }
else if (k === 'v') { toggleFit(); e.preventDefault(); }
@@ -2026,6 +2728,8 @@ async function boot(id) {
// Cleanup on unload
window.addEventListener('beforeunload', () => {
client.disconnect();
+ heatmapPoller?.stop();
+ heatmap?.dispose();
clearInterval(watchPingTimer);
stopWatchStatus();
treasuryCockpit?.destroy();
@@ -2059,8 +2763,10 @@ function buildHelpOverlay() {
<div class="asc-help-row"><span>Toggle avatar cam</span><kbd>C</kbd></div>
<div class="asc-help-row"><span>Toggle activity log</span><kbd>L</kbd></div>
<div class="asc-help-row"><span>Toggle stream stats</span><kbd>I</kbd></div>
+ <div class="asc-help-row"><span>Toggle sentiment heatmap</span><kbd>H</kbd></div>
<div class="asc-help-row"><span>Toggle live stage show</span><kbd>G</kbd></div>
<div class="asc-help-row"><span>Toggle treasury</span><kbd>T</kbd></div>
+ <div class="asc-help-row"><span>Toggle portfolio HUD</span><kbd>B</kbd></div>
<div class="asc-help-row"><span>Capture screenshot</span><kbd>S</kbd></div>
<div class="asc-help-row"><span>Picture-in-picture</span><kbd>P</kbd></div>
<div class="asc-help-row"><span>Fit / fill screen</span><kbd>V</kbd></div>
diff --git a/src/launch-director.js b/src/launch-director.js
index b675e2599..abd916107 100644
--- a/src/launch-director.js
+++ b/src/launch-director.js
@@ -49,6 +49,14 @@ export function parseLaunchCommand(input) {
const text = input.trim();
// Must start with "launch", but never hijack "launchpad …".
if (!/^launch(?!pad)\b/i.test(text)) return null;
+ // Only intercept when it actually reads like a coin launch — otherwise
+ // ("launch the research report") fall through to the normal task path.
+ const looksLikeLaunch =
+ /\b(coin|token|meme(?:coin)?)\b/i.test(text) ||
+ /\bhttps?:\/\//i.test(text) ||
+ /\b(?:ticker|symbol)\b/i.test(text) ||
+ /(?:^|\s)\$[A-Za-z]/.test(text);
+ if (!looksLikeLaunch) return null;
// Metadata URI — first http(s) URL in the command, trailing punctuation trimmed.
const urlMatch = text.match(/\bhttps?:\/\/\S+/i);
@@ -86,7 +94,7 @@ export function parseLaunchCommand(input) {
if (quoted) name = quoted[1].trim();
if (!name) {
const nameKw = text.match(
- /(?:named|name|called)\s+(.+?)(?=\s+(?:ticker|symbol|uri|metadata|on\s+(?:dev|main)net|devnet|mainnet|buyback|dev\s+buy|buy(?:[-\s]?in)?\b|with\b|https?:\/\/)|$)/i,
+ /(?:named|name|called)\s+(.+?)(?=\s+(?:ticker|symbol|uri|metadata|on\s+(?:dev|main)net|devnet|mainnet|buyback|dev\s+buy|buy(?:[-\s]?in)?\b|with\b|https?:\/\/|\$[A-Za-z])|$)/i,
);
if (nameKw) name = nameKw[1].trim().replace(/[.,]+$/, '');
}
diff --git a/src/play/arena-world.js b/src/play/arena-world.js
index 374716df3..4202ef563 100644
--- a/src/play/arena-world.js
+++ b/src/play/arena-world.js
@@ -13,7 +13,7 @@ import {
Scene, PerspectiveCamera, WebGLRenderer, Group,
AmbientLight, DirectionalLight, PointLight, HemisphereLight,
PMREMGenerator, Color, Fog, Vector3, Box3,
- CircleGeometry, RingGeometry, TorusGeometry, CylinderGeometry,
+ CircleGeometry, RingGeometry, TorusGeometry, CylinderGeometry, BoxGeometry, PlaneGeometry,
MeshStandardMaterial, MeshBasicMaterial, Mesh, DoubleSide,
BufferGeometry, BufferAttribute, Points, PointsMaterial, AdditiveBlending,
Sprite, SpriteMaterial, CanvasTexture, MathUtils, LoopOnce, LoopRepeat,
@@ -23,6 +23,7 @@ import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
import { clone as cloneSkeleton } from 'three/addons/utils/SkeletonUtils.js';
import { AnimationManager } from '../animation-manager.js';
import { gltfLoader } from '../loaders/gltf.js';
+import { normalizeFloor } from '../shared/mm-render.js';
const MANIFEST_URL = '/animations/manifest.json';
@@ -79,6 +80,7 @@ export class ArenaWorld {
this._running = false;
this._raf = 0;
this._labels = new Set(); // ArenaAvatar with DOM labels to project
+ this._floors = new Map(); // agentId -> market-maker floor-defense viz
this._focus = null; // { x, z, dist, until } cinematic agent focus
this._tour = null; // active Coin World Tour goal { name, x, z, face, resolve, deadline }
this._tourLoc = 'lobby'; // last waypoint the guide reached
@@ -333,6 +335,7 @@ export class ArenaWorld {
_removeAvatar(avatar) {
if (!avatar) return;
this._labels.delete(avatar);
+ if (avatar.id) this._removeFloor(avatar.id);
if (avatar.root) this.scene.remove(avatar.root);
avatar.dispose();
if (avatar.id) this.agents.delete(avatar.id);
@@ -450,6 +453,170 @@ export class ArenaWorld {
});
}
+ // ── Market-Maker Floor Defense ────────────────────────────────────────────
+ // A glowing horizontal line in front of an agent draws the coin's price floor;
+ // a marker rides above it at a height set by price/floor and descends to touch
+ // the line as the price approaches the floor. Driven entirely by mm events the
+ // agent-mm worker publishes — the render layer never signs or moves funds.
+
+ // Height (world Y) the price marker should sit at for a given floor/price. At
+ // or below the floor it touches the line (LINE_Y); above it floats up.
+ _markerHeight(floorSol, priceSol) {
+ const LINE_Y = 0.07;
+ if (!(floorSol > 0) || !(priceSol > 0)) return LINE_Y + 1.0; // unknown — hover mid
+ const up = Math.max(0, priceSol / floorSol - 1); // 0 = exactly at the floor
+ return LINE_Y + Math.min(2.2, up * 6);
+ }
+
+ _buildFloorViz(avatar, { floorSol, priceSol }, simulate) {
+ const grp = new Group();
+ const at = avatar.root.position;
+ grp.position.set(at.x, 0, at.z + 1.7); // just in front of the avatar, toward the viewer
+
+ // Soft glow pad beneath the line.
+ const glow = new Mesh(
+ new PlaneGeometry(3.4, 0.6),
+ new MeshBasicMaterial({ color: PALETTE.cyan, transparent: true, opacity: 0.12, side: DoubleSide, blending: AdditiveBlending, depthWrite: false }),
+ );
+ glow.rotation.x = -Math.PI / 2;
+ glow.position.y = 0.05;
+ grp.add(glow);
+
+ // The floor line itself — a thin emissive bar lying across the deck.
+ const line = new Mesh(
+ new BoxGeometry(3.0, 0.016, 0.06),
+ new MeshBasicMaterial({ color: PALETTE.cyan, transparent: true, opacity: 0.7, blending: AdditiveBlending, depthWrite: false }),
+ );
+ line.position.y = 0.07;
+ grp.add(line);
+
+ // The price marker — a glowing coin that dances above the line.
+ const marker = new Sprite(new SpriteMaterial({ map: makeLabelTexture('◎', PALETTE.gold), transparent: true, depthTest: false, blending: AdditiveBlending }));
+ marker.scale.set(0.5, 0.5, 1);
+ marker.position.set(0, this._markerHeight(floorSol, priceSol), 0);
+ marker.renderOrder = 11;
+ grp.add(marker);
+
+ // SIM badge — so a dry-run is never mistaken for a real fill.
+ const simBadge = new Sprite(new SpriteMaterial({ map: makeLabelTexture('SIM', PALETTE.violet), transparent: true, depthTest: false }));
+ simBadge.scale.set(0.7, 0.35, 1);
+ simBadge.position.set(1.55, 0.2, 0);
+ simBadge.visible = !!simulate;
+ simBadge.renderOrder = 11;
+ grp.add(simBadge);
+
+ this.scene.add(grp);
+ return {
+ group: grp, glow, line, marker, simBadge,
+ floorSol: floorSol || 0, priceSol: priceSol || 0, simulate: !!simulate,
+ targetY: this._markerHeight(floorSol, priceSol), flash: 0, amber: 0,
+ };
+ }
+
+ // Create or update an agent's floor line + price marker. Lazily builds the viz
+ // the first time it's called for a spawned agent; later calls lerp the marker.
+ setFloor(agentId, { floorSol, priceSol, simulate = false } = {}) {
+ const a = this.agents.get(agentId);
+ if (!a || !a.root) return;
+ const norm = normalizeFloor({ floorSol, priceSol });
+ let f = this._floors.get(agentId);
+ if (!f) {
+ f = this._buildFloorViz(a, norm, simulate);
+ this._floors.set(agentId, f);
+ }
+ if (norm.floorSol > 0) f.floorSol = norm.floorSol;
+ if (norm.priceSol > 0) f.priceSol = norm.priceSol;
+ f.simulate = !!simulate;
+ if (f.simBadge) f.simBadge.visible = !!simulate;
+ f.targetY = this._markerHeight(f.floorSol, f.priceSol);
+ // A fresh quote clears the "re-quoting" amber state.
+ f.amber = 0;
+ return f;
+ }
+
+ // Amber the floor line while a quote/RPC read is failing (the line holds the
+ // last known price; the consumer calls this on a stream error and clears it on
+ // the next good event via setFloor).
+ markFloorReQuoting(agentId) {
+ const f = this._floors.get(agentId);
+ if (f) f.amber = 1;
+ }
+
+ // Route one MM event onto an agent: update the floor/marker, then play the
+ // reaction — defend lunges into a buy + flashes the line, recycle sweeps both
+ // sides, graduate celebrates with a big-win + LP burst.
+ onMmEvent(agentId, ev = {}) {
+ if (!ev) return;
+ const type = ev.type || ev.actionType;
+ const f = this.setFloor(agentId, { floorSol: ev.floorSol, priceSol: ev.priceSol, simulate: ev.simulate });
+ const a = this.agents.get(agentId);
+ const at = a ? a.worldHead() : new Vector3(0, 2, 0);
+ switch (type) {
+ case 'mm_defend':
+ if (a) a.emote('buy');
+ this._spawnCoin(at, { text: 'DEFEND', color: PALETTE.up, dir: 1 });
+ this._ringPulse(a?.root?.position, PALETTE.up);
+ if (f) f.flash = 0.7;
+ break;
+ case 'mm_recycle':
+ this._spawnCoin(at, { text: 'RECYCLE', color: PALETTE.cyan, dir: 1 });
+ this._spawnCoin(at, { text: '◎', color: PALETTE.violet, dir: -1 });
+ if (f) f.flash = 0.4;
+ break;
+ case 'mm_rebalance':
+ this._spawnCoin(at, { text: 'TRIM', color: PALETTE.violet, dir: -1 });
+ break;
+ case 'mm_seed':
+ this._spawnCoin(at, { text: 'SEED', color: PALETTE.cyan, dir: 1 });
+ if (f) f.flash = 0.4;
+ break;
+ case 'mm_graduate':
+ this.reactGraduate(agentId, at);
+ if (f) f.flash = 0.9;
+ break;
+ default:
+ break; // mm_quote — floor/marker already updated, no emote
+ }
+ }
+
+ // Graduation celebration: the big-win backflip (lazy-loaded) + an LP-deposit burst.
+ async reactGraduate(agentId, at) {
+ const a = this.agents.get(agentId);
+ const pos = at || (a ? a.worldHead() : new Vector3(0, 2, 0));
+ if (a) { await this.ensureLibClip(CLIPS.bigWin); a.emote('bigWin'); }
+ this._confetti(pos, true);
+ this._spawnCoin(pos, { text: 'LP', color: PALETTE.gold, dir: 1 });
+ this._ringPulse(a?.root?.position, PALETTE.gold);
+ }
+
+ // Advance every floor's marker lerp + line shimmer. Called from _tick.
+ _tickFloors(dt, t) {
+ for (const f of this._floors.values()) {
+ f.marker.position.y += (f.targetY - f.marker.position.y) * Math.min(1, 4 * dt);
+ f.marker.position.x = Math.sin(t * 1.5 + f.group.position.x) * 0.06;
+ const touching = f.floorSol > 0 && f.priceSol > 0 && f.priceSol <= f.floorSol * 1.02;
+ const pulse = 0.65 + 0.35 * Math.sin(t * 3 + f.group.position.x);
+ const col = f.amber > 0 ? PALETTE.gold : (touching ? PALETTE.up : PALETTE.cyan);
+ f.line.material.color.set(col);
+ f.glow.material.color.set(col);
+ const base = (touching ? 0.95 : 0.6);
+ f.line.material.opacity = Math.min(1, base * pulse + (f.flash > 0 ? f.flash : 0));
+ f.glow.material.opacity = 0.1 + (f.flash > 0 ? f.flash * 0.4 : 0) + (touching ? 0.08 : 0);
+ if (f.flash > 0) f.flash = Math.max(0, f.flash - dt * 1.6);
+ }
+ }
+
+ _removeFloor(agentId) {
+ const f = this._floors.get(agentId);
+ if (!f) return;
+ this.scene.remove(f.group);
+ f.group.traverse?.((o) => {
+ if (o.isMesh) { o.geometry?.dispose?.(); o.material?.dispose?.(); }
+ if (o.isSprite) { o.material?.map?.dispose?.(); o.material?.dispose?.(); }
+ });
+ this._floors.delete(agentId);
+ }
+
// ── Controls (third-person follow) ────────────────────────────────────────
_initControls() {
@@ -665,6 +832,8 @@ export class ArenaWorld {
const halo = a.pad?.userData?.halo;
if (halo) halo.material.opacity = (a.leader ? 0.9 : 0.6) * (0.7 + 0.3 * Math.sin(t * 2 + (a.headHeight || 0)));
}
+ // Market-maker floor lines + price markers.
+ if (this._floors.size) this._tickFloors(dt, t);
if (this._onLabels) this._onLabels();
}
diff --git a/src/play/arena.js b/src/play/arena.js
index 9f84cfa6c..8f11b7722 100644
--- a/src/play/arena.js
+++ b/src/play/arena.js
@@ -8,6 +8,8 @@
import { ArenaWorld } from './arena-world.js';
import { tourCommentary } from '../tour-commentary.js';
+import { createAgentScreenClient } from '../shared/agent-screen-client.js';
+import { sanitizeMmEvent } from '../shared/mm-render.js';
import { createLogger } from '../shared/log.js';
import { fetchReputationBatch } from '../shared/agent-reputation.js';
import { fetchUnlocks } from '../shared/wallet-access.js';
@@ -259,6 +261,7 @@ async function spawnAgentsProgressively(board) {
});
rowsById.set(row.id, row);
createLabel(agent);
+ if (row.kind === 'agent') connectMmFloor(row.id);
} catch (err) {
log.warn('spawn agent', err);
}
@@ -284,6 +287,33 @@ function arenaPositions(n) {
return out;
}
+// ── market-maker floor defense ───────────────────────────────────────────────
+// Each spawned agent subscribes to its own screen stream and watches for the
+// `mm` ride-along the agent-mm worker publishes. A live frame drives the full
+// reaction (floor update + emote + FX); the on-connect log backfill only draws
+// the line at the last known price (no replayed emotes). A stream error ambers
+// the line — it holds the last price until the next good quote.
+const _mmClients = new Map(); // agentId -> screen client
+function connectMmFloor(agentId) {
+ if (!agentId || _mmClients.has(agentId)) return;
+ const client = createAgentScreenClient(agentId, {
+ onFrame: (frame) => {
+ const ev = sanitizeMmEvent(frame?.mm);
+ if (ev) safe(() => world.onMmEvent(agentId, ev));
+ },
+ onLog: (entries) => {
+ // Apply only the most recent MM entry as a static floor (no emote).
+ for (let i = (entries || []).length - 1; i >= 0; i--) {
+ const ev = sanitizeMmEvent(entries[i]?.mm);
+ if (ev) { safe(() => world.setFloor(agentId, ev)); break; }
+ }
+ },
+ onError: () => safe(() => world.markFloorReQuoting(agentId)),
+ });
+ _mmClients.set(agentId, client);
+ client.connect();
+}
+
// ── live stream ────────────────────────────────────────────────────────────────
let es = null;
diff --git a/src/reaction-overlay.js b/src/reaction-overlay.js
new file mode 100644
index 000000000..c233002e6
--- /dev/null
+++ b/src/reaction-overlay.js
@@ -0,0 +1,245 @@
+// Floating-emoji reaction overlay — the canvas layer that paints viewers' live
+// reactions rising over a stream. Split into a pure simulation core (testable
+// with no DOM) and a thin canvas mount that both the live wall and the agent
+// screen reuse.
+//
+// Design goals:
+// • Performant: one <canvas> per surface, capped particle count, and the RAF
+// loop self-pauses the instant the field empties (idle cards cost nothing).
+// • Batched bursts: a flood of reactions can't spawn unbounded particles — each
+// burst is clamped, and the field as a whole is capped (oldest evicted).
+// • Deterministic core: spawn jitter derives from a caller-supplied seed, so the
+// simulation is unit-testable without Math.random.
+
+// The emoji the bar offers, in display order. Mirrors the server allowlist in
+// api/_lib/reaction-rules.js — the server is the authority; this copy is what the
+// viewer can tap. Keep the two in sync.
+export const REACTION_EMOJI = Object.freeze(['🔥', '❤️', '👏', '🚀', '😂']);
+
+const DEFAULT_MAX = 64; // hard ceiling on concurrent particles
+const DEFAULT_PER_BURST = 12; // most particles a single burst may spawn
+const PARTICLE_TTL_MS = 2200; // lifetime of one floating emoji
+const FADE_IN = 0.12; // fraction of life spent fading in
+const FADE_OUT = 0.36; // trailing fraction spent fading out
+
+// Deterministic pseudo-jitter in [0,1) from an integer seed — a cheap hash so two
+// particles from one burst don't stack exactly, without pulling in Math.random
+// (which would make the core untestable).
+function jitter(seed) {
+ const x = Math.sin(seed * 12.9898 + 78.233) * 43758.5453;
+ return x - Math.floor(x);
+}
+
+/**
+ * Create one particle. Coordinates are normalized: x ∈ [0,1] across the width,
+ * y ∈ [0,1] rising from the bottom (0) to the top (1). The mount maps these to
+ * pixels, so the same particle reads correctly at any canvas size.
+ *
+ * @param {string} emoji
+ * @param {number} seed integer seed for deterministic jitter
+ */
+export function spawnParticle(emoji, seed = 0) {
+ const j1 = jitter(seed);
+ const j2 = jitter(seed * 2 + 1);
+ const j3 = jitter(seed * 3 + 7);
+ return {
+ emoji,
+ // Cluster the launch point around the lower centre with a little spread.
+ x0: 0.28 + j1 * 0.44,
+ x: 0.28 + j1 * 0.44,
+ y: 0,
+ // Horizontal sway amplitude + phase so emojis weave as they rise.
+ sway: (j2 - 0.5) * 0.16,
+ phase: j3 * Math.PI * 2,
+ age: 0,
+ ttl: PARTICLE_TTL_MS * (0.85 + j2 * 0.3),
+ size: 0.6,
+ opacity: 0,
+ };
+}
+
+/**
+ * Advance one particle by dtMs. Mutates and returns it. Returns the particle so
+ * callers can map; check `alive(p)` for liveness.
+ */
+export function advanceParticle(p, dtMs) {
+ p.age += dtMs;
+ const t = Math.min(1, p.age / p.ttl);
+ // Rise with a gentle ease-out so it slows near the top.
+ p.y = 1 - (1 - t) * (1 - t);
+ // Weave horizontally around the launch column.
+ p.x = p.x0 + p.sway * Math.sin(p.phase + t * Math.PI * 3);
+ // Pop in scale over the first fifth of life, then hold.
+ p.size = 0.6 + 0.4 * Math.min(1, t / 0.2);
+ p.opacity = particleOpacity(t);
+ return p;
+}
+
+/** Opacity envelope for a normalized life position t ∈ [0,1]. */
+export function particleOpacity(t) {
+ if (t <= 0) return 0;
+ if (t >= 1) return 0;
+ if (t < FADE_IN) return t / FADE_IN;
+ if (t > 1 - FADE_OUT) return (1 - t) / FADE_OUT;
+ return 1;
+}
+
+/** Whether a particle is still within its lifetime. */
+export function alive(p) {
+ return p.age < p.ttl;
+}
+
+/** How many particles a burst of `requested` reactions should actually spawn. */
+export function burstCount(requested, perBurst = DEFAULT_PER_BURST) {
+ const n = Math.max(1, Math.floor(Number(requested) || 1));
+ return Math.min(n, perBurst);
+}
+
+/**
+ * Trim a particle list to `max`, evicting the OLDEST (front) first. Mutates and
+ * returns the same array.
+ */
+export function capParticles(list, max = DEFAULT_MAX) {
+ if (list.length > max) list.splice(0, list.length - max);
+ return list;
+}
+
+/**
+ * The pure simulation field. Holds particles, spawns bursts (clamped + capped),
+ * and steps them forward. No DOM — drive it from a render loop or a test.
+ */
+export class ReactionField {
+ constructor({ max = DEFAULT_MAX, perBurst = DEFAULT_PER_BURST } = {}) {
+ this.max = max;
+ this.perBurst = perBurst;
+ this.particles = [];
+ this._seed = 1;
+ }
+
+ /** Spawn a clamped burst of one emoji. Returns the number actually spawned. */
+ add(emoji, count = 1) {
+ if (!emoji) return 0;
+ const n = burstCount(count, this.perBurst);
+ for (let i = 0; i < n; i++) this.particles.push(spawnParticle(emoji, this._seed++));
+ capParticles(this.particles, this.max);
+ return n;
+ }
+
+ /** Advance the whole field by dtMs, dropping dead particles. */
+ step(dtMs) {
+ const next = [];
+ for (const p of this.particles) {
+ advanceParticle(p, dtMs);
+ if (alive(p)) next.push(p);
+ }
+ this.particles = next;
+ return this.particles.length;
+ }
+
+ get count() {
+ return this.particles.length;
+ }
+
+ clear() {
+ this.particles = [];
+ }
+}
+
+/**
+ * Mount a canvas overlay inside `container`. The container must be positioned
+ * (relative/absolute); the canvas fills it and never intercepts pointer events.
+ * The RAF loop runs only while particles exist, so an idle overlay is free.
+ *
+ * @param {HTMLElement} container
+ * @param {object} [opts]
+ * @param {number} [opts.max] particle ceiling
+ * @param {number} [opts.perBurst] per-burst spawn cap
+ * @param {number} [opts.baseFontPx] emoji size at scale 1.0 for a 360px-tall canvas
+ * @returns {{ burst(emoji:string, count?:number):void, count():number, destroy():void }}
+ */
+export function mountReactionOverlay(container, opts = {}) {
+ if (typeof document === 'undefined' || !container) {
+ // Headless / missing host: hand back a no-op so callers stay simple.
+ return { burst() {}, count: () => 0, destroy() {} };
+ }
+ const field = new ReactionField(opts);
+ const baseFont = opts.baseFontPx || 30;
+
+ const canvas = document.createElement('canvas');
+ canvas.className = 'rx-overlay';
+ canvas.style.cssText =
+ 'position:absolute;inset:0;width:100%;height:100%;pointer-events:none;z-index:6;';
+ canvas.setAttribute('aria-hidden', 'true');
+ container.appendChild(canvas);
+ const ctx = canvas.getContext('2d');
+
+ let raf = null;
+ let last = 0;
+ let destroyed = false;
+ const reduceMotion =
+ typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
+
+ function resize() {
+ const dpr = Math.min(typeof devicePixelRatio === 'number' ? devicePixelRatio : 1, 2);
+ const w = container.clientWidth || 320;
+ const h = container.clientHeight || 180;
+ canvas.width = Math.round(w * dpr);
+ canvas.height = Math.round(h * dpr);
+ ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
+ }
+ resize();
+ const ro = typeof ResizeObserver === 'function' ? new ResizeObserver(resize) : null;
+ ro?.observe(container);
+
+ function frame(now) {
+ if (destroyed) return;
+ const dt = last ? Math.min(now - last, 64) : 16;
+ last = now;
+ field.step(dt);
+
+ const w = canvas.width / (ctx.getTransform().a || 1);
+ const h = canvas.height / (ctx.getTransform().d || 1);
+ ctx.clearRect(0, 0, w, h);
+ ctx.textAlign = 'center';
+ ctx.textBaseline = 'middle';
+ const fontFor = (h / 360) * baseFont;
+ for (const p of field.particles) {
+ const px = p.x * w;
+ const py = (1 - p.y) * h; // y=0 bottom → bottom of canvas
+ ctx.globalAlpha = p.opacity;
+ ctx.font = `${Math.max(12, fontFor * p.size)}px "Apple Color Emoji","Segoe UI Emoji","Noto Color Emoji",sans-serif`;
+ ctx.fillText(p.emoji, px, py);
+ }
+ ctx.globalAlpha = 1;
+
+ if (field.count > 0) {
+ raf = requestAnimationFrame(frame);
+ } else {
+ raf = null;
+ last = 0;
+ ctx.clearRect(0, 0, w, h);
+ }
+ }
+
+ function ensureLoop() {
+ if (raf == null && !destroyed) raf = requestAnimationFrame(frame);
+ }
+
+ return {
+ burst(emoji, count = 1) {
+ if (destroyed || !emoji) return;
+ // Honour reduced-motion: still acknowledge, but a single calm particle.
+ field.add(emoji, reduceMotion ? 1 : count);
+ ensureLoop();
+ },
+ count: () => field.count,
+ destroy() {
+ destroyed = true;
+ if (raf != null) cancelAnimationFrame(raf);
+ raf = null;
+ ro?.disconnect();
+ field.clear();
+ canvas.remove();
+ },
+ };
+}
diff --git a/src/vanity-grind-director.js b/src/vanity-grind-director.js
new file mode 100644
index 000000000..7158f8502
--- /dev/null
+++ b/src/vanity-grind-director.js
@@ -0,0 +1,63 @@
+// Parse a natural-language vanity-grind command typed into the agent-screen task
+// bar, e.g. "grind a wallet starting with pump", "grind pump", "vanity ending
+// with 42", "branded wallet prefix nova suffix xyz". Returns a normalised
+// { prefix, suffix, ignoreCase } request, or null when the text isn't a grind
+// command (so the task bar falls through to the normal task queue).
+//
+// Pure string logic — no network, no key material. The server
+// (/api/agent-vanity-grind) is the real validator and the only place a keypair
+// is ever generated; this just extracts intent.
+
+// Solana base58 alphabet (no 0 O I l). A captured token must be entirely base58
+// to be a usable prefix/suffix; anything else is treated as "no token found".
+const BASE58 = /^[1-9A-HJ-NP-Za-km-z]+$/;
+const MAX_LEN = 6;
+
+const TRIGGER = /\b(grind|vanity)\b|\bbranded\s+wallet\b|\bvanity\s+address\b/i;
+
+// Phrase → which side of the address it targets.
+const PREFIX_PHRASES = /(?:starts?\s+with|starting\s+with|begins?\s+with|beginning\s+with|prefix(?:ed\s+with)?)\s+["'`]?([1-9A-HJ-NP-Za-km-z]{1,12})/i;
+const SUFFIX_PHRASES = /(?:ends?\s+with|ending\s+with|suffix(?:ed\s+with)?)\s+["'`]?([1-9A-HJ-NP-Za-km-z]{1,12})/i;
+// Bare form: "grind pump" / "vanity pump" — the word right after the trigger.
+const BARE = /\b(?:grind|vanity)\b\s+(?:a\s+)?(?:wallet\s+|address\s+)?["'`]?([1-9A-HJ-NP-Za-km-z]{1,12})/i;
+
+function clean(tok) {
+ if (!tok) return '';
+ const t = String(tok).trim();
+ if (!BASE58.test(t)) return '';
+ return t.slice(0, MAX_LEN);
+}
+
+/**
+ * @param {string} input
+ * @returns {{ prefix: string, suffix: string|null, ignoreCase: boolean, raw: string } | null}
+ */
+export function parseGrindCommand(input) {
+ const text = String(input || '').trim();
+ if (!text || !TRIGGER.test(text)) return null;
+
+ let prefix = '';
+ let suffix = '';
+
+ const pm = text.match(PREFIX_PHRASES);
+ if (pm) prefix = clean(pm[1]);
+ const sm = text.match(SUFFIX_PHRASES);
+ if (sm) suffix = clean(sm[1]);
+
+ // Fall back to the bare "grind <token>" form only when no explicit
+ // prefix/suffix phrase matched — and skip filler words that aren't a pattern.
+ if (!prefix && !suffix) {
+ const bm = text.match(BARE);
+ const cand = bm ? clean(bm[1]) : '';
+ const FILLER = new Set(['a', 'an', 'the', 'me', 'wallet', 'address', 'vanity', 'with', 'for', 'my']);
+ if (cand && !FILLER.has(cand.toLowerCase())) prefix = cand;
+ }
+
+ if (!prefix && !suffix) return null;
+
+ // Case-sensitive only when the user explicitly asks; the default keeps grinds
+ // feasible (case-insensitive ≈ halves the difficulty per char).
+ const ignoreCase = !/\b(case[-\s]?sensitive|exact\s+case|match\s+case)\b/i.test(text);
+
+ return { prefix, suffix: suffix || null, ignoreCase, raw: text };
+}
diff --git a/tests/agent-orchestrate.test.js b/tests/agent-orchestrate.test.js
new file mode 100644
index 000000000..f94fddc0c
--- /dev/null
+++ b/tests/agent-orchestrate.test.js
@@ -0,0 +1,279 @@
+import { describe, it, expect, vi } from 'vitest';
+import {
+ extractPlanJson,
+ normalizePlan,
+ splitBudget,
+ clampBudget,
+ buildTaskTree,
+ applyTransition,
+ narrateNode,
+ orchestrateGoal,
+ MAX_SUBTASKS,
+ HARD_MAX_USD,
+ DEFAULT_MAX_USD,
+} from '../api/_lib/agent-orchestrate.js';
+
+describe('extractPlanJson', () => {
+ it('parses a raw JSON object', () => {
+ const out = extractPlanJson('{"subtasks":[{"title":"a","kind":"delegate"}]}');
+ expect(out.subtasks).toHaveLength(1);
+ });
+
+ it('parses JSON wrapped in prose and code fences', () => {
+ const text = 'Sure! Here is the plan:\n```json\n{"subtasks":[{"title":"x","kind":"hire","serviceSlug":"s"}]}\n```\nDone.';
+ const out = extractPlanJson(text);
+ expect(out.subtasks[0].serviceSlug).toBe('s');
+ });
+
+ it('is string-aware so a brace inside a value does not close early', () => {
+ const out = extractPlanJson('{"subtasks":[{"title":"use } char","kind":"delegate"}]}');
+ expect(out.subtasks[0].title).toBe('use } char');
+ });
+
+ it('returns null on no JSON or malformed JSON', () => {
+ expect(extractPlanJson('no json here')).toBeNull();
+ expect(extractPlanJson('{not valid')).toBeNull();
+ expect(extractPlanJson(null)).toBeNull();
+ });
+});
+
+describe('normalizePlan — plan → tree shaping', () => {
+ const leadAgentId = 'lead-1';
+
+ it('keeps valid delegate + hire sub-tasks and defaults delegate target to the lead', () => {
+ const raw = {
+ subtasks: [
+ { title: 'research', kind: 'delegate', instruction: 'do research' },
+ { title: 'scan', kind: 'hire', serviceSlug: 'sentiment-scan', input: { mint: 'x' } },
+ ],
+ };
+ const out = normalizePlan(raw, { leadAgentId, allowedSlugs: ['sentiment-scan'] });
+ expect(out).toHaveLength(2);
+ expect(out[0]).toMatchObject({ kind: 'delegate', agentId: leadAgentId });
+ expect(out[1]).toMatchObject({ kind: 'hire', serviceSlug: 'sentiment-scan' });
+ expect(out[1].input).toEqual({ mint: 'x' });
+ });
+
+ it('downgrades a hire with an unknown/disallowed slug to a free delegate', () => {
+ const raw = { subtasks: [{ title: 'pump', kind: 'hire', serviceSlug: 'not-real' }] };
+ const out = normalizePlan(raw, { leadAgentId, allowedSlugs: ['sentiment-scan'] });
+ expect(out[0].kind).toBe('delegate');
+ expect(out[0].agentId).toBe(leadAgentId);
+ expect(out[0].serviceSlug).toBeUndefined();
+ });
+
+ it('drops entries without a title and caps the count at maxSubtasks', () => {
+ const raw = { subtasks: [{ kind: 'delegate' }, ...Array.from({ length: 20 }, (_, i) => ({ title: `t${i}` }))] };
+ const out = normalizePlan(raw, { leadAgentId });
+ expect(out.length).toBe(MAX_SUBTASKS);
+ expect(out.every((s) => s.title)).toBe(true);
+ });
+
+ it('returns an empty list for a missing/garbage plan', () => {
+ expect(normalizePlan(null, { leadAgentId })).toEqual([]);
+ expect(normalizePlan({ subtasks: 'nope' }, { leadAgentId })).toEqual([]);
+ });
+});
+
+describe('splitBudget / clampBudget — budget never exceeds total', () => {
+ it('splits evenly across hire nodes, floored to cents, sum <= total', () => {
+ const subtasks = [
+ { kind: 'hire' }, { kind: 'delegate' }, { kind: 'hire' }, { kind: 'hire' },
+ ];
+ const slices = splitBudget(subtasks, 1.0);
+ expect(slices[1]).toBeNull(); // delegate costs nothing
+ const hireSlices = slices.filter((s) => s != null);
+ expect(hireSlices).toHaveLength(3);
+ // 1.00 / 3 = 0.33 floored, sum 0.99 <= 1.00
+ hireSlices.forEach((s) => expect(s).toBe(0.33));
+ expect(hireSlices.reduce((a, b) => a + b, 0)).toBeLessThanOrEqual(1.0 + 1e-9);
+ });
+
+ it('returns all-null when there are no hire nodes', () => {
+ expect(splitBudget([{ kind: 'delegate' }, { kind: 'delegate' }], 2)).toEqual([null, null]);
+ });
+
+ it('never lets the summed slices exceed the total for any cap/count', () => {
+ for (const cap of [0.01, 0.1, 1, 2.5, HARD_MAX_USD]) {
+ for (const count of [1, 2, 3, 5, 7]) {
+ const subtasks = Array.from({ length: count }, () => ({ kind: 'hire' }));
+ const sum = splitBudget(subtasks, cap).reduce((a, b) => a + (b || 0), 0);
+ expect(sum).toBeLessThanOrEqual(cap + 1e-9);
+ }
+ }
+ });
+
+ it('clamps budget into (0, HARD_MAX_USD] with a sane default', () => {
+ expect(clampBudget(-5)).toBe(DEFAULT_MAX_USD);
+ expect(clampBudget(0)).toBe(DEFAULT_MAX_USD);
+ expect(clampBudget('nan')).toBe(DEFAULT_MAX_USD);
+ expect(clampBudget(999)).toBe(HARD_MAX_USD);
+ expect(clampBudget(2)).toBe(2);
+ });
+});
+
+describe('buildTaskTree + applyTransition', () => {
+ const leadAgentId = 'lead-1';
+ const subtasks = [
+ { title: 'research', kind: 'delegate', agentId: leadAgentId },
+ { title: 'scan', kind: 'hire', serviceSlug: 'sentiment-scan' },
+ ];
+
+ it('builds a two-level tree: lead + one child per sub-task, edges fan out', () => {
+ const tree = buildTaskTree({ taskId: 't1', leadAgentId, goal: 'do it', maxUsd: 1, subtasks });
+ expect(tree.nodes[0].id).toBe('lead');
+ expect(tree.nodes).toHaveLength(3);
+ expect(tree.edges).toEqual([{ from: 'lead', to: 'n0' }, { from: 'lead', to: 'n1' }]);
+ expect(tree.nodes[1].status).toBe('queued');
+ expect(tree.nodes[2].serviceSlug).toBe('sentiment-scan');
+ expect(tree.nodes[2].maxUsd).toBe(1); // single hire gets full cap
+ });
+
+ it('applyTransition returns a fresh tree and recomputes spend + status', () => {
+ const tree = buildTaskTree({ taskId: 't1', leadAgentId, goal: 'do it', maxUsd: 1, subtasks });
+ const t2 = applyTransition(tree, 'n1', { status: 'done', costUsd: 0.5 });
+ expect(t2).not.toBe(tree);
+ expect(tree.nodes[2].status).toBe('queued'); // original untouched
+ expect(t2.budgetSpentUsd).toBe(0.5);
+
+ const t3 = applyTransition(t2, 'n0', { status: 'done' });
+ const t4 = applyTransition(t3, 'lead', { status: 'done' });
+ expect(t4.status).toBe('done'); // all children + lead done
+ });
+
+ it('marks the task completed_with_errors when any node failed', () => {
+ let tree = buildTaskTree({ taskId: 't1', leadAgentId, goal: 'g', maxUsd: 1, subtasks });
+ tree = applyTransition(tree, 'n0', { status: 'done' });
+ tree = applyTransition(tree, 'n1', { status: 'failed', error: 'budget exceeded' });
+ tree = applyTransition(tree, 'lead', { status: 'done' });
+ expect(tree.status).toBe('completed_with_errors');
+ });
+});
+
+describe('narrateNode', () => {
+ it('narrates a paid hire with cost and receipt', () => {
+ const line = narrateNode({ kind: 'hire', title: 'sentiment scan', status: 'done', costUsd: 0.02, signature: '5xRabcdefghijk' });
+ expect(line).toMatch(/Hired/);
+ expect(line).toMatch(/\$0\.02/);
+ expect(line).toMatch(/5xRabcde/);
+ });
+
+ it('narrates a failed hire with the reason', () => {
+ const line = narrateNode({ kind: 'hire', title: 'scan', status: 'failed', error: 'budget exceeded' });
+ expect(line).toMatch(/budget exceeded/);
+ });
+});
+
+describe('orchestrateGoal — graph-delta sequencing', () => {
+ const base = { userId: 'u1', leadAgentId: 'lead-1', leadName: 'Lead', goal: 'research a coin' };
+
+ function fakeDelegate(plan) {
+ // First call (planning) returns the plan JSON; later calls echo the message.
+ let first = true;
+ return vi.fn(async ({ message }) => {
+ if (first) { first = false; return { response: JSON.stringify(plan) }; }
+ return { response: `did: ${message.slice(0, 20)}` };
+ });
+ }
+
+ it('emits monotonic queued → running → done transitions and a final tree', async () => {
+ const plan = { subtasks: [
+ { title: 'research', kind: 'delegate', instruction: 'research the coin' },
+ { title: 'sentiment', kind: 'hire', serviceSlug: 'sentiment-scan' },
+ ] };
+ const runDelegate = fakeDelegate(plan);
+ const runHire = vi.fn(async ({ maxUsd }) => ({
+ hire: { usd: maxUsd, provider_agent_id: 'prov-1', provider: { name: 'Kestrel' }, invocation_signature: 'sig123', invocation_explorer: 'https://solscan.io/tx/sig123' },
+ result: 'sentiment: bullish',
+ }));
+
+ const snapshots = [];
+ const tree = await orchestrateGoal(
+ { ...base, maxUsd: 1, catalog: [{ slug: 'sentiment-scan', name: 'Sentiment', price_usdc: 0.02 }], emit: (t) => snapshots.push(structuredClone(t)) },
+ { runDelegate, runHire, makeTaskId: () => 'task-1' },
+ );
+
+ // First snapshot is the planning phase; last is the finished tree.
+ expect(snapshots[0].status).toBe('planning');
+ expect(tree.taskId).toBe('task-1');
+ expect(tree.status).toBe('done');
+
+ // The hire node ran through queued → running → done across snapshots.
+ const hireStatuses = snapshots.map((s) => s.nodes.find((n) => n.id === 'n1')?.status).filter(Boolean);
+ expect(hireStatuses).toContain('queued');
+ expect(hireStatuses.indexOf('running')).toBeLessThan(hireStatuses.lastIndexOf('done'));
+
+ // Real signature + cost landed on the hire node; budget respected.
+ const hireNode = tree.nodes.find((n) => n.id === 'n1');
+ expect(hireNode.status).toBe('done');
+ expect(hireNode.signature).toBe('sig123');
+ expect(hireNode.costUsd).toBe(1); // single hire → full cap slice
+ expect(tree.budgetSpentUsd).toBeLessThanOrEqual(tree.maxUsd + 1e-9);
+
+ // The lead synthesized at the end.
+ expect(tree.nodes[0].status).toBe('done');
+ expect(runHire).toHaveBeenCalledOnce();
+ });
+
+ it('a failed hire turns one node red but the rest of the team continues', async () => {
+ const plan = { subtasks: [
+ { title: 'scan', kind: 'hire', serviceSlug: 'sentiment-scan' },
+ { title: 'summary', kind: 'delegate', instruction: 'summarize' },
+ ] };
+ const runDelegate = fakeDelegate(plan);
+ const runHire = vi.fn(async () => { throw Object.assign(new Error('over budget'), { code: 'over_cap' }); });
+
+ const tree = await orchestrateGoal(
+ { ...base, maxUsd: 0.5, catalog: [{ slug: 'sentiment-scan', name: 'S', price_usdc: 1 }] },
+ { runDelegate, runHire, makeTaskId: () => 't' },
+ );
+
+ const hireNode = tree.nodes.find((n) => n.id === 'n0');
+ expect(hireNode.status).toBe('failed');
+ expect(hireNode.error).toBe('budget exceeded');
+ // The delegate sub-task still completed, and so did the lead.
+ expect(tree.nodes.find((n) => n.id === 'n1').status).toBe('done');
+ expect(tree.nodes[0].status).toBe('done');
+ expect(tree.status).toBe('completed_with_errors');
+ });
+
+ it('handles a solo goal (empty plan) as a single lead node', async () => {
+ const runDelegate = fakeDelegate({ subtasks: [] });
+ const runHire = vi.fn();
+ const tree = await orchestrateGoal(
+ { ...base, maxUsd: 1, emit: () => {} },
+ { runDelegate, runHire, makeTaskId: () => 't' },
+ );
+ expect(tree.nodes).toHaveLength(1);
+ expect(tree.nodes[0].status).toBe('done');
+ expect(runHire).not.toHaveBeenCalled();
+ });
+
+ it('never exceeds the total budget across multiple hires', async () => {
+ const plan = { subtasks: [
+ { title: 'a', kind: 'hire', serviceSlug: 's' },
+ { title: 'b', kind: 'hire', serviceSlug: 's' },
+ { title: 'c', kind: 'hire', serviceSlug: 's' },
+ ] };
+ const runDelegate = fakeDelegate(plan);
+ // Each provider charges exactly its allotted slice.
+ const runHire = vi.fn(async ({ maxUsd }) => ({ hire: { usd: maxUsd, invocation_signature: 's' }, result: 'ok' }));
+ const tree = await orchestrateGoal(
+ { ...base, maxUsd: 1, catalog: [{ slug: 's', name: 'S', price_usdc: 0.3 }] },
+ { runDelegate, runHire, makeTaskId: () => 't' },
+ );
+ expect(tree.budgetSpentUsd).toBeLessThanOrEqual(1 + 1e-9);
+ expect(runHire).toHaveBeenCalledTimes(3);
+ });
+
+ it('falls back to a solo failed-plan node when planning throws', async () => {
+ const runDelegate = vi.fn(async () => { throw Object.assign(new Error('no llm'), { code: 'llm_unavailable' }); });
+ const tree = await orchestrateGoal(
+ { ...base, maxUsd: 1 },
+ { runDelegate, runHire: vi.fn(), makeTaskId: () => 't' },
+ );
+ expect(tree.nodes).toHaveLength(1);
+ expect(tree.nodes[0].status).toBe('failed');
+ expect(tree.nodes[0].error).toMatch(/unavailable/);
+ });
+});
diff --git a/tests/agent-screen-dj.test.js b/tests/agent-screen-dj.test.js
new file mode 100644
index 000000000..ac8333ab6
--- /dev/null
+++ b/tests/agent-screen-dj.test.js
@@ -0,0 +1,108 @@
+// Unit tests for the Ambient World DJ script (Brief 22).
+//
+// The DJ turns world snapshots into calm host lines. Two properties matter most
+// and are easy to regress: the minimum-gap pacing (it must never get chatty) and
+// that lines are real, templated reactions to world events (sunrise, dusk, a
+// crowd) rather than random filler — and that none of them ever names a coin.
+
+import { describe, it, expect } from 'vitest';
+import { createDjScript, DJ_MIN_GAP_MS } from '../src/agent-screen-dj.js';
+
+const state = (over = {}) => ({ phase: 0.5, pedCount: 0, crowd: 0, biomeLabel: 'Verdant Meadow', landmark: 'the plaza', ...over });
+
+describe('createDjScript pacing', () => {
+ it('emits the first line immediately, then nothing until the gap elapses', () => {
+ const dj = createDjScript({ minGapMs: 28_000 });
+ const first = dj.observe(state(), 0);
+ expect(first).not.toBeNull();
+ expect(dj.observe(state(), 1_000)).toBeNull();
+ expect(dj.observe(state(), 27_999)).toBeNull();
+ expect(dj.observe(state(), 28_000)).not.toBeNull();
+ });
+
+ it('never spaces two emitted lines closer than the min gap over a long run', () => {
+ const dj = createDjScript({ minGapMs: 28_000 });
+ let now = 0;
+ let lastEmit = -Infinity;
+ // Hammer it far more often than the gap, with a changing world.
+ for (let i = 0; i < 500; i++) {
+ now += 3_000;
+ const line = dj.observe(state({ phase: (i / 50) % 1, crowd: (i % 7) / 6, pedCount: i % 4 }), now);
+ if (line) {
+ expect(now - lastEmit).toBeGreaterThanOrEqual(28_000);
+ lastEmit = now;
+ }
+ }
+ });
+
+ it('defaults the min gap to DJ_MIN_GAP_MS', () => {
+ const dj = createDjScript();
+ expect(dj.observe(state(), 0)).not.toBeNull();
+ expect(dj.observe(state(), DJ_MIN_GAP_MS - 1)).toBeNull();
+ expect(dj.observe(state(), DJ_MIN_GAP_MS)).not.toBeNull();
+ });
+});
+
+describe('createDjScript events', () => {
+ it('templates the world name and landmark into the line', () => {
+ const dj = createDjScript({ minGapMs: 0, place: 'Dune Sea', landmark: 'the dunes' });
+ const line = dj.observe(state({ phase: 0.5, biomeLabel: 'Dune Sea', landmark: 'the dunes' }), 0);
+ expect(line.text).toMatch(/Dune Sea|the dunes/);
+ expect(line.type).toBe('activity');
+ expect(typeof line.mood).toBe('string');
+ });
+
+ it('announces a sunrise when the sky crosses into the sunrise band', () => {
+ const dj = createDjScript({ minGapMs: 0 });
+ dj.observe(state({ phase: 0.1 }), 0); // night — primes the band memory
+ const line = dj.observe(state({ phase: 0.25 }), 1);
+ expect(line.event).toBe('sunrise');
+ });
+
+ it('calls golden hour as its own beat', () => {
+ const dj = createDjScript({ minGapMs: 0 });
+ dj.observe(state({ phase: 0.5 }), 0); // day
+ const line = dj.observe(state({ phase: 0.7 }), 1);
+ expect(line.event).toBe('goldenHour');
+ });
+
+ it('reacts to the plaza filling up with a crowd line', () => {
+ const dj = createDjScript({ minGapMs: 0 });
+ dj.observe(state({ phase: 0.5, crowd: 0 }), 0); // quiet — prime
+ const line = dj.observe(state({ phase: 0.5, crowd: 0.8 }), 1);
+ expect(line.event).toBe('zoneBusy');
+ });
+
+ it('falls back to calm idle ambiance when nothing changed', () => {
+ const dj = createDjScript({ minGapMs: 0 });
+ dj.observe(state({ phase: 0.5 }), 0);
+ const line = dj.observe(state({ phase: 0.5 }), 1);
+ expect(line.event).toBe('idleAmbiance');
+ });
+
+ it('rotates phrasings deterministically (no Math.random)', () => {
+ const a = createDjScript({ minGapMs: 0 });
+ const b = createDjScript({ minGapMs: 0 });
+ const seq = [];
+ for (let i = 0; i < 5; i++) seq.push([a.observe(state(), i).text, b.observe(state(), i).text]);
+ for (const [x, y] of seq) expect(x).toBe(y);
+ });
+});
+
+describe('createDjScript brand safety', () => {
+ it('never mentions any coin or token in any phrasing', () => {
+ const dj = createDjScript({ minGapMs: 0, place: 'Neon Expanse', landmark: 'the expanse' });
+ const seen = new Set();
+ // Drive every event band many times to exhaust the template banks.
+ const phases = [0.1, 0.25, 0.5, 0.7, 0.75, 0.9];
+ for (let i = 0; i < 200; i++) {
+ const line = dj.observe(state({ phase: phases[i % phases.length], crowd: (i % 3) / 2, pedCount: i % 5 }), i);
+ if (line) seen.add(line.text.toLowerCase());
+ }
+ for (const text of seen) {
+ expect(text).not.toMatch(/\$[a-z]/i); // no $TICKER
+ expect(text).not.toMatch(/token|coin|\bbuy\b|\bsell\b|pump|market cap/i);
+ }
+ expect(seen.size).toBeGreaterThan(3);
+ });
+});
diff --git a/tests/agent-screen-mirror.test.js b/tests/agent-screen-mirror.test.js
index dbc3bf187..11396908f 100644
--- a/tests/agent-screen-mirror.test.js
+++ b/tests/agent-screen-mirror.test.js
@@ -112,6 +112,6 @@ describe('fmtSol', () => {
it('trims trailing zeros and renders 0 cleanly', () => {
expect(fmtSol(0.5000)).toBe('0.5');
expect(fmtSol(0)).toBe('0');
- expect(fmtSol(0.12305, 4)).toBe('0.123');
+ expect(fmtSol(0.123, 4)).toBe('0.123');
});
});
diff --git a/tests/agent-screen-world-clock.test.js b/tests/agent-screen-world-clock.test.js
new file mode 100644
index 000000000..2a7307520
--- /dev/null
+++ b/tests/agent-screen-world-clock.test.js
@@ -0,0 +1,95 @@
+// Unit tests for the Ambient World DJ deterministic clock (Brief 22).
+//
+// The whole point of worldClock is that every viewer of the same agent sees the
+// same sky: it must be a pure, deterministic function of wall time, cycle length
+// and a per-agent offset — no Math.random, no hidden state. These tests pin the
+// phase mapping (the day-fraction convention day-night.js consumes) and the
+// time-of-day band labels the readout + DJ key off.
+
+import { describe, it, expect } from 'vitest';
+import {
+ worldClock, phaseLabel, isGoldenHour, daylightAmount, DEFAULT_CYCLE_MS,
+} from '../src/shared/world-clock.js';
+
+describe('worldClock', () => {
+ const CYCLE = 8 * 60 * 1000;
+
+ it('maps the start of a cycle to midnight (phase 0)', () => {
+ expect(worldClock(0, CYCLE)).toBe(0);
+ expect(worldClock(CYCLE, CYCLE)).toBe(0); // exactly one cycle later wraps to 0
+ });
+
+ it('maps quarter / half / three-quarter cycle to sunrise / noon / sunset', () => {
+ expect(worldClock(CYCLE * 0.25, CYCLE)).toBeCloseTo(0.25, 10);
+ expect(worldClock(CYCLE * 0.5, CYCLE)).toBeCloseTo(0.5, 10);
+ expect(worldClock(CYCLE * 0.75, CYCLE)).toBeCloseTo(0.75, 10);
+ });
+
+ it('is deterministic — same inputs always give the same phase', () => {
+ const a = worldClock(1_700_000_123_456, CYCLE);
+ const b = worldClock(1_700_000_123_456, CYCLE);
+ expect(a).toBe(b);
+ });
+
+ it('always returns a phase in [0, 1)', () => {
+ for (let t = -CYCLE * 3; t <= CYCLE * 3; t += CYCLE / 37) {
+ const p = worldClock(t, CYCLE);
+ expect(p).toBeGreaterThanOrEqual(0);
+ expect(p).toBeLessThan(1);
+ }
+ });
+
+ it('handles negative wall-clock values without going out of range', () => {
+ expect(worldClock(-CYCLE * 0.25, CYCLE)).toBeCloseTo(0.75, 10);
+ });
+
+ it('applies a per-agent offset deterministically', () => {
+ const offset = CYCLE * 0.5;
+ expect(worldClock(0, CYCLE, offset)).toBeCloseTo(0.5, 10);
+ // Two agents with different offsets diverge but each stays pure.
+ expect(worldClock(0, CYCLE, CYCLE * 0.1)).not.toBe(worldClock(0, CYCLE, CYCLE * 0.6));
+ });
+
+ it('guards a non-positive cycle by falling back to the default', () => {
+ expect(worldClock(DEFAULT_CYCLE_MS * 0.5, 0)).toBeCloseTo(0.5, 10);
+ expect(worldClock(DEFAULT_CYCLE_MS * 0.5, -5)).toBeCloseTo(0.5, 10);
+ });
+});
+
+describe('phaseLabel', () => {
+ it('names the four times of day by band', () => {
+ expect(phaseLabel(0.0)).toBe('night');
+ expect(phaseLabel(0.25)).toBe('sunrise');
+ expect(phaseLabel(0.5)).toBe('day');
+ expect(phaseLabel(0.75)).toBe('dusk');
+ expect(phaseLabel(0.9)).toBe('night');
+ });
+
+ it('wraps phases outside [0,1)', () => {
+ expect(phaseLabel(1.25)).toBe('sunrise');
+ expect(phaseLabel(-0.75)).toBe('sunrise');
+ });
+});
+
+describe('isGoldenHour', () => {
+ it('is true only just before sunset', () => {
+ expect(isGoldenHour(0.7)).toBe(true);
+ expect(isGoldenHour(0.5)).toBe(false);
+ expect(isGoldenHour(0.9)).toBe(false);
+ });
+});
+
+describe('daylightAmount', () => {
+ it('peaks at noon and bottoms out at midnight', () => {
+ expect(daylightAmount(0.5)).toBeCloseTo(1, 5);
+ expect(daylightAmount(0.0)).toBe(0);
+ });
+
+ it('always returns a value in [0, 1]', () => {
+ for (let p = 0; p < 1; p += 0.013) {
+ const d = daylightAmount(p);
+ expect(d).toBeGreaterThanOrEqual(0);
+ expect(d).toBeLessThanOrEqual(1);
+ }
+ });
+});
diff --git a/tests/launch-director.test.js b/tests/launch-director.test.js
new file mode 100644
index 000000000..3313c9de9
--- /dev/null
+++ b/tests/launch-director.test.js
@@ -0,0 +1,165 @@
+// Launch Director — unit tests for the pure command parser, validation, the
+// stage→narration mapping, and the formatting helpers. No DOM, no network:
+// renderLaunchHud needs a canvas and is exercised in the browser, but every bit
+// of logic the launch depends on lives in pure functions covered here.
+
+import { describe, it, expect } from 'vitest';
+import {
+ parseLaunchCommand,
+ validateLaunchParams,
+ narrate,
+ LAUNCH_STAGES,
+ LAUNCH_LIMITS,
+ stageIndex,
+ truncMid,
+ formatSol,
+} from '../src/launch-director.js';
+
+describe('parseLaunchCommand', () => {
+ it('returns null for non-launch text', () => {
+ expect(parseLaunchCommand('research the latest in AI')).toBe(null);
+ expect(parseLaunchCommand('')).toBe(null);
+ expect(parseLaunchCommand(null)).toBe(null);
+ // "launch" without any coin signal stays a normal task
+ expect(parseLaunchCommand('launch the research report')).toBe(null);
+ });
+
+ it('never hijacks "launchpad …"', () => {
+ expect(parseLaunchCommand('launchpad studio open the gallery')).toBe(null);
+ });
+
+ it('parses a full command with keyword name, ticker, uri', () => {
+ const p = parseLaunchCommand(
+ 'launch a coin named Doge Killer ticker DKILL uri https://meta.example/d.json',
+ );
+ expect(p).toMatchObject({
+ name: 'Doge Killer',
+ symbol: 'DKILL',
+ uri: 'https://meta.example/d.json',
+ network: 'mainnet',
+ buyback_bps: 0,
+ sol_buy_in: 0,
+ });
+ });
+
+ it('parses a quoted name, devnet, and percent buyback', () => {
+ const p = parseLaunchCommand(
+ 'launch coin "My Cool Coin" ticker MCC uri https://x.io/m.json on devnet buyback 4.2%',
+ );
+ expect(p.name).toBe('My Cool Coin');
+ expect(p.symbol).toBe('MCC');
+ expect(p.network).toBe('devnet');
+ expect(p.buyback_bps).toBe(420);
+ });
+
+ it('accepts buyback expressed in bps', () => {
+ const p = parseLaunchCommand('launch token named A ticker A uri https://x.io/m.json buyback 250 bps');
+ expect(p.buyback_bps).toBe(250);
+ });
+
+ it('reads a $TICKER fallback and stops the name before it', () => {
+ const p = parseLaunchCommand('launch a coin named Foo $FOO uri https://x.io/m.json');
+ expect(p.symbol).toBe('FOO');
+ expect(p.name).toBe('Foo');
+ });
+
+ it('parses an optional SOL dev buy', () => {
+ const p = parseLaunchCommand('launch a coin named A ticker A uri https://x.io/m.json with 0.5 sol');
+ expect(p.sol_buy_in).toBe(0.5);
+ const p2 = parseLaunchCommand('launch a coin named A ticker A uri https://x.io/m.json dev buy 1.25 sol');
+ expect(p2.sol_buy_in).toBe(1.25);
+ });
+
+ it('trims trailing punctuation off the URI and keeps the network out of it', () => {
+ const p = parseLaunchCommand('launch a coin named A ticker A uri https://x.io/m.json on devnet.');
+ expect(p.uri).toBe('https://x.io/m.json');
+ expect(p.network).toBe('devnet');
+ });
+
+ it('clamps buyback to the 0–10000 bps range', () => {
+ const p = parseLaunchCommand('launch a coin named A ticker A uri https://x.io/m.json buyback 50000 bps');
+ expect(p.buyback_bps).toBe(10_000);
+ });
+
+ it('returns incomplete params (validation handles the gaps)', () => {
+ const p = parseLaunchCommand('launch a coin uri https://x.io/m.json');
+ expect(p.name).toBe(null);
+ expect(p.symbol).toBe(null);
+ expect(p.uri).toBe('https://x.io/m.json');
+ });
+});
+
+describe('validateLaunchParams', () => {
+ const good = { name: 'Good Coin', symbol: 'GOOD', uri: 'https://x.io/m.json', network: 'mainnet' };
+
+ it('passes a complete, in-bounds command', () => {
+ expect(validateLaunchParams(good)).toEqual({ ok: true, errors: [] });
+ });
+
+ it('flags a missing name, ticker, and uri', () => {
+ const r = validateLaunchParams({ name: null, symbol: null, uri: null });
+ expect(r.ok).toBe(false);
+ expect(r.errors).toHaveLength(3);
+ });
+
+ it('enforces the endpoint length limits', () => {
+ const longName = validateLaunchParams({ ...good, name: 'x'.repeat(LAUNCH_LIMITS.name + 1) });
+ expect(longName.ok).toBe(false);
+ const longSym = validateLaunchParams({ ...good, symbol: 'x'.repeat(LAUNCH_LIMITS.symbol + 1) });
+ expect(longSym.ok).toBe(false);
+ const longUri = validateLaunchParams({ ...good, uri: `https://x.io/${'a'.repeat(LAUNCH_LIMITS.uri)}` });
+ expect(longUri.ok).toBe(false);
+ });
+
+ it('rejects a non-http URI and an unknown network', () => {
+ expect(validateLaunchParams({ ...good, uri: 'ipfs://abc' }).ok).toBe(false);
+ expect(validateLaunchParams({ ...good, network: 'testnet' }).ok).toBe(false);
+ });
+});
+
+describe('narrate', () => {
+ it('maps every stage to a non-empty, value-bearing line', () => {
+ const ctx = { name: 'Good Coin', symbol: 'GOOD', network: 'devnet' };
+ for (const s of LAUNCH_STAGES) {
+ expect(narrate(s.key, ctx).length).toBeGreaterThan(0);
+ }
+ expect(narrate('prepare', ctx)).toContain('$GOOD');
+ expect(narrate('prepare', ctx)).toContain('devnet');
+ expect(narrate('broadcast', ctx)).toContain('devnet');
+ });
+
+ it('only claims success once a real signature is present', () => {
+ expect(narrate('confirm', {})).toBe('Confirming on-chain…');
+ const live = narrate('confirm', { mint: 'Mint1111111111', signature: 'Sig22222222222' });
+ expect(live).toContain('Live!');
+ });
+
+ it('shows the spend ceiling once known', () => {
+ expect(narrate('policy', {})).toBe('Checking spend policy…');
+ expect(narrate('policy', { ceilingSol: 1, solBuyIn: 0.25 })).toContain('ceiling 1 SOL/tx');
+ });
+
+ it('confirms the feed only when the coin actually surfaced', () => {
+ expect(narrate('feed', { symbol: 'GOOD', onFeed: false })).toContain('Surfacing');
+ expect(narrate('feed', { symbol: 'GOOD', onFeed: true })).toContain('launches feed');
+ });
+});
+
+describe('helpers', () => {
+ it('stageIndex finds the ordered position', () => {
+ expect(stageIndex('prepare')).toBe(0);
+ expect(stageIndex('feed')).toBe(LAUNCH_STAGES.length - 1);
+ expect(stageIndex('nope')).toBe(-1);
+ });
+
+ it('truncMid middle-truncates long strings only', () => {
+ expect(truncMid('short')).toBe('short');
+ expect(truncMid('ABCDEFGHIJKLMNOP', 4, 4)).toBe('ABCD…MNOP');
+ });
+
+ it('formatSol renders small and zero amounts cleanly', () => {
+ expect(formatSol(0)).toBe('0');
+ expect(formatSol(0.5)).toBe('0.5');
+ expect(formatSol(1)).toBe('1');
+ });
+});