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.

Add tests for tour commentary and vanity grinder progress; implement anchor client and brief logic

zprv79a18f6f21ae
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d5debad6c..e7f6c052e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **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]`
- **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]`
- **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]`
+- **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]`
## 2026-06-28
@@ -55,7 +56,6 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Submitted three.ws to the Claude Connectors Directory** — three.ws is now in the queue for Anthropic's Claude Connectors Directory — the in-app catalog where Claude users browse and one-click-connect remote MCP servers. We submitted our flagship server (the Avatars & Agents connector at /api/mcp): 35 tools that let Claude manage your three.ws avatars, validate and inspect glTF/GLB models, read on-chain agent reputation and identity, recall agent memory, and surface live $THREE-era market data — connected securely with OAuth, with pay-per-call tools settling in USDC over x402. Once it's approved, you'll be able to add three.ws to Claude straight from the directory. (`/docs/mcp`) `[feature, infra]`
- **Text-to-3D falls back to the free engine when the paid one runs dry** — Typing a prompt to generate a 3D model first paints a quick reference image, and on higher-quality tiers that step ran on a paid image service. If that account was out of credit, the whole request used to stop at a 'temporarily unavailable' message — even though our free NVIDIA engine builds a model straight from your words and never needed that paid step at all. Now a dry paid account automatically hands your prompt to the free engine instead of giving up, so 'type a prompt, get a model' keeps working. If every engine is genuinely down, you still get an honest 'try again shortly' rather than a hard error or a confusing billing message. `[fix]`
- **The "Save to my avatars" button is readable on every theme** — On pages with a white accent color, the "⑂ Save to my avatars" button (shown on any avatar you don't own) rendered white text on a white background — effectively invisible. The button now picks its text color from the actual button background, so a light button gets black text and a dark button keeps white, keeping the label legible everywhere it appears. `[fix]`
-- **The agent's walk preview now fills its whole card** — On an agent's page, the 'Walk with this agent' preview used to sit as a small box pinned to the left with the rest of the card empty beside it. It's now a proper two-column panel: the live avatar walks on the left while the right side 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]`
- **The Agents directory now lists every on-chain agent, not just ours** — Until now /agents showed the agents launched on three.ws plus the ones registered through ERC-8004 on EVM chains. We've expanded it to the whole Solana agent ecosystem: a new background crawler indexes the Metaplex Agent Registry and the AgenC coordination protocol every half hour, so agents created anywhere on Solana — not only on three.ws — appear in the directory automatically. The page now opens on one unified feed with quick filters for All sources, Solana, and EVM, and every card carries a coloured badge showing where the agent came from (Metaplex, AgenC, an EVM chain, or three.ws). Agents we launched that are also registered upstream are de-duplicated so they only show once, with their richer three.ws profile. (`/agents`) `[feature, infra]`
- **The Avatar Engines Atlas page is now reachable** — The link to the Avatar Engines Atlas — the curated rundown of the open-source and commercial engines behind high-quality, photoreal 3D human avatars — was returning a 404 because the page was never wired into routing. The route is now in place, so the page opens from navigation as intended. (`/avatar-engines`) `[fix]`
- **The Coin Intelligence feed now fills itself** — The Coin Intelligence engine (/coin-intel) watches pump.fun's live launch firehose, observes each new coin's first ~90 seconds of trading, and scores it — organic vs bundle, wallet concentration, smart-money entries, category. Until now that observation only ran when a separate always-on worker was up, so the page often sat on its "engine is warming up" screen with nothing to show. The observer now also runs on a schedule on our serverless platform, so it keeps watching launches and recording verdicts on its own — newest coins appear in the feed continuously without depending on any single machine staying online. (`/coin-intel`) `[fix, feature]`
diff --git a/api/_lib/a2a-hire-phases.js b/api/_lib/a2a-hire-phases.js
new file mode 100644
index 000000000..b9b427850
--- /dev/null
+++ b/api/_lib/a2a-hire-phases.js
@@ -0,0 +1,186 @@
+// Pure phase → render mapping + cap math for the live agent-to-agent hire
+// visualizer.
+//
+// /api/agents/a2a-hire emits ONE screen frame per real milestone of a hire so a
+// viewer on /agent-screen watches the commerce happen end to end:
+//
+// discover → quote → reserved → running → settled → delivered → recorded
+//
+// This module is the PURE part of that flow. Given a milestone and its real
+// numbers it produces (a) the plain-language narration line + structured sidecar
+// the client renders, and (b) the cap math that decides the over-cap verdict and
+// the remaining daily headroom the badge shows. No I/O, no Redis, no clock — the
+// caller stamps `ts` and writes the frame — so every branch here is exhaustively
+// unit-testable, and the same builder runs on the server and in the test.
+
+export const HIRE_KIND = 'a2a_hire';
+
+// Ordered phases of a hire, in real timeline order. x402 settles only AFTER the
+// provider's work succeeds (verify → work → settle), so `running` precedes
+// `settled`: the coin animation fires on the real settled frame, never before.
+// The client uses the index to drive its stepper and to drop stale/out-of-order
+// frames on reconnect (it must never paint `settled` after it already showed the
+// terminal receipt of a newer hire).
+export const HIRE_PHASES = [
+ 'discover',
+ 'quote',
+ 'reserved',
+ 'running',
+ 'settled',
+ 'delivered',
+ 'recorded',
+];
+export const HIRE_PHASE_INDEX = Object.fromEntries(HIRE_PHASES.map((p, i) => [p, i]));
+
+// Terminal non-happy phases — rendered as amber/red cards, not steps.
+export const HIRE_ERROR_PHASES = ['over_cap', 'failed'];
+
+const SOLSCAN_TX = 'https://solscan.io/tx/';
+
+// Build a Solana explorer link from a real signature. Returns null for a missing
+// signature so the client renders "pending" instead of a dead link.
+export function explorerTxUrl(sig, network = 'mainnet') {
+ if (!sig || typeof sig !== 'string') return null;
+ const cluster = network === 'devnet' ? '?cluster=devnet' : '';
+ return `${SOLSCAN_TX}${sig}${cluster}`;
+}
+
+// Round to USDC precision (6 decimals) and reject non-finite input.
+function money(n) {
+ const v = Number(n);
+ if (!Number.isFinite(v)) return null;
+ return Math.round(v * 1e6) / 1e6;
+}
+
+// Format a USD amount for narration. Whole-cent values read as $0.04; sub-cent
+// micro-prices keep enough precision to not collapse to $0.00.
+export function fmtUsd(n) {
+ const v = Number(n);
+ if (!Number.isFinite(v)) return '0.00';
+ if (v !== 0 && Math.abs(v) < 0.01) return v.toFixed(4).replace(/0+$/, '').replace(/\.$/, '.0');
+ return v.toFixed(2);
+}
+
+// Cap math: given the hire price and the hiring agent's real limits + prior
+// rolling-24h spend, compute the over-cap verdict and the headroom the badge
+// renders. A null limit means "no ceiling" (not zero); a null result field means
+// "uncapped on that axis". `dailySpentUsd` is the spend BEFORE this hire.
+export function hireCapMath({ usd, maxUsd = null, perTxUsd = null, dailyUsd = null, dailySpentUsd = 0 } = {}) {
+ const EPS = 1e-9;
+ const price = money(usd) ?? 0;
+ const max = money(maxUsd);
+ const perTx = money(perTxUsd);
+ const daily = money(dailyUsd);
+ const spent = money(dailySpentUsd) ?? 0;
+
+ const overMax = max != null && price > max + EPS;
+ const overPerTx = perTx != null && price > perTx + EPS;
+
+ // Effective per-call ceiling shown on the badge = the tightest of the owner's
+ // per-call maxUsd and the agent's policy per-tx limit.
+ let perCallCap = null;
+ if (max != null && perTx != null) perCallCap = Math.min(max, perTx);
+ else if (max != null) perCallCap = max;
+ else if (perTx != null) perCallCap = perTx;
+
+ const dailyRemainingBefore = daily != null ? money(Math.max(0, daily - spent)) : null;
+ const overDaily = daily != null && spent + price > daily + EPS;
+ const dailyRemainingAfter = daily != null ? money(Math.max(0, daily - spent - price)) : null;
+
+ return {
+ price,
+ overCap: overMax || overPerTx || overDaily,
+ overMax,
+ overPerTx,
+ overDaily,
+ perCallCap,
+ dailyUsd: daily,
+ dailySpentUsd: spent,
+ dailyRemainingBefore,
+ dailyRemainingAfter,
+ };
+}
+
+function narration(phase, { skillLabel, provLabel, slug, price, cap, resultSummary, error }) {
+ const capStr = cap?.perCallCap != null ? ` · cap $${fmtUsd(cap.perCallCap)}` : '';
+ switch (phase) {
+ case 'discover':
+ return `Need ${skillLabel} — shopping the offer registry`;
+ case 'quote':
+ return `Quote: ${provLabel} · ${slug} · $${fmtUsd(price)} USDC${capStr}`;
+ case 'reserved':
+ return `Spend reserved within caps — hiring ${provLabel}`;
+ case 'running':
+ return `Running remote skill: ${slug}`;
+ case 'settled':
+ return `Settled $${fmtUsd(price)} USDC to ${provLabel}`;
+ case 'delivered':
+ return `${provLabel} delivered ${skillLabel}${resultSummary ? ` — ${resultSummary}` : ''}`;
+ case 'recorded':
+ return 'On-chain invocation receipt recorded';
+ case 'over_cap':
+ return `Skipped: $${fmtUsd(price)} would exceed the cap${cap?.perCallCap != null ? ` of $${fmtUsd(cap.perCallCap)}` : ''}`;
+ case 'failed':
+ return error
+ ? `Skill failed — no charge (verify-then-settle): ${error}`
+ : 'Skill failed — no charge (verify-then-settle)';
+ default:
+ return `Hire: ${phase}`;
+ }
+}
+
+// Map a real hire milestone to a screen frame the client renders: a plain
+// narration line, the `analysis` frame type, and a structured `meta` sidecar that
+// carries everything the visualizer needs (price, cap, signatures, explorer
+// links). Pure and synchronous — the caller stamps `ts` and writes it.
+export function hirePhaseFrame(phase, ctx = {}) {
+ const {
+ hireId = null,
+ slug = null,
+ skill = null,
+ providerName = null,
+ providerId = null,
+ hirerId = null,
+ hirerName = null,
+ usd,
+ maxUsd = null,
+ network = 'mainnet',
+ cap = null,
+ txSig = null,
+ invocationSig = null,
+ resultSummary = null,
+ error = null,
+ } = ctx;
+
+ const price = money(usd);
+ const skillLabel = skill || slug || 'a skill';
+ const provLabel = providerName || 'a provider';
+ const ok = !HIRE_ERROR_PHASES.includes(phase);
+
+ const meta = {
+ kind: HIRE_KIND,
+ phase,
+ phaseIndex: phase in HIRE_PHASE_INDEX ? HIRE_PHASE_INDEX[phase] : -1,
+ ok,
+ hireId,
+ slug,
+ skill,
+ providerName,
+ providerId,
+ hirerId,
+ hirerName,
+ usd: price,
+ maxUsd: money(maxUsd),
+ cap: cap || null,
+ network,
+ txSig: txSig || null,
+ paymentExplorer: explorerTxUrl(txSig, network),
+ invocationSig: invocationSig || null,
+ invocationExplorer: explorerTxUrl(invocationSig, network),
+ resultSummary: resultSummary || null,
+ error: error || null,
+ };
+
+ const activity = narration(phase, { skillLabel, provLabel, slug, price, cap, resultSummary, error });
+ return { activity, type: 'analysis', meta };
+}
diff --git a/api/_lib/agent-screen-frame.js b/api/_lib/agent-screen-frame.js
new file mode 100644
index 000000000..aeff2bab8
--- /dev/null
+++ b/api/_lib/agent-screen-frame.js
@@ -0,0 +1,81 @@
+// Server-internal screen-frame writer.
+//
+// /api/agent-screen-push is the HTTP path agents use to publish frames. Some
+// first-party flows (the a2a-hire orchestrator) run INSIDE the API and need to
+// publish a frame without a round-trip to themselves — this writes the same
+// Redis records the push endpoint does, so a viewer subscribed to
+// /api/agent-screen-stream receives it identically.
+//
+// Two differences from the HTTP path, both deliberate:
+// • It carries a structured `meta` sidecar on the frame + log entry (the hire
+// visualizer reads it). The HTTP endpoint also accepts `meta` now.
+// • A text/meta-only frame PRESERVES the agent's last screenshot image rather
+// than blanking it: we don't want a hire narration to wipe a live caster's
+// screen. When no prior image exists the frame is image-less (the viewer's
+// hire panel is the content during a hire).
+
+import { getRedis } from './redis.js';
+
+const FRAME_TTL = 90; // seconds — mirrors agent-screen-push.js
+const LOG_CAP = 50;
+const ACTIVITY_MAX = 320;
+const FRAME_TYPES = ['screenshot', 'activity', 'trade', 'analysis'];
+
+// Bound the meta sidecar so a caller can't push an unbounded blob into Redis.
+function safeMeta(meta) {
+ if (!meta || typeof meta !== 'object') return null;
+ try {
+ const s = JSON.stringify(meta);
+ if (s.length > 4000) return null;
+ return JSON.parse(s);
+ } catch {
+ return null;
+ }
+}
+
+// Publish a frame for `agentId` directly to Redis. Returns true when written,
+// false when Redis is unavailable or the input is unusable. Never throws — the
+// caller treats publishing as fire-and-forget and must never let it block real
+// settlement.
+export async function writeScreenFrame(agentId, frame = {}, { nowMs, preserveImage = true } = {}) {
+ const r = getRedis();
+ if (!r || !agentId || typeof agentId !== 'string') return false;
+
+ const now = nowMs || Date.now();
+ const activity = String(frame.activity || '').slice(0, ACTIVITY_MAX);
+ const type = FRAME_TYPES.includes(frame.type) ? frame.type : 'activity';
+ const meta = safeMeta(frame.meta);
+
+ const frameKey = `agent:screen:${agentId}:frame`;
+ const logKey = `agent:screen:${agentId}:log`;
+
+ // Preserve the agent's last screenshot when this frame carries no image, so a
+ // text/meta narration never blanks a live caster's screen.
+ let data = typeof frame.data === 'string' ? frame.data : null;
+ if (!data && preserveImage) {
+ try {
+ const prevRaw = await r.get(frameKey);
+ const prev = prevRaw ? (typeof prevRaw === 'string' ? JSON.parse(prevRaw) : prevRaw) : null;
+ if (prev?.data) data = prev.data;
+ } catch {
+ /* no prior frame — fine, publish image-less */
+ }
+ }
+
+ const frameRecord = JSON.stringify({ ts: now, data, activity, type, meta, agentId });
+ const logEntry = JSON.stringify({ ts: now, activity, type, meta });
+
+ try {
+ await Promise.all([
+ r.set(frameKey, frameRecord, { ex: FRAME_TTL }),
+ r.lpush(logKey, logEntry).then(() => r.ltrim(logKey, 0, LOG_CAP - 1)),
+ r.expire(logKey, FRAME_TTL * 5),
+ r.zadd('agent:screen:active', { score: now, member: agentId }),
+ r.zremrangebyscore('agent:screen:active', 0, now - 120_000),
+ r.expire('agent:screen:active', FRAME_TTL * 3),
+ ]);
+ return true;
+ } catch {
+ return false;
+ }
+}
diff --git a/api/_lib/pump-vanity.js b/api/_lib/pump-vanity.js
index 8a50b76ab..3c4c08046 100644
--- a/api/_lib/pump-vanity.js
+++ b/api/_lib/pump-vanity.js
@@ -15,6 +15,11 @@ const BASE58_CHARS = new Set(BASE58_ALPHABET);
const MAX_PATTERN_LENGTH = 6;
const DEFAULT_MAX_ITERATIONS = 2_000_000;
const YIELD_EVERY = 10_000;
+// How often (in attempts) onProgress fires. Aligned to a yield boundary so a
+// sample is emitted right after the loop hands control back to the event loop —
+// the live grind runner turns each sample into one screen frame, then throttles
+// its own pushes (~4/sec) to respect the frame TTL and Redis quota.
+const PROGRESS_EVERY = 25_000;
// Wall-clock deadline is checked more often than we yield so a maxMs budget
// overshoots by at most ~this-many keypairs (a fraction of a second) instead of
// a full YIELD_EVERY block — keeps a serverless grind well inside maxDuration.
@@ -96,7 +101,10 @@ export function estimateAttempts({ prefix, suffix, ignoreCase = false } = {}) {
* @param {number} [opts.maxMs] — wall-clock budget in ms (default Infinity). Bails
* with a `vanity_timeout` error before this elapses so a serverless invocation
* returns a clean 504 instead of being hard-killed by the platform's runtime limit.
- * @param {(attempts:number,rate:number)=>void} [opts.onProgress] — every 1k attempts
+ * @param {(sample:{iterations:number,elapsedMs:number,attemptsPerSec:number,sampleAddress:string})=>void} [opts.onProgress]
+ * — fired every PROGRESS_EVERY (25k) attempts with real, monotonic numbers. iterations
+ * and elapsedMs only ever increase; attemptsPerSec is the instantaneous windowed rate;
+ * sampleAddress is the actual candidate just generated (for on-screen texture).
* @returns {Promise<{ keypair: Keypair, iterations: number, durationMs: number }>}
*/
export async function grindMintKeypair({
@@ -106,6 +114,7 @@ export async function grindMintKeypair({
maxIterations = DEFAULT_MAX_ITERATIONS,
maxMs = Infinity,
onProgress,
+ progressEvery = PROGRESS_EVERY,
} = {}) {
if (!prefix && !suffix) {
const kp = Keypair.generate();
@@ -113,6 +122,7 @@ export async function grindMintKeypair({
}
if (prefix) validatePattern(prefix, 'prefix');
if (suffix) validatePattern(suffix, 'suffix');
+ const sampleEvery = Math.max(1, Math.floor(progressEvery) || PROGRESS_EVERY);
const targetPrefix = prefix ? (ignoreCase ? prefix.toLowerCase() : prefix) : null;
const targetSuffix = suffix ? (ignoreCase ? suffix.toLowerCase() : suffix) : null;
@@ -141,6 +151,24 @@ export async function grindMintKeypair({
const kp = Keypair.generate();
const addr = kp.publicKey.toBase58();
+ // Emit a live progress sample from real numbers. attemptsPerSec is the
+ // instantaneous rate over the window since the previous sample, never a
+ // synthetic counter. sampleAddress is the actual candidate just generated,
+ // surfaced purely for on-screen texture (the "almost right" flicker).
+ if (onProgress && i % sampleEvery === 0) {
+ const now = Date.now();
+ const windowMs = now - lastProgressAt;
+ const windowAttempts = i - lastProgressAttempts;
+ const attemptsPerSec = windowMs > 0 ? (windowAttempts / windowMs) * 1000 : 0;
+ lastProgressAt = now;
+ lastProgressAttempts = i;
+ try {
+ onProgress({ iterations: i, elapsedMs: now - start, attemptsPerSec, sampleAddress: addr });
+ } catch {
+ // A misbehaving progress sink must never abort a paid grind.
+ }
+ }
+
const head = ignoreCase ? addr.substring(0, pLen).toLowerCase() : addr.substring(0, pLen);
if (targetPrefix && head !== targetPrefix) {
if (i % YIELD_EVERY === 0) await new Promise((r) => setImmediate(r));
diff --git a/api/_lib/vanity-frame.js b/api/_lib/vanity-frame.js
new file mode 100644
index 000000000..1b30b299a
--- /dev/null
+++ b/api/_lib/vanity-frame.js
@@ -0,0 +1,195 @@
+// Server-side frame renderer for the live Vanity Address Miner (feature #11).
+//
+// Each progress sample from the real grind is turned into one PNG frame here
+// (SVG → PNG via sharp, already a project dependency) and pushed to
+// /api/agent-screen-push, which the agent-screen canvas renders live. There is
+// no browser/canvas in this path — keys never touch a client — so the visual is
+// composed as SVG and rasterised on the server.
+//
+// Two frame kinds:
+// renderGrindFrame — the spinning keyspace counter + attempts/sec + the
+// expected-iterations probability ring + flickering
+// candidate addresses (the suspense state).
+// renderRevealFrame — the MATCH moment: the winning PUBLIC address resolving
+// character-by-character (the secret is NEVER rendered).
+
+import sharp from 'sharp';
+import { abbrev } from './vanity-grind-stats.js';
+
+const W = 1280;
+const H = 720;
+const BG = '#080a0f';
+const ACCENT = '#5eead4'; // teal — the brand grind colour
+const DIM = '#3a4150';
+const TEXT = '#e7ecf3';
+
+// Escape the handful of chars that would break out of SVG text/attribute context.
+function esc(s) {
+ return String(s == null ? '' : s)
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;');
+}
+
+// Deterministic pseudo-random in [0,1) from an integer seed — used only for the
+// cosmetic flicker of candidate rows, never for any key material. No Math.random
+// (kept reproducible so identical state renders an identical frame).
+function jitter(seed) {
+ const x = Math.sin(seed * 12.9898) * 43758.5453;
+ return x - Math.floor(x);
+}
+
+// A circular progress ring (probability-of-completion indicator). progress is
+// clamped 0..1 by the caller; we draw the swept arc plus a soft track.
+function ringSvg(cx, cy, r, progress, color) {
+ const p = Math.max(0, Math.min(1, progress));
+ const C = 2 * Math.PI * r;
+ const dash = C * p;
+ return (
+ `<circle cx="${cx}" cy="${cy}" r="${r}" fill="none" stroke="${DIM}" stroke-width="10" opacity="0.5"/>` +
+ `<circle cx="${cx}" cy="${cy}" r="${r}" fill="none" stroke="${color}" stroke-width="10" ` +
+ `stroke-linecap="round" stroke-dasharray="${dash.toFixed(1)} ${(C - dash).toFixed(1)}" ` +
+ `transform="rotate(-90 ${cx} ${cy})"/>`
+ );
+}
+
+async function svgToDataUrl(svg) {
+ const png = await sharp(Buffer.from(svg)).png({ compressionLevel: 6 }).toBuffer();
+ return `data:image/png;base64,${png.toString('base64')}`;
+}
+
+/**
+ * The suspense / populated state.
+ * @param {object} s
+ * @param {string} s.prefix
+ * @param {string} [s.suffix]
+ * @param {number} s.iterations
+ * @param {number} s.attemptsPerSec
+ * @param {number} s.expectedIterations
+ * @param {number} s.progress 0..1 probability indicator
+ * @param {number|null} [s.etaSec]
+ * @param {string[]} [s.candidates] recent candidate addresses for texture
+ * @param {string} [s.agentName]
+ * @returns {Promise<string>} PNG data URL
+ */
+export async function renderGrindFrame(s) {
+ const prefix = esc(s.prefix || '');
+ const suffix = s.suffix ? esc(s.suffix) : '';
+ const pattern = suffix ? `${prefix}…${suffix}` : `${prefix}…`;
+ const iters = abbrev(s.iterations);
+ const rate = abbrev(s.attemptsPerSec);
+ const expected = abbrev(s.expectedIterations);
+ const pct = Math.round(Math.max(0, Math.min(1, s.progress || 0)) * 100);
+ const eta = s.etaSec != null && Number.isFinite(s.etaSec)
+ ? (s.etaSec >= 60 ? `~${Math.round(s.etaSec / 60)}m to expectation` : `~${Math.round(s.etaSec)}s to expectation`)
+ : 'past expectation — still searching';
+
+ // Flickering candidate rows: real recent candidate addresses, each with the
+ // matched-so-far head tinted and the rest dimmed, jittering position.
+ const candidates = (s.candidates || []).slice(-6);
+ const rows = candidates
+ .map((addr, idx) => {
+ const y = 360 + idx * 40;
+ const dx = (jitter(s.iterations + idx) - 0.5) * 8;
+ const head = esc(addr.slice(0, Math.max(1, prefix.length)));
+ const rest = esc(addr.slice(Math.max(1, prefix.length), 28));
+ const op = 0.28 + idx * 0.1;
+ return (
+ `<text x="${90 + dx}" y="${y}" font-family="monospace" font-size="22" opacity="${op}">` +
+ `<tspan fill="${ACCENT}">${head}</tspan><tspan fill="${DIM}">${rest}…</tspan></text>`
+ );
+ })
+ .join('');
+
+ const ringCx = 1030;
+ const ringCy = 360;
+ const ringR = 150;
+
+ const svg =
+ `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">` +
+ `<defs><linearGradient id="g" x1="0" y1="0" x2="1" y2="1">` +
+ `<stop offset="0" stop-color="#0b0f17"/><stop offset="1" stop-color="#080a0f"/></linearGradient></defs>` +
+ `<rect width="${W}" height="${H}" fill="url(#g)"/>` +
+ // header
+ `<text x="90" y="120" font-family="monospace" font-size="20" fill="${DIM}" letter-spacing="3">VANITY GRINDER</text>` +
+ `<text x="90" y="180" font-family="monospace" font-size="56" fill="${TEXT}">grinding <tspan fill="${ACCENT}">${pattern}</tspan></text>` +
+ // big live counter
+ `<text x="90" y="280" font-family="monospace" font-size="84" font-weight="bold" fill="${TEXT}">${iters}</text>` +
+ `<text x="90" y="320" font-family="monospace" font-size="26" fill="${ACCENT}">${rate}/sec · expected ~${expected}</text>` +
+ // candidate flicker
+ rows +
+ // ring + labels
+ ringSvg(ringCx, ringCy, ringR, s.progress || 0, ACCENT) +
+ `<text x="${ringCx}" y="${ringCy - 6}" text-anchor="middle" font-family="monospace" font-size="52" font-weight="bold" fill="${TEXT}">${pct}%</text>` +
+ `<text x="${ringCx}" y="${ringCy + 34}" text-anchor="middle" font-family="monospace" font-size="18" fill="${DIM}">of expected</text>` +
+ `<text x="${ringCx}" y="${ringCy + ringR + 50}" text-anchor="middle" font-family="monospace" font-size="18" fill="${DIM}">${esc(eta)}</text>` +
+ // footer
+ `<text x="90" y="660" font-family="monospace" font-size="18" fill="${DIM}">${esc(s.agentName || 'agent')} · real ed25519 keyspace search — every number is a real attempt</text>` +
+ `</svg>`;
+
+ return svgToDataUrl(svg);
+}
+
+/**
+ * The MATCH reveal. Renders the winning PUBLIC address with `revealed` leading
+ * characters resolved and the remainder still scrambling. The secret key is
+ * never passed in here and never rendered.
+ * @param {object} s
+ * @param {string} s.address full winning PUBLIC base58 address
+ * @param {number} s.revealed how many leading chars are resolved (0..len)
+ * @param {string} s.prefix
+ * @param {number} s.iterations
+ * @param {string} [s.agentName]
+ * @returns {Promise<string>} PNG data URL
+ */
+export async function renderRevealFrame(s) {
+ const addr = String(s.address || '');
+ const revealed = Math.max(0, Math.min(addr.length, s.revealed ?? addr.length));
+ const done = revealed >= addr.length;
+ const iters = abbrev(s.iterations);
+
+ // Build the address line: resolved chars in accent, the still-scrambling tail
+ // from the base58 alphabet (deterministic per position, cosmetic only).
+ const scrambleSrc = '123456789ABCDEFGHJKLMNPQRSTUVWXYZabcdefghijkmnopqrstuvwxyz';
+ let line = '';
+ for (let i = 0; i < addr.length; i++) {
+ if (i < revealed) {
+ line += `<tspan fill="${ACCENT}">${esc(addr[i])}</tspan>`;
+ } else {
+ const c = scrambleSrc[Math.floor(jitter(s.iterations + i * 7) * scrambleSrc.length)] || '?';
+ line += `<tspan fill="${DIM}">${esc(c)}</tspan>`;
+ }
+ }
+
+ const svg =
+ `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">` +
+ `<rect width="${W}" height="${H}" fill="${BG}"/>` +
+ `<rect x="0" y="0" width="${W}" height="${H}" fill="none" stroke="${ACCENT}" stroke-width="3" opacity="${done ? 0.9 : 0.35}"/>` +
+ `<text x="${W / 2}" y="220" text-anchor="middle" font-family="monospace" font-size="40" letter-spacing="8" fill="${ACCENT}">${done ? 'MATCH' : 'RESOLVING…'}</text>` +
+ `<text x="${W / 2}" y="370" text-anchor="middle" font-family="monospace" font-size="34" fill="${TEXT}">${line}</text>` +
+ `<text x="${W / 2}" y="470" text-anchor="middle" font-family="monospace" font-size="22" fill="${DIM}">found in ${iters} real attempts</text>` +
+ (done
+ ? `<text x="${W / 2}" y="540" text-anchor="middle" font-family="monospace" font-size="20" fill="${ACCENT}">a real, usable branded wallet — secret delivered privately to the owner</text>`
+ : '') +
+ `<text x="${W / 2}" y="660" text-anchor="middle" font-family="monospace" font-size="16" fill="${DIM}">${esc(s.agentName || 'agent')} · vanity grinder</text>` +
+ `</svg>`;
+
+ return svgToDataUrl(svg);
+}
+
+// Loading / spin-up state shown before the first real sample arrives.
+export async function renderSpinupFrame(s) {
+ const prefix = esc(s.prefix || '');
+ const suffix = s.suffix ? esc(s.suffix) : '';
+ const pattern = suffix ? `${prefix}…${suffix}` : `${prefix}…`;
+ const expected = abbrev(s.expectedIterations || 0);
+ const svg =
+ `<svg xmlns="http://www.w3.org/2000/svg" width="${W}" height="${H}" viewBox="0 0 ${W} ${H}">` +
+ `<rect width="${W}" height="${H}" fill="${BG}"/>` +
+ `<text x="${W / 2}" y="320" text-anchor="middle" font-family="monospace" font-size="34" fill="${TEXT}">Spinning up the grinder…</text>` +
+ `<text x="${W / 2}" y="380" text-anchor="middle" font-family="monospace" font-size="26" fill="${ACCENT}">target ${pattern}</text>` +
+ `<text x="${W / 2}" y="430" text-anchor="middle" font-family="monospace" font-size="20" fill="${DIM}">expected ~${expected} attempts</text>` +
+ `</svg>`;
+ return svgToDataUrl(svg);
+}
diff --git a/api/_lib/vanity-grind-stats.js b/api/_lib/vanity-grind-stats.js
new file mode 100644
index 000000000..768d1b340
--- /dev/null
+++ b/api/_lib/vanity-grind-stats.js
@@ -0,0 +1,80 @@
+// Pure transform for the live Vanity Address Miner (feature #11).
+//
+// Turns the real grind numbers (iterations, elapsedMs) emitted by
+// grindMintKeypair's onProgress callback into the stats the agent-screen frame
+// renders: instantaneous attempts/sec, the statistically-expected attempt count
+// for the requested pattern, and a probability-of-completion progress value.
+//
+// Every value derives from real iteration counts — there is no synthetic
+// counter anywhere. `progress` is explicitly a probability indicator (clamped to
+// 1), never a guaranteed completion bar: a grind can land before or well after
+// its expected attempt count.
+
+import { estimateAttempts } from './pump-vanity.js';
+
+/**
+ * @param {object} p
+ * @param {number} p.iterations — current real attempt count
+ * @param {number} p.elapsedMs — ms since the grind started
+ * @param {number} [p.prevIterations] — attempt count at the previous sample
+ * @param {number} [p.prevElapsedMs] — elapsedMs at the previous sample
+ * @param {string} [p.prefix]
+ * @param {string} [p.suffix]
+ * @param {boolean} [p.ignoreCase]
+ * @returns {{ attemptsPerSec:number, expectedIterations:number, progress:number, etaSec:number|null }}
+ */
+export function computeGrindStats({
+ iterations,
+ elapsedMs,
+ prevIterations = 0,
+ prevElapsedMs = 0,
+ prefix = '',
+ suffix = '',
+ ignoreCase = false,
+} = {}) {
+ const iters = Math.max(0, Number(iterations) || 0);
+ const elapsed = Math.max(0, Number(elapsedMs) || 0);
+
+ // Instantaneous rate over the window since the previous sample. Falls back to
+ // the cumulative average when there is no prior sample (or a zero window), so
+ // the first frame still shows a real number instead of 0.
+ const windowIters = iters - (Number(prevIterations) || 0);
+ const windowMs = elapsed - (Number(prevElapsedMs) || 0);
+ let attemptsPerSec;
+ if (windowMs > 0 && windowIters > 0) {
+ attemptsPerSec = (windowIters / windowMs) * 1000;
+ } else if (elapsed > 0) {
+ attemptsPerSec = (iters / elapsed) * 1000;
+ } else {
+ attemptsPerSec = 0;
+ }
+
+ const expectedIterations = Math.round(estimateAttempts({ prefix, suffix, ignoreCase }));
+ const progress = expectedIterations > 0 ? Math.min(1, iters / expectedIterations) : 0;
+
+ // ETA to the statistical expectation, in seconds, from the live rate. Null
+ // once we're already past expectation (the search is "overdue" — still real,
+ // just unlucky) or before we have a rate.
+ let etaSec = null;
+ if (attemptsPerSec > 0 && iters < expectedIterations) {
+ etaSec = (expectedIterations - iters) / attemptsPerSec;
+ }
+
+ return { attemptsPerSec, expectedIterations, progress, etaSec };
+}
+
+/**
+ * Compact one-line activity string for the screen log + the agents-live card
+ * ticker, e.g. "4.18M attempts · 38.9k/sec · expected ~11.3M". Pure formatting.
+ */
+export function formatGrindActivity({ iterations, attemptsPerSec, expectedIterations }) {
+ return `${abbrev(iterations)} attempts · ${abbrev(attemptsPerSec)}/sec · expected ~${abbrev(expectedIterations)}`;
+}
+
+// 4_182_330 → "4.18M", 38_900 → "38.9k", 420 → "420".
+export function abbrev(n) {
+ const v = Math.max(0, Number(n) || 0);
+ if (v >= 1_000_000) return `${(v / 1_000_000).toFixed(2).replace(/\.?0+$/, '')}M`;
+ if (v >= 1_000) return `${(v / 1_000).toFixed(1).replace(/\.0$/, '')}k`;
+ return String(Math.round(v));
+}
diff --git a/api/agent-screen-push.js b/api/agent-screen-push.js
index 3084f6a00..1477c6828 100644
--- a/api/agent-screen-push.js
+++ b/api/agent-screen-push.js
@@ -25,6 +25,7 @@ import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.j
import { limits, clientIp } from './_lib/rate-limit.js';
import { getRedis } from './_lib/redis.js';
import { sql } from './_lib/db.js';
+import { sanitizeFrameMeta } from '../src/shared/forge-frames.js';
// First-party on-demand caster pool (workers/agent-screen-pool) authenticates
// with a single shared secret and may push frames for ANY agent — it casts
@@ -52,6 +53,22 @@ export function isRasterDataUrl(s) {
return typeof s === 'string' && RASTER_DATA_URL.test(s);
}
+// Whitelist + coerce a trade PnL ride-along payload. Keeps only known fields,
+// drops non-finite numbers, and bounds the strings so an agent can't smuggle
+// arbitrary data through the frame's `pnl` slot. Returns null when unusable.
+const PNL_PHASES = ['scored', 'buy', 'hold', 'exit'];
+export function sanitizePnl(pnl) {
+ if (!pnl || typeof pnl !== 'object' || !PNL_PHASES.includes(pnl.phase)) return null;
+ const out = { phase: pnl.phase };
+ if (typeof pnl.mint === 'string') out.mint = pnl.mint.slice(0, 64);
+ if (typeof pnl.symbol === 'string') out.symbol = pnl.symbol.slice(0, 32);
+ for (const k of ['solDelta', 'pct', 'realizedUsd', 'unrealizedUsd']) {
+ const n = Number(pnl[k]);
+ if (Number.isFinite(n)) out[k] = n;
+ }
+ return out;
+}
+
export default async function handleAgentScreenPush(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
if (!method(req, res, ['POST'])) return;
@@ -101,6 +118,16 @@ export default async function handleAgentScreenPush(req, res) {
? frame.type : 'activity';
const sliced = typeof frame.data === 'string' ? frame.data.slice(0, DATA_MAX) : null;
const data = sliced && isRasterDataUrl(sliced) ? sliced : null;
+ // Optional structured PnL ride-along on 'trade' frames (Live Trading Desk).
+ // Drives the viewer's PnL ticker + avatar emote; sanitized so a malformed
+ // push can't poison the stream. Persisted on the frame AND the log entry so
+ // the ticker survives a reconnect's backfill.
+ const pnl = sanitizePnl(frame.pnl);
+ // Optional forge sidecar on the final 'analysis' frame of a Live Avatar Forge
+ // run: carries the durable GLB url + viewer link so every connected viewer can
+ // load and animate the freshly-forged avatar. Sanitized + http(s)-gated so a
+ // push can't smuggle a junk or javascript: url to the viewer's loader.
+ const meta = sanitizeFrameMeta(frame.meta);
// Ownership: the pool worker may cast any existing agent; owners are limited
// to their own agents.
@@ -117,10 +144,10 @@ export default async function handleAgentScreenPush(req, res) {
const logKey = `agent:screen:${agentId}:log`;
// Full frame record (includes image data when present)
- const frameRecord = JSON.stringify({ ts: now, data, activity, type, agentId });
+ const frameRecord = JSON.stringify({ ts: now, data, activity, type, agentId, ...(pnl ? { pnl } : {}), ...(meta ? { meta } : {}) });
// Log entry (no image — the activity log only needs text + metadata)
- const logEntry = JSON.stringify({ ts: now, activity, type });
+ const logEntry = JSON.stringify({ ts: now, activity, type, ...(pnl ? { pnl } : {}), ...(meta ? { meta } : {}) });
await Promise.all([
r.set(frameKey, frameRecord, { ex: FRAME_TTL }),
diff --git a/api/agent/anchor-script.js b/api/agent/anchor-script.js
new file mode 100644
index 000000000..f2462aaa8
--- /dev/null
+++ b/api/agent/anchor-script.js
@@ -0,0 +1,119 @@
+// /api/agent/anchor-script — the Newsroom Anchor's spoken script store.
+//
+// GET ?agentId=<uuid> → { ok, script: { ts, headline, body, offline } | null }
+// POST { agentId, headline, body, offline? } → { ok, ts }
+//
+// The anchor worker (workers/agent-anchor) scripts each bulletin and POSTs the
+// spoken body here; viewers' browsers GET it (after a type:'analysis' screen
+// frame arrives) to synthesize speech + lip-sync. The headline rides in the
+// frame's `activity`; the (longer) spoken body lives here so it isn't bound by
+// the frame's 320-char activity cap.
+//
+// Storage: Redis key agent:anchor:{agentId}:script (TTL 180s — a little over two
+// 90s cadence ticks, so a freshly-arrived frame always has a script to fetch,
+// and a stopped anchor's script expires on its own).
+//
+// Auth: GET is public (the stream it pairs with is public). POST requires the
+// agent's bearer JWT / owner session, or the first-party screen-pool secret —
+// the same authorization model as /api/agent-screen-push.
+
+import { timingSafeEqual } from 'node:crypto';
+import { cors, json, method, error, readJson, wrap, rateLimited } from '../_lib/http.js';
+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { getRedis } from '../_lib/redis.js';
+import { isUuid } from '../_lib/validate.js';
+import { sql } from '../_lib/db.js';
+
+const SCRIPT_TTL = 180; // seconds
+const HEADLINE_MAX = 320;
+const BODY_MAX = 4096;
+
+const WORKER_SECRET = process.env.SCREEN_WORKER_SECRET || '';
+function isPoolWorker(bearer) {
+ if (!bearer || !WORKER_SECRET || WORKER_SECRET.length < 16) return false;
+ const a = Buffer.from(bearer);
+ const b = Buffer.from(WORKER_SECRET);
+ return a.length === b.length && timingSafeEqual(a, b);
+}
+
+const scriptKey = (agentId) => `agent:anchor:${agentId}:script`;
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const r = getRedis();
+
+ // ── GET: read the current script ─────────────────────────────────────────
+ if (req.method === 'GET') {
+ const rl = await limits.apiIp(clientIp(req), { limit: 240, window: '60s' });
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, `http://${req.headers.host || 'x'}`);
+ const agentId = (url.searchParams.get('agentId') || '').trim();
+ if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'valid agentId required');
+ if (!r) return json(res, 200, { ok: true, script: null });
+
+ let script = null;
+ try {
+ const raw = await r.get(scriptKey(agentId));
+ if (raw) script = typeof raw === 'string' ? JSON.parse(raw) : raw;
+ } catch { /* treat a Redis blip as "no script yet" */ }
+ return json(res, 200, { ok: true, script }, { 'cache-control': 'no-store' });
+ }
+
+ // ── POST: store the latest script ────────────────────────────────────────
+ const rl = await limits.apiIp(clientIp(req), { limit: 120, window: '60s' });
+ if (!rl.success) return rateLimited(res, rl);
+
+ let userId = null;
+ let isWorker = false;
+ const bearer = extractBearer(req);
+ if (isPoolWorker(bearer)) {
+ isWorker = true;
+ } else {
+ if (bearer) {
+ const auth = await authenticateBearer(bearer).catch(() => null);
+ if (auth?.userId) userId = auth.userId;
+ }
+ if (!userId) {
+ const auth = await getSessionUser(req, res);
+ if (auth?.id) userId = auth.id;
+ }
+ if (!userId) return error(res, 401, 'unauthorized', 'authentication required');
+ }
+
+ const body = await readJson(req, 12_000).catch(() => null);
+ if (!body || typeof body !== 'object') return error(res, 400, 'invalid_body', 'JSON body required');
+
+ const agentId = typeof body.agentId === 'string' ? body.agentId.trim() : '';
+ if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'valid agentId required');
+
+ const headline = String(body.headline || '').slice(0, HEADLINE_MAX).trim();
+ const speakBody = String(body.body || '').slice(0, BODY_MAX).trim();
+ if (!headline && !speakBody) return error(res, 400, 'validation_error', 'headline or body required');
+ const offline = Array.isArray(body.offline)
+ ? body.offline.filter((x) => typeof x === 'string').slice(0, 8)
+ : [];
+
+ // Ownership: workers (shared secret) may write any agent; owners only their own.
+ const [agentRow] = isWorker
+ ? await sql`SELECT id FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL LIMIT 1`
+ : await sql`SELECT id FROM agent_identities WHERE id = ${agentId} AND user_id = ${userId} LIMIT 1`;
+ if (!agentRow) {
+ return error(res, isWorker ? 404 : 403, isWorker ? 'not_found' : 'forbidden',
+ isWorker ? 'agent not found' : 'agent not owned by this user');
+ }
+
+ if (!r) return error(res, 503, 'redis_unavailable', 'script store offline');
+
+ const now = Date.now();
+ const record = JSON.stringify({ ts: now, headline, body: speakBody, offline, agentId });
+ try {
+ await r.set(scriptKey(agentId), record, { ex: SCRIPT_TTL });
+ } catch {
+ return error(res, 503, 'redis_unavailable', 'could not store script');
+ }
+ return json(res, 200, { ok: true, ts: now });
+});
diff --git a/api/agent/watch-status.js b/api/agent/watch-status.js
new file mode 100644
index 000000000..4f5e3714e
--- /dev/null
+++ b/api/agent/watch-status.js
@@ -0,0 +1,81 @@
+// GET /api/agent/watch-status?agentId=<uuid> → { state, position?, max }
+//
+// Resolves, from Redis ALONE (no DB), where a single agent sits in the on-demand
+// caster pipeline so the live wall can show an honest handoff between the
+// zero-cost activity terminal and real browser pixels:
+//
+// • casting — a real frame exists (a Playwright caster is pushing pixels now).
+// • warming — the agent is inside the watch window AND the pool has free
+// capacity, so a browser is (or is about to be) spinning up for it.
+// • queued — the agent is wanted but the pool is at MAX_BROWSERS; we return a
+// 1-based queue position so the card can say "#N in line".
+// • activity — not wanted, or Redis is off: the always-available activity view
+// stays, and we never claim a live state without a real frame.
+//
+// The wall fetches this on mount and refreshes it only while a card is
+// warming/queued — never once it's casting (frames drive that), so steady-state
+// adds no per-frame load. Public + per-IP rate-limited like watch-intent.
+//
+// SCREEN_POOL_MAX must mirror the pool worker's MAX_BROWSERS (default 6) for the
+// queue math to be accurate — the worker casts the first MAX_BROWSERS wanted
+// agents in recency order, exactly the ordering ZREVRANK reflects here.
+
+import { cors, json, method, error, wrap, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { getRedis } from '../_lib/redis.js';
+import { isUuid } from '../_lib/validate.js';
+
+export const WANTED_KEY = 'screen:wanted';
+const WINDOW_MS = 90_000; // mirrors watch-wanted: agents wanted within 90s are live-watched
+// Read-only mirror of the worker's MAX_BROWSERS. Display/queue-math only — the
+// worker reads its own env; this never casts, it only reports position.
+export const POOL_MAX = Math.max(1, Number(process.env.SCREEN_POOL_MAX) || 6);
+
+// Pure queue-math seam (unit-tested): given an agent's reverse-rank in the wanted
+// set (0 = most-recently-wanted) and the pool size, classify its handoff state.
+// Ranks 0..max-1 are within casting capacity (warming); the rest queue, 1-based.
+export function classifyRank(rank, max = POOL_MAX) {
+ if (rank == null || rank < 0) return { state: 'activity' };
+ if (rank < max) return { state: 'warming' };
+ return { state: 'queued', position: rank - max + 1 };
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ // High-frequency status poll: bound per-IP, enforced per-instance (local) so a
+ // poll flood can't drain the Upstash quota the wall's economics depend on.
+ const rl = await limits.apiIp(clientIp(req), { limit: 300, window: '60s', local: true });
+ if (!rl.success) return rateLimited(res, rl);
+
+ const url = new URL(req.url, 'http://x');
+ const agentId = (url.searchParams.get('agentId') || '').trim();
+ if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'valid agentId required');
+
+ const r = getRedis();
+ // No Redis → the activity view is the honest state; never fake a live handoff.
+ if (!r) return json(res, 200, { state: 'activity', max: POOL_MAX }, { 'cache-control': 'no-store' });
+
+ try {
+ // A live frame outranks everything: if pixels exist, we're casting.
+ const hasFrame = await r.exists(`agent:screen:${agentId}:frame`);
+ if (hasFrame) return json(res, 200, { state: 'casting', max: POOL_MAX }, { 'cache-control': 'no-store' });
+
+ // Otherwise place the agent in the wanted ordering. Stale members (older than
+ // the window) carry lower scores and rank BELOW every in-window member, so a
+ // fresh agent's reverse-rank equals its position among currently-wanted
+ // agents — the same set, in the same order, the worker casts from.
+ const [score, rank] = await Promise.all([
+ r.zscore(WANTED_KEY, agentId),
+ r.zrevrank(WANTED_KEY, agentId),
+ ]);
+ const fresh = score != null && Date.now() - Number(score) <= WINDOW_MS;
+ if (!fresh) return json(res, 200, { state: 'activity', max: POOL_MAX }, { 'cache-control': 'no-store' });
+
+ return json(res, 200, { ...classifyRank(rank, POOL_MAX), max: POOL_MAX }, { 'cache-control': 'no-store' });
+ } catch {
+ // Redis blip — degrade to the always-available activity view, never an error.
+ return json(res, 200, { state: 'activity', max: POOL_MAX }, { 'cache-control': 'no-store' });
+ }
+});
diff --git a/api/agents/a2a-hire.js b/api/agents/a2a-hire.js
index ad855ebd5..11164bf10 100644
--- a/api/agents/a2a-hire.js
+++ b/api/agents/a2a-hire.js
@@ -36,7 +36,10 @@ import {
releaseSpendReservation,
updateCustodyEvent,
recordCustodyEvent,
+ getSpendLimits,
} from '../_lib/agent-trade-guards.js';
+import { writeScreenFrame } from '../_lib/agent-screen-frame.js';
+import { hirePhaseFrame, hireCapMath } from '../_lib/a2a-hire-phases.js';
import { payExternalX402, resolveSpendEnabled } from '../_lib/x402-user-payer.js';
import { serviceResourceUrl } from '../_lib/agent-paid-services.js';
import { recoverSolanaAgentKeypair } from '../_lib/agent-wallet.js';
@@ -107,6 +110,42 @@ export default wrap(async (req, res) => {
return error(res, 409, 'no_wallet', 'this agent has no Solana wallet provisioned to pay from');
}
+ // ── Live hire visualizer: push one screen frame per real milestone ──────
+ // Viewers on /agent-screen?agentId=<hirer> watch this hire happen. Every push
+ // is fire-and-forget and isolated in its own try/catch by writeScreenFrame —
+ // a frame write must NEVER block or fail a real settlement.
+ let hireRow = null;
+ let baseCtx = {}; // filled once the offer resolves; merged into every phase
+ const limits = getSpendLimits(hirer.meta);
+ const pushPhase = (phase, extra = {}) => {
+ const frame = hirePhaseFrame(phase, {
+ ...baseCtx,
+ hireId: hireRow?.id ?? null,
+ hirerId: hirerAgentId,
+ hirerName: hirer.name || null,
+ ...extra,
+ });
+ writeScreenFrame(hirerAgentId, frame).catch(() => {});
+ };
+ // Build the badge cap object from the agent's real spend policy.
+ const capBadge = (dailySpentUsd, priceUsd) => {
+ const m = hireCapMath({
+ usd: priceUsd,
+ maxUsd: typeof maxUsd === 'number' ? maxUsd : null,
+ perTxUsd: limits.per_tx_usd,
+ dailyUsd: limits.daily_usd,
+ dailySpentUsd,
+ });
+ return {
+ perCallCap: m.perCallCap,
+ dailyUsd: m.dailyUsd,
+ dailyRemaining: dailySpentUsd != null ? m.dailyRemainingAfter : m.dailyRemainingBefore,
+ overCap: m.overCap,
+ };
+ };
+
+ pushPhase('discover', { slug: serviceSlug });
+
// ── Resolve the provider's offer ────────────────────────────────────────
const offer = await getOfferBySlug(serviceSlug);
if (!offer) return error(res, 404, 'offer_not_found', `no service offer at ${serviceSlug}`);
@@ -121,8 +160,22 @@ export default wrap(async (req, res) => {
const usd = atomicsToUsdc(offer.price_atomics);
const priceNetwork = offer.network === 'solana' ? 'solana' : 'base';
+ // The hire settles USDC on Solana mainnet; explorer links default to that
+ // cluster. Provider/price context is now known — every later phase carries it.
+ baseCtx = {
+ slug: offer.slug,
+ skill: offer.name,
+ providerName: offer.provider.name || null,
+ providerId: offer.provider.id,
+ usd,
+ maxUsd: typeof maxUsd === 'number' ? maxUsd : null,
+ network: 'mainnet',
+ };
+ pushPhase('quote', { cap: capBadge(null, usd) });
+
// Owner-set per-call ceiling for this hire (can only lower the price gate).
if (typeof maxUsd === 'number' && Number.isFinite(maxUsd) && usd > maxUsd + 1e-9) {
+ pushPhase('over_cap', { cap: capBadge(null, usd) });
return error(res, 402, 'over_cap', `this service costs $${usd.toFixed(2)}, above your $${maxUsd.toFixed(2)} per-call limit`, {
price_usd: usd,
max_usd: maxUsd,
@@ -134,7 +187,6 @@ export default wrap(async (req, res) => {
}
// ── Idempotency: never double-charge a retried hire ─────────────────────
- let hireRow;
try {
const { row, existing } = await recordHire({
hirerAgentId,
@@ -186,9 +238,18 @@ export default wrap(async (req, res) => {
});
reservationId = reservation.reservationId;
await sql`UPDATE agent_hires SET spend_reservation_id = ${reservationId}, updated_at = now() WHERE id = ${hireRow.id}`;
+ // Spend is held within the agent's caps — show the badge with real headroom.
+ pushPhase('reserved', { cap: capBadge(Number(reservation.dailySpentUsd ?? 0), usd) });
} catch (err) {
await updateHire(hireRow.id, { status: 'failed', error: err?.message || 'spend policy blocked' });
if (err instanceof SpendLimitError) {
+ // A cap/freeze block at reserve time renders as the amber "skipped" card,
+ // not a silent gap. over_cap covers per-tx/daily/owner-cap exceedance.
+ const capCode = err.code === 'per_tx_exceeded' || err.code === 'daily_exceeded';
+ pushPhase(capCode ? 'over_cap' : 'failed', {
+ cap: capBadge(null, usd),
+ error: capCode ? undefined : err.message,
+ });
return error(res, err.status || 403, err.code || 'spend_blocked', err.message, err.detail || {});
}
console.error('[a2a-hire] reserve failed', err?.message || err);
@@ -196,6 +257,9 @@ export default wrap(async (req, res) => {
}
// ── Pay over the real x402 rails (settles to the provider's wallet) ──────
+ // The remote skill runs inside this call (verify → work → settle). Narrate the
+ // "running" beat before it; the coin animation fires only on the settled frame.
+ pushPhase('running');
let payment;
try {
payment = await payExternalX402({
@@ -213,6 +277,8 @@ export default wrap(async (req, res) => {
await updateHire(hireRow.id, { status: 'failed', error: err?.message || String(err) });
const code = err?.code || 'payment_failed';
const status = code === 'spend_disabled' ? 501 : code === 'no_wallet' || code === 'no_solana_wallet' ? 409 : 502;
+ // Verify-then-settle means no funds moved — say so on the screen, no coin.
+ pushPhase('failed', { error: err?.message || code });
console.error('[a2a-hire] payment failed', code, err?.message || err);
return error(res, status, code, `the hire did not complete — no funds were moved: ${err?.message || code}`);
}
@@ -220,6 +286,12 @@ export default wrap(async (req, res) => {
const paymentSignature = receiptSignature(payment.receipt);
const payerAddress = payment.payer || hirer.meta.solana_address;
+ // Real USDC has settled to the provider — this is the frame the coin animation
+ // fires on. Then the delivery beat with a short summary of the provider's work.
+ pushPhase('settled', { txSig: paymentSignature, cap: capBadge(null, usd) });
+ const deliveredSummary = summarizeResult(payment.result);
+ pushPhase('delivered', { txSig: paymentSignature, resultSummary: deliveredSummary });
+
// Finalize the spend reservation as confirmed (real, settled).
await updateCustodyEvent(reservationId, {
status: 'confirmed',
@@ -269,6 +341,16 @@ export default wrap(async (req, res) => {
console.error('[a2a-hire] invocation receipt failed', invocationError);
}
+ // Terminal beat: the receipt card resolves with both real signatures. If the
+ // invocation write failed we still emit `recorded` (without an invocation sig)
+ // so the viewer sees a completed hire, with the settlement proof intact.
+ pushPhase('recorded', {
+ txSig: paymentSignature,
+ invocationSig: invocation?.signature || null,
+ resultSummary: deliveredSummary,
+ error: invocationError || undefined,
+ });
+
// ── Finalize the hire ───────────────────────────────────────────────────
const finalized = await updateHire(hireRow.id, {
status: 'completed',
diff --git a/api/agents/autopilot.js b/api/agents/autopilot.js
index 2d658bf53..9d2fde3eb 100644
--- a/api/agents/autopilot.js
+++ b/api/agents/autopilot.js
@@ -24,7 +24,7 @@ import {
runAutopilotCycle,
computeRunway,
} from '../_lib/treasury-autopilot.js';
-import { validateSolanaAddress } from '../_lib/agent-trade-guards.js';
+import { validateSolanaAddress, getSpendLimits } from '../_lib/agent-trade-guards.js';
async function resolveAuth(req) {
const session = await getSessionUser(req);
@@ -80,9 +80,12 @@ async function handleGet(req, res, id) {
const network = netOf(req);
const policy = getAutopilot(owned.meta);
+ // Surface the hard spend caps (daily/per-tx USD) read-only so the cockpit can
+ // render the ceiling the autopilot can never exceed. Owner-only data already.
+ const spendLimits = getSpendLimits(owned.meta);
try {
const runway = await computeRunway({ agentId: id, network, meta: owned.meta });
- return json(res, 200, { data: { policy, runway } });
+ return json(res, 200, { data: { policy, runway, spend_limits: spendLimits } });
} catch (e) {
return serverError(res, 500, 'runway_failed', e);
}
diff --git a/api/brain/chat.js b/api/brain/chat.js
index b2bb2f8e5..4326b3cfa 100644
--- a/api/brain/chat.js
+++ b/api/brain/chat.js
@@ -27,7 +27,7 @@ import { createReasoningStripper } from '../_lib/strip-reasoning.js';
// models. Every paid first-party model (Claude, GPT-4o, o3, DashScope, DeepSeek)
// requires sign-in so an unauthenticated script can't drain the server's billed
// API keys. Mirrors the anon-provider gate in api/chat.js.
-const ANON_BRAIN_PROVIDERS = new Set([
+export const ANON_BRAIN_PROVIDERS = new Set([
'gpt-oss-120b',
'nvidia-nemotron-120b',
'nvidia-nemotron-super-49b',
@@ -403,7 +403,7 @@ async function streamWatsonx(res, { messages, system, maxTokens, t0 }) {
res.end();
}
-function validateMessages(input) {
+export function validateMessages(input) {
if (!Array.isArray(input)) {
throw Object.assign(new Error('messages must be an array'), { status: 400 });
}
@@ -424,7 +424,7 @@ function validateMessages(input) {
return out;
}
-function getAvailableProviders() {
+export function getAvailableProviders() {
return Object.entries(PROVIDERS).map(([key, spec]) => {
const available = Boolean(buildPrimary(spec));
return {
@@ -439,71 +439,43 @@ function getAvailableProviders() {
});
}
-export default wrap(async function handler(req, res) {
- if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
-
- if (req.method === 'GET') {
- const providers = getAvailableProviders();
- res.setHeader('content-type', 'application/json');
- res.setHeader('cache-control', 'public, s-maxage=60, stale-while-revalidate=120');
- res.end(JSON.stringify({ providers }));
- return;
- }
-
- if (!method(req, res, ['POST'])) return;
-
- // Auth + rate limiting. The paid flagship models run on the server's billed
- // API keys, so an unmetered, unauthenticated proxy is a direct financial-drain
- // vector. Authenticated callers get a generous per-user budget; anonymous
- // callers a tight per-IP one and access only to the free-tier providers.
- const session = await getSessionUser(req);
- const bearer = session ? null : await authenticateBearer(extractBearer(req));
- const userId = session?.id ?? bearer?.userId ?? null;
- if (userId) {
- const rl = await limits.brainChatUser(userId);
- if (!rl.success) return rateLimited(res, rl, 'too many chat requests, slow down');
- } else {
- const rl = await limits.brainChatIp(clientIp(req));
- if (!rl.success) return rateLimited(res, rl, 'too many anonymous chat requests, try again shortly');
- }
-
- let body;
- try {
- body = await readJson(req, 200_000);
- } catch (e) {
- return error(res, e.status || 400, 'bad_request', e.message);
- }
-
- const providerKey = String(body.provider || 'gpt-oss-120b');
+// Resolve a provider key into a streamable plan: the spec, its primary route
+// (native key or OpenRouter mirror), and a distinct OpenRouter fallback when one
+// exists. Returns { ok: false, status, code, message, available? } when the key
+// is unknown or no route is configured, so every caller (the brain page handler
+// and the live Q&A concierge) reports the same errors identically.
+export function resolveBrain(providerKey) {
const spec = PROVIDERS[providerKey];
if (!spec) {
- return error(res, 400, 'unknown_provider', `unknown provider: ${providerKey}`, {
+ return {
+ ok: false,
+ status: 400,
+ code: 'unknown_provider',
+ message: `unknown provider: ${providerKey}`,
available: Object.keys(PROVIDERS),
- });
- }
- // Paid first-party models are sign-in only — anonymous callers are clamped to
- // the free tiers so they can't burn the server's billed Anthropic/OpenAI keys.
- if (!userId && !ANON_BRAIN_PROVIDERS.has(providerKey)) {
- return error(res, 401, 'unauthorized', 'sign in to use this model');
+ };
}
-
const primary = buildPrimary(spec);
if (!primary) {
- return error(res, 503, 'provider_not_configured',
- `No API key for ${spec.label}. Add your own key in Account → AI Provider Keys to unlock this model.`);
- }
- // OpenRouter escape hatch for a native-provider outage (quota/credits/rate).
- const fallbackModel = buildFallback(spec, primary);
-
- let messages;
- try {
- messages = validateMessages(body.messages);
- } catch (e) {
- return error(res, e.status || 400, 'bad_request', e.message);
+ return {
+ ok: false,
+ status: 503,
+ code: 'provider_not_configured',
+ message: `No API key for ${spec.label}. Add your own key in Account → AI Provider Keys to unlock this model.`,
+ };
}
+ return { ok: true, spec, primary, fallbackModel: buildFallback(spec, primary) };
+}
- const system = typeof body.system === 'string' ? body.system.slice(0, 8000) : undefined;
- const maxTokens = Math.min(Math.max(Number(body.maxTokens) || 4096, 64), spec.maxOutput);
+// Stream a brain completion to an SSE `res`: sets the event-stream headers, emits
+// the `meta` event, then runs the requested route → OpenRouter mirror → free-tier
+// safety-net chain, emitting `first` / chunk / `done` / `error` / `fallback`
+// events. Shared by POST /api/brain/chat and POST /api/agent-ask so both inherit
+// the same tuned timeout budget and never-error-while-a-free-route-can-answer
+// behaviour. The caller owns auth, rate limiting, and message validation; this
+// owns the transport. Resolve `plan` via resolveBrain() first.
+export async function streamBrain(res, { plan, providerKey, messages, system, maxTokens }) {
+ const { spec, primary, fallbackModel } = plan;
res.statusCode = 200;
res.setHeader('content-type', 'text/event-stream; charset=utf-8');
@@ -673,6 +645,73 @@ export default wrap(async function handler(req, res) {
}
}
}
+}
+
+export default wrap(async function handler(req, res) {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+
+ if (req.method === 'GET') {
+ const providers = getAvailableProviders();
+ res.setHeader('content-type', 'application/json');
+ res.setHeader('cache-control', 'public, s-maxage=60, stale-while-revalidate=120');
+ res.end(JSON.stringify({ providers }));
+ return;
+ }
+
+ if (!method(req, res, ['POST'])) return;
+
+ // Auth + rate limiting. The paid flagship models run on the server's billed
+ // API keys, so an unmetered, unauthenticated proxy is a direct financial-drain
+ // vector. Authenticated callers get a generous per-user budget; anonymous
+ // callers a tight per-IP one and access only to the free-tier providers.
+ const session = await getSessionUser(req);
+ const bearer = session ? null : await authenticateBearer(extractBearer(req));
+ const userId = session?.id ?? bearer?.userId ?? null;
+ if (userId) {
+ const rl = await limits.brainChatUser(userId);
+ if (!rl.success) return rateLimited(res, rl, 'too many chat requests, slow down');
+ } else {
+ const rl = await limits.brainChatIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl, 'too many anonymous chat requests, try again shortly');
+ }
+
+ let body;
+ try {
+ body = await readJson(req, 200_000);
+ } catch (e) {
+ return error(res, e.status || 400, 'bad_request', e.message);
+ }
+
+ const providerKey = String(body.provider || 'gpt-oss-120b');
+ const spec = PROVIDERS[providerKey];
+ if (!spec) {
+ return error(res, 400, 'unknown_provider', `unknown provider: ${providerKey}`, {
+ available: Object.keys(PROVIDERS),
+ });
+ }
+ // Paid first-party models are sign-in only — anonymous callers are clamped to
+ // the free tiers so they can't burn the server's billed Anthropic/OpenAI keys.
+ if (!userId && !ANON_BRAIN_PROVIDERS.has(providerKey)) {
+ return error(res, 401, 'unauthorized', 'sign in to use this model');
+ }
+
+ const plan = resolveBrain(providerKey);
+ if (!plan.ok) {
+ return error(res, plan.status, plan.code, plan.message,
+ plan.available ? { available: plan.available } : undefined);
+ }
+
+ let messages;
+ try {
+ messages = validateMessages(body.messages);
+ } catch (e) {
+ return error(res, e.status || 400, 'bad_request', e.message);
+ }
+
+ const system = typeof body.system === 'string' ? body.system.slice(0, 8000) : undefined;
+ const maxTokens = Math.min(Math.max(Number(body.maxTokens) || 4096, 64), plan.spec.maxOutput);
+
+ await streamBrain(res, { plan, providerKey, messages, system, maxTokens });
});
// OpenRouter (and some OpenAI-compatible backends) reject a request whose
diff --git a/api/intel/heatmap.js b/api/intel/heatmap.js
new file mode 100644
index 000000000..649e65ccb
--- /dev/null
+++ b/api/intel/heatmap.js
@@ -0,0 +1,222 @@
+/**
+ * GET /api/intel/heatmap?limit=30
+ * --------------------------------
+ * The live token field behind the 3D sentiment heatmap on agent screens. Returns
+ * a normalized set of tokens — $THREE always pinned first and flagged featured —
+ * each carrying the two signals the heatmap renders: 24h price momentum and 24h
+ * volume (magnitude). The anchor ($THREE) is additionally enriched with a live
+ * pump.fun comment sentiment pulse.
+ *
+ * Data is fully live, no fabricated arrays:
+ * - Field membership → pump.fun frontend-api-v3 /coins (trending by market cap)
+ * - Momentum + volume → Dexscreener batch /latest/dex/tokens/<mints> (best pair)
+ * - $THREE sentiment → pump.fun replies scored by the in-repo lexicon scorer
+ *
+ * $THREE is the only coin three.ws promotes. The rest of the field is generic,
+ * coin-agnostic market plumbing rendered from the live trending feed — this
+ * endpoint never names, recommends, or markets any other token. Tiles carry
+ * market data only.
+ *
+ * Response:
+ * {
+ * ok: true,
+ * fetchedAt,
+ * anchor: "<$THREE mint>",
+ * tokens: [ { id, symbol, name, image, priceUsd, change24h, volume24h,
+ * marketCap, featured, sentiment? } ],
+ * stale?: true
+ * }
+ */
+
+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';
+import { limits, clientIp } from '../_lib/rate-limit.js';
+import { normalizeGatewayURL } from '../../src/ipfs.js';
+
+// The one and only coin three.ws promotes. Always present, always featured.
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+const PUMP_FRONTEND_BASE = 'https://frontend-api-v3.pump.fun';
+const DEXSCREENER_BASE = 'https://api.dexscreener.com';
+const UPSTREAM_TIMEOUT_MS = 6000;
+const TTL_MS = 20_000;
+const STALE_MAX_MS = 5 * 60_000;
+const FIELD_MAX = 48; // hard cap on field size (incl. $THREE)
+const DS_BATCH = 30; // Dexscreener accepts up to 30 comma-separated mints per call
+
+let _cache = { value: null, storedAt: 0, expiresAt: 0, limit: 0 };
+
+async function fetchJson(url, init) {
+ let res;
+ try {
+ res = await fetch(url, { ...init, signal: AbortSignal.timeout(UPSTREAM_TIMEOUT_MS) });
+ } catch {
+ return null;
+ }
+ if (!res.ok) return null;
+ return res.json().catch(() => null);
+}
+
+// Trending mints from the public pump.fun feed (no key). Returns mint pubkeys
+// only; the per-token market data comes from Dexscreener below.
+async function fetchTrendingMints(limit) {
+ const url = new URL('/coins', PUMP_FRONTEND_BASE);
+ url.searchParams.set('offset', '0');
+ url.searchParams.set('limit', String(limit));
+ url.searchParams.set('sort', 'market_cap');
+ url.searchParams.set('order', 'DESC');
+ url.searchParams.set('includeNsfw', 'false');
+ const body = await fetchJson(url, { headers: { accept: 'application/json' } });
+ const coins = Array.isArray(body) ? body : Array.isArray(body?.coins) ? body.coins : null;
+ if (!Array.isArray(coins)) return [];
+ return coins
+ .map((c) => (typeof c.mint === 'string' ? c.mint : typeof c.address === 'string' ? c.address : ''))
+ .filter((m) => m.length >= 32);
+}
+
+// Best (highest 24h volume) Dexscreener pair per mint, keyed by base token mint.
+// One batched call per chunk of up to 30 mints.
+async function fetchDexBatch(mints) {
+ const byMint = new Map();
+ for (let i = 0; i < mints.length; i += DS_BATCH) {
+ const chunk = mints.slice(i, i + DS_BATCH);
+ const url = `${DEXSCREENER_BASE}/latest/dex/tokens/${chunk.join(',')}`;
+ const data = await fetchJson(url, { headers: { accept: 'application/json' } });
+ const pairs = Array.isArray(data?.pairs) ? data.pairs : [];
+ for (const p of pairs) {
+ const mint = p?.baseToken?.address;
+ if (!mint || !chunk.includes(mint)) continue;
+ const vol = Number(p?.volume?.h24 || 0);
+ const prev = byMint.get(mint);
+ if (!prev || vol > prev._vol) {
+ byMint.set(mint, {
+ _vol: vol,
+ symbol: p.baseToken?.symbol || null,
+ name: p.baseToken?.name || null,
+ priceUsd: p.priceUsd != null ? Number(p.priceUsd) : null,
+ change24h: p.priceChange?.h24 != null ? Number(p.priceChange.h24) : null,
+ volume24h: vol,
+ marketCap: p.marketCap != null ? Number(p.marketCap) : p.fdv != null ? Number(p.fdv) : null,
+ image: normalizeGatewayURL(p.info?.imageUrl || '') || null,
+ });
+ }
+ }
+ }
+ return byMint;
+}
+
+// pump.fun metadata for a single mint (name/symbol/image) — fills gaps when a
+// token has no Dexscreener pair yet, and supplies $THREE's canonical metadata.
+async function fetchPumpMeta(mint) {
+ const data = await fetchJson(`${PUMP_FRONTEND_BASE}/coins/${mint}`, {
+ headers: { accept: 'application/json' },
+ });
+ if (!data || data.error) return null;
+ return {
+ symbol: data.symbol || null,
+ name: data.name || null,
+ image: normalizeGatewayURL(data.image_uri || '') || null,
+ marketCap: data.usd_market_cap ?? null,
+ };
+}
+
+// Live $THREE sentiment from pump.fun replies, scored by the in-repo lexicon.
+// Single call, anchor-only — keeps the field fast while still surfacing the one
+// coin three.ws actually tracks.
+async function fetchThreeSentiment() {
+ const data = await fetchJson(`${PUMP_FRONTEND_BASE}/replies/${THREE_MINT}?limit=80&offset=0`, {
+ headers: { accept: 'application/json' },
+ });
+ const replies = Array.isArray(data?.replies) ? data.replies : Array.isArray(data) ? data : [];
+ const posts = replies
+ .map((r) => ({ text: String(r.text || r.message || '').slice(0, 2000) }))
+ .filter((p) => p.text);
+ if (!posts.length) return null;
+ try {
+ const { scoreSentiment } = await import('../../src/social/sentiment.js');
+ const s = scoreSentiment(posts);
+ return { score: s.score, posPct: s.posPct, negPct: s.negPct, neuPct: s.neuPct, count: s.count };
+ } catch {
+ return null;
+ }
+}
+
+async function buildField(limit) {
+ // Pull a slightly wider trending set than requested so that, after dropping
+ // $THREE-duplicates and pairless tokens, we can still fill the field.
+ const trending = await fetchTrendingMints(Math.min(FIELD_MAX, limit + 8));
+ const mints = [THREE_MINT, ...trending.filter((m) => m !== THREE_MINT)].slice(0, limit);
+
+ const [dex, threeMeta, threeSentiment] = await Promise.all([
+ fetchDexBatch(mints),
+ fetchPumpMeta(THREE_MINT),
+ fetchThreeSentiment(),
+ ]);
+
+ const tokens = [];
+ for (const mint of mints) {
+ const d = dex.get(mint) || {};
+ const featured = mint === THREE_MINT;
+ const meta = featured ? threeMeta : null;
+ const token = {
+ id: mint,
+ symbol: d.symbol || meta?.symbol || `${mint.slice(0, 4)}…`,
+ name: d.name || meta?.name || null,
+ image: d.image || meta?.image || null,
+ priceUsd: d.priceUsd ?? null,
+ change24h: d.change24h ?? null,
+ volume24h: d.volume24h ?? 0,
+ marketCap: d.marketCap ?? meta?.marketCap ?? null,
+ featured,
+ };
+ if (featured && threeSentiment) token.sentiment = threeSentiment;
+ // Drop non-anchor tokens with no usable signal at all (no price + no
+ // volume) so the field never carries dead tiles — $THREE always stays.
+ if (!featured && token.priceUsd == null && !token.volume24h) continue;
+ tokens.push(token);
+ }
+ return tokens;
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ const params = new URL(req.url, 'http://x').searchParams;
+ const raw = Number(params.get('limit') || '28');
+ const limit = Math.min(FIELD_MAX, Math.max(1, Number.isFinite(raw) ? Math.floor(raw) : 28));
+
+ const now = Date.now();
+ if (_cache.value && _cache.limit >= limit && _cache.expiresAt > now) {
+ return json(res, 200, { ok: true, anchor: THREE_MINT, fetchedAt: new Date(_cache.storedAt).toISOString(), tokens: _cache.value.slice(0, limit) }, {
+ 'cache-control': 'public, max-age=10, s-maxage=20',
+ });
+ }
+
+ let tokens = [];
+ try {
+ tokens = await buildField(limit);
+ } catch {
+ tokens = [];
+ }
+
+ // A field with only $THREE (or empty) means the trending/Dexscreener upstreams
+ // blipped — serve the last good field as stale rather than collapsing to the
+ // anchor alone, so the heatmap keeps breathing through the outage.
+ if (tokens.length <= 1 && _cache.value && now - _cache.storedAt <= STALE_MAX_MS) {
+ return json(res, 200, { ok: true, anchor: THREE_MINT, fetchedAt: new Date(_cache.storedAt).toISOString(), tokens: _cache.value.slice(0, limit), stale: true }, {
+ 'cache-control': 'public, max-age=8, s-maxage=15',
+ });
+ }
+
+ if (!tokens.length) {
+ return error(res, 502, 'upstream_error', 'Market data is temporarily unavailable');
+ }
+
+ _cache = { value: tokens, storedAt: now, expiresAt: now + TTL_MS, limit };
+ return json(res, 200, { ok: true, anchor: THREE_MINT, fetchedAt: new Date(now).toISOString(), tokens }, {
+ 'cache-control': 'public, max-age=10, s-maxage=20',
+ });
+});
diff --git a/api/pump/autopilot.js b/api/pump/autopilot.js
index 564beff67..db302ff77 100644
--- a/api/pump/autopilot.js
+++ b/api/pump/autopilot.js
@@ -72,7 +72,7 @@ async function listCoins(req, res, userId) {
const coins = await sql`
select
m.id, m.mint, m.network, m.name, m.symbol, m.buyback_bps,
- m.created_at,
+ m.created_at, m.agent_id,
a.name as agent_name,
a.avatar_url as agent_avatar,
a.profile_image_url as agent_image,
@@ -162,6 +162,7 @@ async function listCoins(req, res, userId) {
id: c.id,
mint: c.mint,
network: c.network,
+ agent_id: c.agent_id,
name: c.name || c.agent_name,
symbol: c.symbol,
agent_name: c.agent_name,
diff --git a/data/changelog.json b/data/changelog.json
index 8fb6513fc..3ebccc420 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -38,9 +38,9 @@
"link": "/agent-screen"
},
{
- "date": "2026-06-28",
- "title": "The agent's walk preview now fills its whole card",
- "summary": "On an agent's page, the 'Walk with this agent' preview used to sit as a small box pinned to the left with the rest of the card empty beside it. It's now a proper two-column panel: the live avatar walks on the left while the right side 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.",
+ "date": "2026-06-29",
+ "title": "The agent's walk preview now floats free across its whole card",
+ "summary": "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.",
"tags": [
"improvement"
]
diff --git a/mcp-server/src/lib/pump-vanity.js b/mcp-server/src/lib/pump-vanity.js
index 672cbac8c..7a906db62 100644
--- a/mcp-server/src/lib/pump-vanity.js
+++ b/mcp-server/src/lib/pump-vanity.js
@@ -19,6 +19,9 @@ const BASE58_CHARS = new Set(BASE58_ALPHABET);
const MAX_PATTERN_LENGTH = 6;
const DEFAULT_MAX_ITERATIONS = 2_000_000;
const YIELD_EVERY = 10_000;
+// How often (in attempts) onProgress fires — aligned to a yield boundary. Kept
+// in sync with the canonical api/_lib/pump-vanity.js.
+const PROGRESS_EVERY = 25_000;
function validatePattern(pattern, label) {
if (typeof pattern !== 'string' || pattern.length === 0) {
@@ -71,7 +74,8 @@ export function estimateAttempts({ prefix, suffix, ignoreCase = false } = {}) {
* @param {string} [opts.suffix] — required base58 suffix
* @param {boolean} [opts.ignoreCase] — case-insensitive match
* @param {number} [opts.maxIterations] — hard cap (default 2M)
- * @param {(attempts:number,rate:number)=>void} [opts.onProgress] — every 1k attempts
+ * @param {(sample:{iterations:number,elapsedMs:number,attemptsPerSec:number,sampleAddress:string})=>void} [opts.onProgress]
+ * — fired every PROGRESS_EVERY (25k) attempts with real, monotonic numbers.
* @returns {Promise<{ keypair: Keypair, iterations: number, durationMs: number }>}
*/
export async function grindMintKeypair({
@@ -80,6 +84,7 @@ export async function grindMintKeypair({
ignoreCase = false,
maxIterations = DEFAULT_MAX_ITERATIONS,
onProgress,
+ progressEvery = PROGRESS_EVERY,
} = {}) {
if (!prefix && !suffix) {
const kp = Keypair.generate();
@@ -87,6 +92,7 @@ export async function grindMintKeypair({
}
if (prefix) validatePattern(prefix, 'prefix');
if (suffix) validatePattern(suffix, 'suffix');
+ const sampleEvery = Math.max(1, Math.floor(progressEvery) || PROGRESS_EVERY);
const targetPrefix = prefix ? (ignoreCase ? prefix.toLowerCase() : prefix) : null;
const targetSuffix = suffix ? (ignoreCase ? suffix.toLowerCase() : suffix) : null;
@@ -101,6 +107,22 @@ export async function grindMintKeypair({
const kp = Keypair.generate();
const addr = kp.publicKey.toBase58();
+ // Emit a live progress sample from real numbers (kept in sync with the
+ // canonical api/_lib/pump-vanity.js).
+ if (onProgress && i % sampleEvery === 0) {
+ const now = Date.now();
+ const windowMs = now - lastProgressAt;
+ const windowAttempts = i - lastProgressAttempts;
+ const attemptsPerSec = windowMs > 0 ? (windowAttempts / windowMs) * 1000 : 0;
+ lastProgressAt = now;
+ lastProgressAttempts = i;
+ try {
+ onProgress({ iterations: i, elapsedMs: now - start, attemptsPerSec, sampleAddress: addr });
+ } catch {
+ // A misbehaving progress sink must never abort a paid grind.
+ }
+ }
+
const head = ignoreCase ? addr.substring(0, pLen).toLowerCase() : addr.substring(0, pLen);
if (targetPrefix && head !== targetPrefix) {
if (i % YIELD_EVERY === 0) await new Promise((r) => setImmediate(r));
diff --git a/pages/agent-detail.html b/pages/agent-detail.html
index 3c575f7d4..86871ad9b 100644
--- a/pages/agent-detail.html
+++ b/pages/agent-detail.html
@@ -207,6 +207,13 @@
height: 100%;
border: 0;
display: block;
+ /* This page renders with `color-scheme: dark`, which Chromium
+ propagates into child iframes and paints their otherwise-
+ transparent backdrop opaque — turning the floating avatar into a
+ white box. Forcing the frame's own scheme to `light` keeps the
+ embed's transparent background showing the card through. */
+ color-scheme: light;
+ background: transparent;
transition: opacity 0.4s ease;
}
.ad-walk-skeleton {
diff --git a/pages/agent-screen.html b/pages/agent-screen.html
index 7a37c5b99..649e70074 100644
--- a/pages/agent-screen.html
+++ b/pages/agent-screen.html
@@ -122,6 +122,60 @@
}
.asc-live-badge.dark .dot { background: var(--screen-dark); animation: none; }
+ /* ── live PnL ticker ── */
+ .asc-pnl {
+ display: inline-flex;
+ align-items: baseline;
+ gap: 0.4rem;
+ background: rgba(255,255,255,0.05);
+ border: 1px solid rgba(255,255,255,0.12);
+ border-radius: 999px;
+ padding: 0.22rem 0.6rem;
+ font: inherit;
+ color: #d4d4d8;
+ cursor: pointer;
+ flex: none;
+ transition: background 0.15s, border-color 0.15s, transform 0.1s, box-shadow 0.2s;
+ }
+ .asc-pnl:hover { background: rgba(255,255,255,0.09); border-color: rgba(255,255,255,0.22); }
+ .asc-pnl:active { transform: scale(0.97); }
+ .asc-pnl:focus-visible { outline: none; box-shadow: 0 0 0 2px rgba(120,170,255,0.55); }
+ .asc-pnl-label {
+ font-size: 0.6rem;
+ font-weight: 700;
+ letter-spacing: 0.1em;
+ text-transform: uppercase;
+ color: rgba(255,255,255,0.4);
+ }
+ .asc-pnl-value {
+ font-size: 0.9rem;
+ font-weight: 720;
+ font-variant-numeric: tabular-nums;
+ letter-spacing: -0.01em;
+ color: #e4e4e7;
+ transition: color 0.2s;
+ }
+ .asc-pnl-detail {
+ font-size: 0.7rem;
+ font-weight: 600;
+ font-variant-numeric: tabular-nums;
+ color: rgba(255,255,255,0.5);
+ padding-left: 0.45rem;
+ border-left: 1px solid rgba(255,255,255,0.14);
+ }
+ .asc-pnl.pos .asc-pnl-value { color: var(--screen-live, #4ade80); }
+ .asc-pnl.neg .asc-pnl-value { color: #f87171; }
+ .asc-pnl.pos { border-color: rgba(74,222,128,0.35); background: rgba(74,222,128,0.08); }
+ .asc-pnl.neg { border-color: rgba(248,113,113,0.35); background: rgba(248,113,113,0.08); }
+ /* brief flash when a fresh fill moves the number */
+ .asc-pnl.bump { animation: asc-pnl-bump 0.45s ease; }
+ @keyframes asc-pnl-bump {
+ 0% { transform: scale(1); }
+ 40% { transform: scale(1.09); }
+ 100% { transform: scale(1); }
+ }
+ body.asc-zen .asc-pnl { display: none; }
+
.asc-header-right {
margin-left: auto;
display: flex;
@@ -448,6 +502,11 @@
.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; }
+ /* 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; }
+ .asc-log-entry.pnl-pos .asc-log-type.trade { background: rgba(74,222,128,0.18); color: #6ee7a0; box-shadow: inset 2px 0 0 #4ade80; }
+ .asc-log-entry.pnl-neg .asc-log-type.trade { background: rgba(248,113,113,0.18); color: #f9a8a8; box-shadow: inset 2px 0 0 #f87171; }
.asc-log-empty {
display: flex;
align-items: center;
@@ -850,6 +909,13 @@
<span class="dot"></span>
<span id="asc-badge-text">Connecting</span>
</span>
+ <button class="asc-pnl" id="asc-pnl" type="button" hidden
+ title="Session realized + unrealized, from real fills — click for detail"
+ aria-label="Session profit and loss">
+ <span class="asc-pnl-label">PnL</span>
+ <span class="asc-pnl-value" id="asc-pnl-value">—</span>
+ <span class="asc-pnl-detail" id="asc-pnl-detail" hidden></span>
+ </button>
</div>
<div class="asc-header-right" id="asc-controls">
<div class="asc-ctl-group" id="asc-panel-toggles">
diff --git a/pages/agents-live.html b/pages/agents-live.html
index 8ab576f66..b2776dd0e 100644
--- a/pages/agents-live.html
+++ b/pages/agents-live.html
@@ -300,6 +300,66 @@
background: rgba(255,255,255,0.25);
animation: none;
}
+ /* Stuttering caster: live, but its own feed dropped below ~1fps for >3s.
+ Amber + slow pulse reads as "live but degraded", distinct from dark. */
+ .al-card-live-dot.thin {
+ background: #f5a623;
+ animation: al-pulse 2.6s ease-in-out infinite;
+ }
+
+ /* ── warming / queued handoff overlay ─────────────────────────────
+ Sits above the canvas, below the live badge. Pure ambiance — never
+ blocks the card link (pointer-events:none) and never claims real
+ progress; the pulse is a CSS ring, not a loading bar. */
+ .al-card-warming {
+ position: absolute;
+ inset: 0;
+ z-index: 1;
+ display: flex;
+ flex-direction: column;
+ align-items: center;
+ justify-content: center;
+ gap: 10px;
+ padding: 16px;
+ text-align: center;
+ background: radial-gradient(ellipse at center, rgba(8,8,12,0.55), rgba(6,6,8,0.78));
+ backdrop-filter: blur(2px);
+ -webkit-backdrop-filter: blur(2px);
+ pointer-events: none;
+ opacity: 0;
+ transform: translateY(4px);
+ transition: opacity 0.28s ease, transform 0.28s ease;
+ }
+ .al-card-warming.is-visible {
+ opacity: 1;
+ transform: none;
+ }
+ .al-warming-pulse {
+ width: 22px;
+ height: 22px;
+ border-radius: 50%;
+ border: 2px solid rgba(255,255,255,0.85);
+ will-change: transform, opacity;
+ animation: al-warming-ring 1.5s ease-out infinite;
+ }
+ @keyframes al-warming-ring {
+ 0% { transform: scale(0.5); opacity: 0.9; }
+ 70% { transform: scale(1.25); opacity: 0; }
+ 100% { transform: scale(1.25); opacity: 0; }
+ }
+ .al-warming-text {
+ font-size: 11px;
+ font-weight: 700;
+ letter-spacing: 0.02em;
+ color: rgba(255,255,255,0.82);
+ max-width: 80%;
+ line-height: 1.4;
+ }
+ /* Reduced motion: no expanding ring, just a steady dot + the honest text. */
+ @media (prefers-reduced-motion: reduce) {
+ .al-card-warming { transition: opacity 0.28s ease; transform: none; }
+ .al-warming-pulse { animation: none; opacity: 1; transform: none; }
+ }
.al-card-expand {
position: absolute;
bottom: 10px;
@@ -353,6 +413,24 @@
text-overflow: ellipsis;
margin-top: 2px;
}
+ /* live realized-PnL chip — a row of these reads as a wall of trading desks */
+ .al-card-pnl {
+ display: inline-flex;
+ align-items: center;
+ gap: 3px;
+ margin-top: 3px;
+ padding: 1px 7px;
+ border-radius: 999px;
+ font-size: 11px;
+ font-weight: 800;
+ font-variant-numeric: tabular-nums;
+ letter-spacing: -0.01em;
+ border: 1px solid transparent;
+ }
+ .al-card-pnl[hidden] { display: none; }
+ .al-card-pnl.pos { color: #6ee7a0; background: rgba(74,222,128,0.1); border-color: rgba(74,222,128,0.3); }
+ .al-card-pnl.neg { color: #f9a8a8; background: rgba(248,113,113,0.1); border-color: rgba(248,113,113,0.3); }
+ .al-card-pnl::before { content: ''; width: 5px; height: 5px; border-radius: 50%; background: currentColor; }
.al-card-watch-btn {
flex-shrink: 0;
padding: 5px 12px;
diff --git a/public/changelog.json b/public/changelog.json
index d94db4a99..2cb649ad1 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-29T03:07:18.313Z",
+ "generated_at": "2026-06-29T03:54:57.986Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -36,6 +36,16 @@
"fix"
]
},
+ {
+ "date": "2026-06-29",
+ "type": "update",
+ "title": "The agent's walk preview now floats free across its whole card",
+ "summary": "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.",
+ "link": null,
+ "tags": [
+ "improvement"
+ ]
+ },
{
"date": "2026-06-28",
"type": "update",
@@ -488,16 +498,6 @@
"fix"
]
},
- {
- "date": "2026-06-28",
- "type": "update",
- "title": "The agent's walk preview now fills its whole card",
- "summary": "On an agent's page, the 'Walk with this agent' preview used to sit as a small box pinned to the left with the rest of the card empty beside it. It's now a proper two-column panel: the live avatar walks on the left while the right side 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.",
- "link": null,
- "tags": [
- "improvement"
- ]
- },
{
"date": "2026-06-28",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index a58e6b369..488fae221 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -30,6 +30,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>The agent's walk preview now floats free across its whole card</title>
+ <link>https://three.ws/changelog</link>
+ <guid isPermaLink="false">2026-06-29:The agent's walk preview now floats free across its whole card</guid>
+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>
+ <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>$THREE payments ride out brief price-feed blips instead of failing</title>
<link>https://three.ws/three-token</link>
@@ -374,14 +382,6 @@
<category>fix</category>
<description>On pages with a white accent color, the &quot;⑂ Save to my avatars&quot; button (shown on any avatar you don't own) rendered white text on a white background — effectively invisible. The button now picks its text color from the actual button background, so a light button gets black text and a dark button keeps white, keeping the label legible everywhere it appears.</description>
</item>
- <item>
- <title>The agent's walk preview now fills its whole card</title>
- <link>https://three.ws/changelog</link>
- <guid isPermaLink="false">2026-06-28:The agent's walk preview now fills its whole card</guid>
- <pubDate>Sun, 28 Jun 2026 12:00:00 GMT</pubDate>
- <category>improvement</category>
- <description>On an agent's page, the 'Walk with this agent' preview used to sit as a small box pinned to the left with the rest of the card empty beside it. It's now a proper two-column panel: the live avatar walks on the left while the right side 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>The Agents directory now lists every on-chain agent, not just ours</title>
<link>https://three.ws/agents</link>
diff --git a/public/features.json b/public/features.json
index 3fc349ed6..093aa13b3 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-29T03:07:18.298Z",
+ "generated_at": "2026-06-29T03:54:57.885Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/agent-screen-anchor.js b/src/agent-screen-anchor.js
new file mode 100644
index 000000000..fdad2649f
--- /dev/null
+++ b/src/agent-screen-anchor.js
@@ -0,0 +1,308 @@
+// agent-screen-anchor.js — Newsroom Anchor playback for /agent-screen.
+//
+// When the agent pushes a type:'analysis' frame (a bulletin headline), this
+// module slides up a broadcast lower-third, fetches the spoken script from
+// /api/agent/anchor-script, synthesizes real speech, and lip-syncs the Avatar
+// Cam head to it:
+//
+// • Lipsync, best path: POST /api/a2f { text } returns the spoken audio AND a
+// per-frame ARKit blendshape track. The A2FPlayer drives the avatar's morph
+// targets frame-by-frame against the audio's currentTime.
+// • Fallback, no ARKit morphs (or A2F unconfigured): play TTS audio and bob
+// the jaw/mouth from the audio's real RMS amplitude — never a frozen face.
+// • Fallback, no audio at all: the lower-third still shows, flagged "audio
+// unavailable", so the bulletin is readable.
+//
+// Audio is muted by default (autoplay policy + the live wall), with a one-tap
+// unmute. Nothing is synthesized while muted, so a muted viewer costs no TTS.
+
+import { A2FPlayer } from './voice/a2f-player.js';
+import { AvatarMouthTarget } from './voice/avatar-morph-target.js';
+
+const ANCHOR_VOICE = 'nova';
+const LS_MUTE_KEY = 'asc_anchor_muted';
+
+// 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 b64ToBlob(base64, contentType) {
+ const bytes = atob(base64);
+ const arr = new Uint8Array(bytes.length);
+ for (let i = 0; i < bytes.length; i++) arr[i] = bytes.charCodeAt(i);
+ return new Blob([arr], { type: contentType || 'audio/wav' });
+}
+
+/**
+ * @param {object} opts
+ * @param {string} opts.agentId
+ * @param {object} opts.els — { lowerthird, eyebrow, headline, note, muteBtn, unmute }
+ * @param {() => any} opts.getAvatar — returns the current avatar root (or null)
+ */
+export function createNewsroomAnchor({ agentId, els, getAvatar }) {
+ const a2fPlayer = new A2FPlayer();
+ const mouthTarget = new AvatarMouthTarget();
+ let boundAvatar = null;
+
+ let muted = readMutePref();
+ let a2fSupported = null; // null = unprobed, false = endpoint says unconfigured
+
+ // Active utterance state.
+ let audioEl = null;
+ let analyser = null;
+ let analyserData = null;
+ let mode = 'idle'; // 'idle' | 'a2f' | 'rms'
+ let lastScript = null; // remember the latest bulletin for unmute-then-speak
+ let speakToken = 0; // invalidates an in-flight speak() when a newer one starts
+
+ function readMutePref() {
+ try {
+ const v = localStorage.getItem(LS_MUTE_KEY);
+ return v === null ? true : v === '1';
+ } catch { return true; }
+ }
+ function writeMutePref(v) {
+ try { localStorage.setItem(LS_MUTE_KEY, v ? '1' : '0'); } catch { /* quota */ }
+ }
+
+ function ensureAvatarBound() {
+ const root = getAvatar?.();
+ if (root && root !== boundAvatar) {
+ boundAvatar = root;
+ a2fPlayer.attach(root);
+ mouthTarget.attach(root);
+ }
+ return boundAvatar;
+ }
+
+ // ── lower-third UI ────────────────────────────────────────────────────────
+ function showLowerThird(headline, { skeleton = false, note = '' } = {}) {
+ if (!els.lowerthird) return;
+ els.lowerthird.classList.toggle('asc-lt--skeleton', skeleton);
+ els.lowerthird.classList.add('asc-lt--show');
+ if (els.headline) els.headline.textContent = skeleton ? '' : (headline || '');
+ if (els.note) {
+ els.note.textContent = note;
+ els.note.style.display = note ? 'block' : 'none';
+ }
+ // Long headlines marquee on hover (CSS); flag when it overflows.
+ if (els.headline) {
+ requestAnimationFrame(() => {
+ const overflow = els.headline.scrollWidth > els.headline.clientWidth + 4;
+ els.lowerthird.classList.toggle('asc-lt--overflow', overflow);
+ });
+ }
+ }
+
+ function setMuteUi() {
+ if (els.muteBtn) {
+ els.muteBtn.classList.toggle('asc-muted', muted);
+ els.muteBtn.setAttribute('aria-pressed', String(!muted));
+ els.muteBtn.title = muted ? 'Unmute anchor — M' : 'Mute anchor — M';
+ els.muteBtn.innerHTML = muted ? '🔇' : '🔊';
+ }
+ if (els.unmute) els.unmute.style.display = muted ? 'flex' : 'none';
+ }
+
+ // ── speech + lipsync ───────────────────────────────────────────────────────
+ function stopSpeaking() {
+ speakToken++;
+ if (audioEl) {
+ try { audioEl.pause(); } catch { /* */ }
+ if (audioEl.src?.startsWith('blob:')) { try { URL.revokeObjectURL(audioEl.src); } catch { /* */ } }
+ audioEl = null;
+ }
+ analyser = null;
+ analyserData = null;
+ mode = 'idle';
+ a2fPlayer.reset();
+ mouthTarget.setMouthShape({ open: 0 });
+ }
+
+ async function playClip(blob, { track = null } = {}) {
+ const myToken = ++speakToken;
+ ensureAvatarBound();
+
+ audioEl = new Audio();
+ audioEl.src = URL.createObjectURL(blob);
+ audioEl.muted = false; // we only reach here when unmuted
+
+ // Decide lipsync path. A2F track with real morph coverage wins; otherwise
+ // drive the jaw/mouth from live RMS so the face never freezes.
+ if (track) a2fPlayer.setTrack(track);
+ if (track && a2fPlayer.hasCoverage()) {
+ mode = 'a2f';
+ } else {
+ mode = 'rms';
+ 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; // element route still plays sound below
+ }
+ }
+ }
+
+ const cleanup = () => {
+ if (myToken !== speakToken) return;
+ mode = 'idle';
+ a2fPlayer.reset();
+ mouthTarget.setMouthShape({ open: 0 });
+ };
+ audioEl.addEventListener('ended', cleanup, { once: true });
+ audioEl.addEventListener('error', cleanup, { once: true });
+
+ try {
+ await audioEl.play();
+ } catch {
+ // Autoplay blocked or decode error — surface as mute so the CTA returns.
+ cleanup();
+ throw new Error('audio_play_failed');
+ }
+ }
+
+ // Synthesize + play one read. Tries the combined A2F text path first (audio +
+ // blendshapes in one call), then plain TTS + RMS, then text-only.
+ async function speak(text) {
+ if (!text || muted) return;
+ stopSpeaking();
+ const myToken = speakToken;
+
+ // Path 1: /api/a2f text → { audio, animation }
+ if (a2fSupported !== false) {
+ try {
+ const r = await fetch('/api/a2f', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ text, voice: ANCHOR_VOICE }),
+ });
+ if (r.status === 503) {
+ a2fSupported = false; // not configured — don't keep trying this lane
+ } else if (r.ok) {
+ const j = await r.json();
+ if (myToken !== speakToken) return;
+ if (j?.audio?.base64 && j?.animation) {
+ a2fSupported = true;
+ await playClip(b64ToBlob(j.audio.base64, j.audio.contentType), { track: j.animation });
+ return;
+ }
+ }
+ } catch { /* fall through to TTS-only */ }
+ }
+ if (myToken !== speakToken) return;
+
+ // Path 2: /api/tts/speak → audio bytes, lip-synced by RMS amplitude.
+ try {
+ const r = await fetch('/api/tts/speak', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ text, voice: ANCHOR_VOICE, format: 'mp3' }),
+ });
+ if (!r.ok) throw new Error(`tts ${r.status}`);
+ const blob = await r.blob();
+ if (myToken !== speakToken) return;
+ await playClip(blob, { track: null });
+ return;
+ } catch {
+ // Path 3: text-only — the lower-third stays up with an honest note.
+ if (myToken === speakToken && els.note) {
+ els.note.textContent = 'audio unavailable';
+ els.note.style.display = 'block';
+ }
+ }
+ }
+
+ async function fetchScript() {
+ try {
+ const r = await fetch(`/api/agent/anchor-script?agentId=${encodeURIComponent(agentId)}`);
+ if (!r.ok) return null;
+ const j = await r.json();
+ return j?.script || null;
+ } catch { return null; }
+ }
+
+ // ── public surface ──────────────────────────────────────────────────────────
+
+ // Called for every type:'analysis' frame on the stream.
+ async function handleFrame(frame) {
+ const headline = frame?.activity || '';
+ showLowerThird(headline, { skeleton: !headline });
+ const script = await fetchScript();
+ lastScript = {
+ headline: script?.headline || headline,
+ body: script?.body || headline,
+ offline: script?.offline || [],
+ };
+ const note = lastScript.offline.length
+ ? `${lastScript.offline.join(' · ')} offline`
+ : '';
+ showLowerThird(lastScript.headline, { note });
+ if (!muted) speak(lastScript.body);
+ }
+
+ // Driven from the webcam render loop to advance lipsync.
+ function tick() {
+ if (mode === 'idle' || !audioEl) return;
+ ensureAvatarBound();
+ if (mode === 'a2f') {
+ a2fPlayer.update(audioEl.currentTime || 0);
+ } else if (mode === 'rms' && analyser && analyserData) {
+ 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);
+ // Map RMS (~0–0.3 for speech) to mouth-open with a touch of gain + clamp.
+ const open = Math.min(1, rms * 3.2);
+ mouthTarget.setMouthShape({ open });
+ }
+ }
+
+ function setMuted(next, { speakNow = true } = {}) {
+ muted = next;
+ writeMutePref(muted);
+ setMuteUi();
+ if (muted) {
+ stopSpeaking();
+ } else if (speakNow && lastScript?.body) {
+ audioContext()?.resume?.();
+ speak(lastScript.body);
+ }
+ }
+
+ function toggleMute() { setMuted(!muted); }
+
+ function init() {
+ setMuteUi();
+ els.muteBtn?.addEventListener('click', toggleMute);
+ els.unmute?.addEventListener('click', () => setMuted(false));
+ }
+
+ function destroy() {
+ stopSpeaking();
+ a2fPlayer.dispose();
+ mouthTarget.dispose();
+ }
+
+ init();
+
+ return { handleFrame, tick, toggleMute, setMuted, isMuted: () => muted, destroy };
+}
diff --git a/src/agent-screen-dj.js b/src/agent-screen-dj.js
new file mode 100644
index 000000000..56c871ffa
--- /dev/null
+++ b/src/agent-screen-dj.js
@@ -0,0 +1,157 @@
+// Ambient World DJ — turns world state into a calm spoken host script (Brief 22).
+//
+// On the /agent-screen Ambient stage the agent stops trading and starts hosting:
+// it watches the living world (the day/night phase, how busy the plaza is, the
+// odd wanderer) and narrates it in short, calm lines — the "lo-fi beats" of the
+// agent wall. This module is the script generator. It is pure logic (no Three.js,
+// no DOM, no network) so it unit-tests cleanly and the stage just feeds it world
+// snapshots and plays back whatever it returns.
+//
+// Two rules keep it calm instead of chatty:
+// 1. A minimum gap between lines (default ~28s) — observe() returns null until
+// the gap has elapsed, no matter how much the world changed.
+// 2. Lines are templated from real world events (a sunrise, golden hour, the
+// plaza filling up), never random filler. Each event has a small rotation
+// of phrasings advanced by a counter — varied, but deterministic, so there's
+// no Math.random in the path.
+
+import { phaseLabel, isGoldenHour } from './shared/world-clock.js';
+
+// Default minimum spacing between spoken host lines. Calm pacing: one line every
+// ~28s settles to roughly two a minute even when the world is eventful.
+export const DJ_MIN_GAP_MS = 28_000;
+
+// Event → mood tag the stage uses to tint the log entry and (with audio on) pick
+// the TTS delivery. Kept small and human.
+const EVENT_MOOD = {
+ sunrise: 'warm',
+ goldenHour: 'warm',
+ dusk: 'calm',
+ night: 'sleepy',
+ zoneBusy: 'lively',
+ npcArrived: 'lively',
+ idleAmbiance: 'calm',
+};
+
+// Phrasings per event. `{place}` is the agent's world (a biome label) and
+// `{landmark}` the spot the camera frames. Calm, coin-agnostic, never a market
+// call — the Ambient channel is the opposite of the trading desk.
+const LINES = {
+ sunrise: [
+ 'Sun’s coming up over {place}. Soft light on {landmark}.',
+ 'Dawn breaks across {place} — the world stretches awake.',
+ 'First light. {landmark} warms up gold and quiet.',
+ ],
+ goldenHour: [
+ 'Golden hour over {place}. Everything’s lit like honey right now.',
+ 'The light’s gone warm and long across {landmark}. Best part of the day.',
+ 'Sun’s low and golden. {place} glows for a few minutes more.',
+ ],
+ dusk: [
+ 'Sun’s setting over {landmark}. Quiet shift tonight.',
+ 'Dusk settling on {place}. The sky cools toward dark.',
+ 'Last of the light fading over {landmark}. Lamps coming on.',
+ ],
+ night: [
+ 'Night over {place}. Just the stars and a little wind now.',
+ 'It’s gone dark and still across {landmark}. Calm out here.',
+ 'Stars are out over {place}. The quiet shift begins.',
+ ],
+ zoneBusy: [
+ 'Bit of a crowd gathering near {landmark} — nice to see some life.',
+ '{landmark}’s filling up. The world’s busy this hour.',
+ 'Foot traffic picking up around {place}. Good energy.',
+ ],
+ npcArrived: [
+ 'Someone just wandered up to {landmark}. We’ve got company.',
+ 'New face drifting through {place}. Welcome in.',
+ 'A wanderer reaches {landmark} and stops to look around.',
+ ],
+ idleAmbiance: [
+ 'Quiet out here right now — just the wind through {place}.',
+ 'Nothing urgent on {landmark}. Leave it on, let it breathe.',
+ 'Calm shift over {place}. The world ticks along on its own.',
+ ],
+};
+
+function fill(template, ctx) {
+ return template
+ .replace(/\{place\}/g, ctx.place)
+ .replace(/\{landmark\}/g, ctx.landmark);
+}
+
+/**
+ * Build a DJ script for one agent's ambient stage.
+ *
+ * @param {object} [opts]
+ * @param {number} [opts.minGapMs] minimum ms between emitted lines
+ * @param {string} [opts.place] the world's name (biome label) for templating
+ * @param {string} [opts.landmark] the framed spot (e.g. "the plaza", "the wall")
+ * @returns {{ observe: (state:object, now:number) => (null | {text:string,type:string,mood:string,event:string}), reset: () => void }}
+ */
+export function createDjScript({ minGapMs = DJ_MIN_GAP_MS, place = 'the world', landmark = 'the plaza' } = {}) {
+ const ctx = { place, landmark };
+ const rot = Object.create(null); // event → next phrasing index (deterministic rotation)
+ let lastEmitAt = -Infinity;
+ let lastLabel = null;
+ let lastGolden = false;
+ let lastBusy = false;
+ let lastPedCount = null;
+
+ // Pick the highest-priority event the world is currently presenting that we
+ // haven't already announced. Transitions (a band the sky just crossed) outrank
+ // the steady-state crowd reading, which outranks plain idle ambiance.
+ function pickEvent(state) {
+ const label = phaseLabel(state.phase);
+ const golden = isGoldenHour(state.phase);
+
+ // Golden hour is its own beat, called once as it begins.
+ if (golden && !lastGolden) return 'goldenHour';
+ // A fresh time-of-day band (sunrise/dusk/night/day → we narrate the named ones).
+ if (label !== lastLabel && (label === 'sunrise' || label === 'dusk' || label === 'night')) return label;
+
+ // A wanderer arriving — a rising edge in the detailed crowd count.
+ if (lastPedCount != null && (state.pedCount | 0) > lastPedCount) return 'npcArrived';
+
+ // The plaza filling up — a rising edge across the "busy" threshold.
+ const busy = (Number(state.crowd) || 0) >= 0.6;
+ if (busy && !lastBusy) return 'zoneBusy';
+
+ // Nothing new — keep the channel alive with calm ambiance.
+ return 'idleAmbiance';
+ }
+
+ return {
+ observe(state, now) {
+ if (!state) return null;
+ if (now - lastEmitAt < minGapMs) return null;
+
+ const event = pickEvent(state);
+
+ // Update memory AFTER picking so a rising edge is detected exactly once.
+ lastLabel = phaseLabel(state.phase);
+ lastGolden = isGoldenHour(state.phase);
+ lastBusy = (Number(state.crowd) || 0) >= 0.6;
+ lastPedCount = state.pedCount | 0;
+
+ const bank = LINES[event] || LINES.idleAmbiance;
+ const i = (rot[event] || 0) % bank.length;
+ rot[event] = i + 1;
+ lastEmitAt = now;
+
+ return {
+ text: fill(bank[i], ctx),
+ type: 'activity',
+ mood: EVENT_MOOD[event] || 'calm',
+ event,
+ };
+ },
+ reset() {
+ lastEmitAt = -Infinity;
+ lastLabel = null;
+ lastGolden = false;
+ lastBusy = false;
+ lastPedCount = null;
+ },
+ };
+}
diff --git a/src/agent-screen-mirror.js b/src/agent-screen-mirror.js
new file mode 100644
index 000000000..637c86bcd
--- /dev/null
+++ b/src/agent-screen-mirror.js
@@ -0,0 +1,807 @@
+// agent-screen-mirror.js — live copy-trade mirror cockpit for /agent-screen.
+//
+// Two columns: SOURCE (a target wallet's pump.fun trades, detected live) and
+// MIRROR (the agent's guarded replica of each one). A source buy lands on the
+// left; the agent re-quotes, sizes per the configured rule, and lands a matching
+// trade on the right — stamped with the real latency (submitted − detected) and
+// the actual fill it got. Every order passes the same server-side trade firewall
+// (per-trade cap, daily budget, price-impact breaker, kill switch); a rejected
+// order renders as a BLOCKED row with the reason, never a silent skip.
+//
+// Real wiring, no mocks:
+// • Source detection → GET /api/pump/trades-stream?mint=… (PumpPortal SSE),
+// filtered to the target wallet's trades.
+// • Re-quote → GET/POST /api/agents/:id/trade/quote (expected out,
+// price impact, guard preview).
+// • Replicate → POST /api/agents/:id/trade (server-signed from the
+// agent's own custodial wallet, firewall-enforced).
+// • Wall frame → POST /api/agent-screen-push (type:"trade") so the
+// /agents-live card paints the dual-column view.
+//
+// The owner drives the loop (their session can quote, trade, and push). A
+// non-owner viewer sees the panel in a read-only armed state and watches the
+// action through the pushed wall frame + activity log, exactly like the rest of
+// /agent-screen.
+
+// ── $THREE is the only coin the platform promotes. The mirror itself is generic,
+// coin-agnostic plumbing: it replicates whatever mint the SOURCE trade carries at
+// runtime. $THREE is simply the default mint we watch out of the box. CA below.
+const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+const MAX_ROWS = 60; // bound each column's DOM
+const MAX_WATCH_MINTS = 20; // trades-stream caps at 20 mints
+const PUSH_MIN_INTERVAL_MS = 1000; // throttle wall-frame pushes
+
+const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : 0);
+const clamp = (x, lo, hi) => Math.min(hi, Math.max(lo, x));
+
+// ── pure helpers (unit-tested in tests/agent-screen-mirror.test.js) ───────────
+
+/** Is this a usable Solana wallet / mint address? */
+export function isValidAddress(addr) {
+ return typeof addr === 'string' && BASE58_RE.test(addr.trim());
+}
+
+/** Short, copy-friendly label for a base58 address. */
+export function truncateAddr(addr, head = 4, tail = 4) {
+ const s = String(addr || '');
+ if (s.length <= head + tail + 1) return s;
+ return `${s.slice(0, head)}…${s.slice(-tail)}`;
+}
+
+/**
+ * Size a mirror BUY (in SOL) from the configured rule, then clamp to the
+ * per-trade cap and the minimum order. Sells mirror an exit and aren't sized
+ * here. Mirrors the server copy engine's rawOrderSol semantics exactly so the
+ * preview and the eventual fill agree.
+ *
+ * @returns {{ ok:true, order:number, raw:number } | { ok:false, reason:string, raw?:number }}
+ */
+export function sizeMirrorOrder(rule, {
+ leaderSol = 0, balanceSol = null,
+ fixedSol = 0, multiplier = 0, pctBalance = 0,
+ perTxCapSol = null, minOrderSol = 0,
+} = {}) {
+ let raw;
+ switch (rule) {
+ case 'multiplier': raw = num(leaderSol) * num(multiplier); break;
+ case 'pct_balance': raw = balanceSol == null ? NaN : num(balanceSol) * (num(pctBalance) / 100); break;
+ case 'fixed':
+ default: raw = num(fixedSol); break;
+ }
+ if (!Number.isFinite(raw) || raw <= 0) {
+ return { ok: false, reason: rule === 'pct_balance' && balanceSol == null ? 'sizing_unavailable' : 'zero_size' };
+ }
+ let order = raw;
+ if (perTxCapSol != null && num(perTxCapSol) > 0) order = Math.min(order, num(perTxCapSol));
+ const minOrder = num(minOrderSol);
+ if (minOrder > 0 && order < minOrder) return { ok: false, reason: 'below_min_order', raw };
+ return { ok: true, order, raw };
+}
+
+/** Latency of a mirrored order: submitted − detected, floored at 0 (ms). */
+export function computeLatency(detectedAt, submittedAt) {
+ const d = Number(detectedAt), s = Number(submittedAt);
+ if (!Number.isFinite(d) || !Number.isFinite(s)) return null;
+ return Math.max(0, Math.round(s - d));
+}
+
+// Human label for the guard/firewall codes the quote + trade endpoints return.
+const BLOCK_LABELS = {
+ kill_switch: 'Trading paused',
+ per_trade_cap: 'Over per-trade cap',
+ daily_budget: 'Daily budget reached',
+ max_positions: 'Too many open trades',
+ insufficient_sol: 'Wallet underfunded',
+ price_impact: 'Price impact too high',
+ insufficient_token_balance: 'Agent holds none',
+ spend_limit_exceeded: 'Spend limit reached',
+ spend_limit: 'Spend limit reached',
+ firewall_block: 'Firewall blocked',
+ graduated: 'Coin graduated',
+ zero_out: 'Buys zero tokens',
+ sizing_unavailable: 'Sizing unavailable',
+ below_min_order: 'Below minimum order',
+ zero_size: 'Sizes to zero',
+};
+
+/**
+ * Map a blocked quote/trade result to a { label, message } the UI renders on a
+ * blocked row. Prefers the server's actionable message when present.
+ */
+export function mapBlockedReason(blocked) {
+ const code = blocked?.code || blocked?.reason || 'blocked';
+ const label = BLOCK_LABELS[code] || 'Blocked';
+ const message = blocked?.message
+ || (code === 'sizing_unavailable' ? 'Set a balance source for % sizing, or switch sizing rule.'
+ : code === 'below_min_order' ? 'The sized order is below your minimum — raise the multiplier or lower the minimum.'
+ : code === 'zero_size' ? 'This rule sizes the order to zero — check the sizing values.'
+ : `Order rejected (${code}).`);
+ return { code, label, message };
+}
+
+/** Format a SOL amount compactly (trim trailing zeros). */
+export function fmtSol(v, dp = 4) {
+ const n = num(v);
+ if (n === 0) return '0';
+ const s = n.toFixed(dp).replace(/\.?0+$/, '');
+ return s || '0';
+}
+
+function fmtUsd(v) {
+ const n = Number(v);
+ if (!Number.isFinite(n)) return null;
+ if (n >= 1000) return `$${Math.round(n).toLocaleString()}`;
+ return `$${n.toFixed(2)}`;
+}
+
+function explorerTx(sig) {
+ return sig ? `https://solscan.io/tx/${sig}` : null;
+}
+
+const esc = (s) => String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+
+// ── the panel ─────────────────────────────────────────────────────────────────
+
+export class MirrorPanel {
+ /**
+ * @param {object} opts
+ * @param {HTMLElement} opts.body the panel body element to render into.
+ * @param {string} opts.agentId
+ * @param {string} [opts.agentName]
+ * @param {(msg:string)=>void} [opts.onToast]
+ */
+ constructor({ body, agentId, agentName = 'Agent', onToast = () => {} }) {
+ this.body = body;
+ this.agentId = agentId;
+ this.agentName = agentName;
+ this.toast = onToast;
+
+ this.isOwner = false;
+ this.csrfToken = '';
+ this.limits = null; // server trade limits (per_trade_sol, daily_budget_sol, …)
+ this.walletBalanceSol = null;
+ this.network = 'mainnet';
+
+ this.config = this.loadConfig();
+ this.es = null; // source EventSource
+ this.streamState = 'idle'; // idle | connecting | live | error
+ this.inFlight = new Set(); // signatures being mirrored (dedupe)
+ this.seenSigs = new Set();
+ this.rows = { source: [], mirror: [] };
+ this.lastRelay = null; // { latency, fill, blocked }
+ this.destroyed = false;
+
+ // offscreen canvas for the wall frame
+ this.frameCanvas = document.createElement('canvas');
+ this.frameCanvas.width = 640;
+ this.frameCanvas.height = 360;
+ this.lastPushAt = 0;
+ this.pushTimer = null;
+
+ this.renderShell();
+ this.init();
+ }
+
+ // ── persistence ──────────────────────────────────────────────────────────
+ get lsKey() { return `twx_mirror_cfg_${this.agentId}`; }
+
+ loadConfig() {
+ const base = {
+ targetWallet: '',
+ sizingRule: 'fixed',
+ fixedSol: 0.05,
+ multiplier: 0.25,
+ pctBalance: 5,
+ minOrderSol: 0.01,
+ watchMints: [THREE_MINT],
+ copySells: true,
+ };
+ try {
+ const saved = JSON.parse(localStorage.getItem(this.lsKey) || '{}');
+ if (saved && typeof saved === 'object') {
+ for (const k of Object.keys(base)) if (k in saved) base[k] = saved[k];
+ }
+ } catch { /* defaults */ }
+ if (!Array.isArray(base.watchMints) || !base.watchMints.length) base.watchMints = [THREE_MINT];
+ base.watchMints = base.watchMints.filter(isValidAddress).slice(0, MAX_WATCH_MINTS);
+ if (!['fixed', 'multiplier', 'pct_balance'].includes(base.sizingRule)) base.sizingRule = 'fixed';
+ return base;
+ }
+
+ saveConfig() {
+ try { localStorage.setItem(this.lsKey, JSON.stringify(this.config)); } catch { /* quota */ }
+ }
+
+ // ── boot ──────────────────────────────────────────────────────────────────
+ async init() {
+ // Owner probe: the trade-limits read is owner-gated, so a 200 means we can
+ // drive the loop; anything else means a read-only viewer.
+ try {
+ const r = await fetch(`/api/agents/${encodeURIComponent(this.agentId)}/trade/limits`, { credentials: 'include' });
+ if (r.ok) {
+ const j = await r.json().catch(() => ({}));
+ this.limits = j?.data?.limits || null;
+ this.isOwner = true;
+ } else {
+ this.isOwner = false;
+ }
+ } catch { this.isOwner = false; }
+
+ if (this.isOwner) {
+ this.csrfToken = await fetch('/api/csrf-token', { credentials: 'include' })
+ .then((r) => r.json()).then((j) => j.data?.token || j.token || '').catch(() => '');
+ }
+
+ if (this.destroyed) return;
+ this.render();
+ if (this.isOwner && isValidAddress(this.config.targetWallet)) this.arm();
+ }
+
+ // ── source stream ───────────────────────────────────────────────────────
+ arm() {
+ this.disarmStream();
+ const mints = (this.config.watchMints || []).filter(isValidAddress).slice(0, MAX_WATCH_MINTS);
+ if (!mints.length || !isValidAddress(this.config.targetWallet)) { this.render(); return; }
+
+ this.streamState = 'connecting';
+ this.render();
+
+ const url = `/api/pump/trades-stream?mint=${encodeURIComponent(mints.join(','))}`;
+ const es = new EventSource(url);
+ this.es = es;
+
+ es.addEventListener('open', () => { if (this.es === es) { this.streamState = 'live'; this.renderStatus(); } });
+ es.addEventListener('trade', (e) => {
+ let data; try { data = JSON.parse(e.data); } catch { return; }
+ this.onSourceTrade(data);
+ });
+ es.addEventListener('close', () => { /* server duration limit — onerror reconnects */ });
+ es.onerror = () => {
+ if (this.es !== es) return;
+ this.streamState = 'error';
+ this.renderStatus();
+ es.close();
+ this.es = null;
+ // trades-stream caps at 90s; reconnect transparently to keep watching.
+ if (!this.destroyed && isValidAddress(this.config.targetWallet)) {
+ clearTimeout(this._reconnect);
+ this._reconnect = setTimeout(() => { if (!this.destroyed) this.arm(); }, 1500);
+ }
+ };
+ }
+
+ disarmStream() {
+ clearTimeout(this._reconnect);
+ if (this.es) { try { this.es.close(); } catch { /* ok */ } this.es = null; }
+ this.streamState = 'idle';
+ }
+
+ onSourceTrade(data) {
+ if (this.destroyed) return;
+ const trader = data?.trader || null;
+ if (!trader || trader !== this.config.targetWallet) return; // not our target
+ const sig = data?.signature || data?.tx_signature || '';
+ if (sig && this.seenSigs.has(sig)) return;
+ if (sig) { this.seenSigs.add(sig); if (this.seenSigs.size > 4000) this.seenSigs.clear(); }
+
+ const side = data?.is_buy ? 'buy' : 'sell';
+ const detectedAt = Date.now();
+ const source = {
+ id: sig || `${detectedAt}-${Math.round(num(data?.sol_amount) * 1e6)}`,
+ side, mint: data?.mint || '',
+ solAmount: num(data?.sol_amount),
+ tokenAmount: num(data?.token_amount),
+ usd: data?.sol_value_usd ?? null,
+ signature: sig, detectedAt,
+ };
+ this.addRow('source', source);
+ this.replicate(source);
+ }
+
+ // ── re-quote + replicate ─────────────────────────────────────────────────
+ async replicate(source) {
+ const { mint, side, detectedAt } = source;
+ if (!isValidAddress(mint)) return;
+ if (source.signature) {
+ if (this.inFlight.has(source.signature)) return;
+ this.inFlight.add(source.signature);
+ }
+
+ try {
+ if (this.config.copySells === false && side === 'sell') {
+ this.addRow('mirror', { kind: 'blocked', source, ...mapBlockedReason({ code: 'sells_disabled', message: 'Sell mirroring is off for this agent.' }), latency: computeLatency(detectedAt, Date.now()) });
+ return;
+ }
+
+ // Size the order. Sells mirror an exit (sell the agent's whole holding).
+ let amount;
+ if (side === 'buy') {
+ if (this.config.sizingRule === 'pct_balance' && this.walletBalanceSol == null) {
+ await this.primeBalance(mint); // learn the wallet balance once
+ }
+ const sized = sizeMirrorOrder(this.config.sizingRule, {
+ leaderSol: source.solAmount,
+ balanceSol: this.walletBalanceSol,
+ fixedSol: this.config.fixedSol,
+ multiplier: this.config.multiplier,
+ pctBalance: this.config.pctBalance,
+ perTxCapSol: this.limits?.per_trade_sol ?? null,
+ minOrderSol: this.config.minOrderSol,
+ });
+ if (!sized.ok) {
+ this.addRow('mirror', { kind: 'blocked', source, ...mapBlockedReason({ code: sized.reason }), latency: computeLatency(detectedAt, Date.now()) });
+ this.narrate(`Mirror skipped ${truncateAddr(mint)} — ${mapBlockedReason({ code: sized.reason }).label.toLowerCase()}`);
+ return;
+ }
+ amount = sized.order;
+ } else {
+ amount = 'max';
+ }
+
+ // Re-quote (expected out + price impact + guard preview).
+ const quote = await this.quote({ side, mint, amount });
+ if (quote && quote.wallet_balance_sol != null) this.walletBalanceSol = num(quote.wallet_balance_sol);
+ if (quote && quote.allowed === false && quote.blocked_reason) {
+ this.addRow('mirror', { kind: 'blocked', source, ...mapBlockedReason(quote.blocked_reason), latency: computeLatency(detectedAt, Date.now()) });
+ this.narrate(`Mirror blocked ${truncateAddr(mint)} — ${mapBlockedReason(quote.blocked_reason).label.toLowerCase()}`);
+ return;
+ }
+
+ // Execute the guarded, server-signed replica.
+ const res = await this.trade({ side, mint, amount });
+ const submittedAt = Date.now();
+ const latency = computeLatency(detectedAt, submittedAt);
+
+ if (res.ok) {
+ const d = res.data || {};
+ const fillSol = side === 'buy' ? null : num(d.sol_received);
+ const fillTokens = side === 'buy' ? d.tokens_received : d.tokens_sold;
+ const row = {
+ kind: 'fill', source, side, mint,
+ solSpent: side === 'buy' ? num(d.sol_spent) : null,
+ solReceived: fillSol,
+ tokens: fillTokens,
+ priceImpact: d.price_impact_pct ?? quote?.price_impact_pct ?? null,
+ signature: d.signature, explorer: d.explorer || explorerTx(d.signature),
+ latency,
+ };
+ if (d.new_balance_sol != null) this.walletBalanceSol = num(d.new_balance_sol);
+ this.addRow('mirror', row);
+ this.lastRelay = { latency, fill: side === 'buy' ? `${fmtSol(row.solSpent)} SOL` : `${fmtSol(fillSol)} SOL`, blocked: false };
+ this.renderRelay();
+ this.toast(`Mirrored ${side} · ${latency}ms`);
+ this.narrate(`Mirror ${side} ${truncateAddr(mint)} filled — ${latency}ms latency`);
+ } else {
+ const blocked = mapBlockedReason(res);
+ this.addRow('mirror', { kind: 'blocked', source, ...blocked, latency });
+ this.lastRelay = { latency, fill: null, blocked: true };
+ this.renderRelay();
+ this.narrate(`Mirror blocked ${truncateAddr(mint)} — ${blocked.label.toLowerCase()}`);
+ }
+ } catch (err) {
+ console.warn('[mirror] replicate failed', err);
+ this.addRow('mirror', { kind: 'blocked', source, ...mapBlockedReason({ code: 'network', message: 'Network error reaching the trade engine — will retry on the next signal.' }), latency: computeLatency(detectedAt, Date.now()) });
+ } finally {
+ if (source.signature) this.inFlight.delete(source.signature);
+ }
+ }
+
+ async primeBalance(mint) {
+ // A throwaway minimal buy quote just reads back wallet_balance_sol so
+ // pct_balance sizing has a real number. Never executes.
+ try {
+ const q = await this.quote({ side: 'buy', mint, amount: 0.001 });
+ if (q && q.wallet_balance_sol != null) this.walletBalanceSol = num(q.wallet_balance_sol);
+ } catch { /* leave null → sizing will surface 'sizing_unavailable' */ }
+ }
+
+ async quote({ side, mint, amount }) {
+ const r = await fetch(`/api/agents/${encodeURIComponent(this.agentId)}/trade/quote`, {
+ method: 'POST', credentials: 'include',
+ headers: { 'content-type': 'application/json', ...(this.csrfToken ? { 'x-csrf-token': this.csrfToken } : {}) },
+ body: JSON.stringify({ side, mint, amount, network: this.network }),
+ });
+ const j = await r.json().catch(() => ({}));
+ if (!r.ok) return { allowed: false, blocked_reason: { code: j.error || 'quote_failed', message: j.message || j.error_description || 'Could not price the trade.' } };
+ return j.data || {};
+ }
+
+ async trade({ side, mint, amount }) {
+ const idem = (crypto?.randomUUID?.() || `${Date.now()}-${Math.round(Math.random() * 1e9)}`);
+ const r = await fetch(`/api/agents/${encodeURIComponent(this.agentId)}/trade`, {
+ method: 'POST', credentials: 'include',
+ headers: { 'content-type': 'application/json', ...(this.csrfToken ? { 'x-csrf-token': this.csrfToken } : {}) },
+ body: JSON.stringify({ side, mint, amount, network: this.network, idempotency_key: idem }),
+ });
+ const j = await r.json().catch(() => ({}));
+ if (r.ok) return { ok: true, data: j.data || {} };
+ return { ok: false, code: j.error || 'trade_failed', message: j.message || j.error_description || 'Trade rejected.', detail: j.detail || null };
+ }
+
+ // ── rows + render ──────────────────────────────────────────────────────────
+ addRow(col, row) {
+ this.rows[col].unshift(row);
+ while (this.rows[col].length > MAX_ROWS) this.rows[col].pop();
+ this.renderColumns();
+ this.schedulePush();
+ }
+
+ renderShell() {
+ this.body.innerHTML = `
+ <div class="asc-mir" id="asc-mir">
+ <div class="asc-mir-head" id="asc-mir-head"></div>
+ <div class="asc-mir-cols">
+ <div class="asc-mir-col">
+ <div class="asc-mir-col-head"><span class="asc-mir-dot src"></span>Source</div>
+ <div class="asc-mir-list" id="asc-mir-source"></div>
+ </div>
+ <div class="asc-mir-col">
+ <div class="asc-mir-col-head"><span class="asc-mir-dot mir"></span>Mirror</div>
+ <div class="asc-mir-list" id="asc-mir-mirror"></div>
+ </div>
+ </div>
+ <div class="asc-mir-relay" id="asc-mir-relay"></div>
+ <div class="asc-mir-controls" id="asc-mir-controls"></div>
+ </div>`;
+ this.el = {
+ head: this.body.querySelector('#asc-mir-head'),
+ source: this.body.querySelector('#asc-mir-source'),
+ mirror: this.body.querySelector('#asc-mir-mirror'),
+ relay: this.body.querySelector('#asc-mir-relay'),
+ controls: this.body.querySelector('#asc-mir-controls'),
+ };
+ }
+
+ render() {
+ this.renderHead();
+ this.renderColumns();
+ this.renderRelay();
+ this.renderControls();
+ }
+
+ renderHead() {
+ const tw = this.config.targetWallet;
+ const rule = this.config.sizingRule;
+ const ruleLabel = rule === 'fixed' ? `Fixed ${fmtSol(this.config.fixedSol)} SOL`
+ : rule === 'multiplier' ? `${fmtSol(this.config.multiplier)}× source`
+ : `${fmtSol(this.config.pctBalance)}% balance`;
+ this.el.head.innerHTML = `
+ <div class="asc-mir-target">
+ ${isValidAddress(tw)
+ ? `<button class="asc-mir-wallet" id="asc-mir-copy" title="Copy target wallet">
+ <span class="asc-mir-wallet-label">Target</span>
+ <code>${esc(truncateAddr(tw, 5, 5))}</code>
+ <span class="asc-mir-copy-ic">⧉</span>
+ </button>`
+ : `<span class="asc-mir-wallet asc-mir-wallet--unset">No target wallet</span>`}
+ </div>
+ <span class="asc-mir-rule" title="Active sizing rule">${esc(ruleLabel)}</span>
+ ${this.renderStatusBadge()}`;
+ this.el.head.querySelector('#asc-mir-copy')?.addEventListener('click', () => {
+ navigator.clipboard?.writeText(tw).then(() => this.toast('Target wallet copied')).catch(() => {});
+ });
+ }
+
+ renderStatusBadge() {
+ if (!this.isOwner) return `<span class="asc-mir-status armed">read-only</span>`;
+ if (!isValidAddress(this.config.targetWallet)) return `<span class="asc-mir-status off">not armed</span>`;
+ const map = {
+ connecting: ['armed', 'connecting…'],
+ live: ['live', 'armed'],
+ error: ['err', 'reconnecting…'],
+ idle: ['off', 'idle'],
+ };
+ const [cls, label] = map[this.streamState] || map.idle;
+ return `<span class="asc-mir-status ${cls}">${label}</span>`;
+ }
+
+ renderStatus() {
+ const badge = this.el.head?.querySelector('.asc-mir-status');
+ if (badge) badge.outerHTML = this.renderStatusBadge();
+ this.renderColumns();
+ }
+
+ renderColumns() {
+ this.renderColumn('source');
+ this.renderColumn('mirror');
+ }
+
+ renderColumn(col) {
+ const host = this.el[col];
+ if (!host) return;
+ const rows = this.rows[col];
+ if (!rows.length) {
+ host.innerHTML = `<div class="asc-mir-empty">${esc(this.emptyText(col))}</div>`;
+ return;
+ }
+ host.innerHTML = rows.map((r) => col === 'source' ? this.sourceRowHTML(r) : this.mirrorRowHTML(r)).join('');
+ }
+
+ emptyText(col) {
+ if (!this.isOwner) return col === 'source' ? 'The owner controls this mirror.' : 'Replicas appear here when the owner is armed.';
+ if (!isValidAddress(this.config.targetWallet)) return 'Set a target wallet below to arm the mirror.';
+ if (this.streamState === 'connecting') return col === 'source' ? 'Watching the target wallet…' : 'Armed and waiting.';
+ if (this.streamState === 'error') return 'Reconnecting to the trade stream…';
+ return col === 'source'
+ ? 'No trades from the target yet — the mirror is armed and waiting.'
+ : 'No replicas yet.';
+ }
+
+ sourceRowHTML(r) {
+ const verb = r.side === 'buy' ? 'bought' : 'sold';
+ const amt = r.side === 'buy' ? `${fmtSol(r.solAmount)} SOL` : `${fmtSol(r.solAmount)} SOL`;
+ const usd = fmtUsd(r.usd);
+ const ex = explorerTx(r.signature);
+ return `<div class="asc-mir-row ${r.side}">
+ <span class="asc-mir-side ${r.side}">${r.side}</span>
+ <div class="asc-mir-row-main">
+ <div class="asc-mir-row-top">Target ${verb} <strong>${esc(amt)}</strong>${usd ? ` <span class="asc-mir-usd">${esc(usd)}</span>` : ''}</div>
+ <div class="asc-mir-row-sub"><code>${esc(truncateAddr(r.mint, 4, 4))}</code>${ex ? ` · <a href="${esc(ex)}" target="_blank" rel="noopener">tx ↗</a>` : ''}</div>
+ </div>
+ </div>`;
+ }
+
+ mirrorRowHTML(r) {
+ if (r.kind === 'blocked') {
+ return `<div class="asc-mir-row blocked">
+ <span class="asc-mir-side blocked">blocked</span>
+ <div class="asc-mir-row-main">
+ <div class="asc-mir-row-top"><strong>${esc(r.label)}</strong>${r.latency != null ? ` <span class="asc-mir-lat">${r.latency}ms</span>` : ''}</div>
+ <div class="asc-mir-row-sub">${esc(r.message)}</div>
+ </div>
+ </div>`;
+ }
+ const verb = r.side === 'buy' ? 'bought' : 'sold';
+ const fill = r.side === 'buy' ? `${fmtSol(r.solSpent)} SOL` : `${fmtSol(r.solReceived)} SOL`;
+ const impact = r.priceImpact != null ? ` · ${Number(r.priceImpact).toFixed(2)}% impact` : '';
+ const ex = r.explorer || explorerTx(r.signature);
+ return `<div class="asc-mir-row ${r.side} fill">
+ <span class="asc-mir-side ${r.side}">${r.side}</span>
+ <div class="asc-mir-row-main">
+ <div class="asc-mir-row-top">Mirror ${verb} <strong>${esc(fill)}</strong> <span class="asc-mir-lat ok" title="latency = submitted − detected">${r.latency}ms</span></div>
+ <div class="asc-mir-row-sub"><code>${esc(truncateAddr(r.mint, 4, 4))}</code>${esc(impact)}${ex ? ` · <a href="${esc(ex)}" target="_blank" rel="noopener">tx ↗</a>` : ''}</div>
+ </div>
+ </div>`;
+ }
+
+ renderRelay() {
+ if (!this.el.relay) return;
+ if (!this.lastRelay) {
+ this.el.relay.innerHTML = `<span class="asc-mir-relay-idle">Latency &amp; fill appear here on the first mirrored order.</span>`;
+ return;
+ }
+ const { latency, fill, blocked } = this.lastRelay;
+ this.el.relay.innerHTML = `
+ <div class="asc-mir-relay-stat"><span class="k">Latency</span><span class="v">${latency != null ? `${latency}ms` : '—'}</span></div>
+ <div class="asc-mir-relay-stat"><span class="k">Last fill</span><span class="v ${blocked ? 'blocked' : ''}">${blocked ? 'blocked' : esc(fill || '—')}</span></div>`;
+ }
+
+ renderControls() {
+ const c = this.el.controls;
+ if (!c) return;
+ if (!this.isOwner) {
+ c.innerHTML = `<div class="asc-mir-readonly">You're watching this agent. Its owner sets the target wallet, sizing rule, and spend caps.</div>`;
+ return;
+ }
+ const cfg = this.config;
+ const lim = this.limits || {};
+ const sizingFields = cfg.sizingRule === 'fixed'
+ ? `<label class="asc-mir-field"><span>Fixed SOL</span><input type="number" step="0.001" min="0" id="mir-fixed" value="${esc(cfg.fixedSol)}"></label>`
+ : cfg.sizingRule === 'multiplier'
+ ? `<label class="asc-mir-field"><span>Multiplier</span><input type="number" step="0.05" min="0" id="mir-mult" value="${esc(cfg.multiplier)}"></label>`
+ : `<label class="asc-mir-field"><span>% of balance</span><input type="number" step="0.5" min="0" max="100" id="mir-pct" value="${esc(cfg.pctBalance)}"></label>`;
+ c.innerHTML = `
+ <details class="asc-mir-cfg" ${isValidAddress(cfg.targetWallet) ? '' : 'open'}>
+ <summary>Mirror settings</summary>
+ <div class="asc-mir-cfg-body">
+ <label class="asc-mir-field asc-mir-field--wide">
+ <span>Target wallet</span>
+ <input type="text" id="mir-target" spellcheck="false" placeholder="Solana wallet address" value="${esc(cfg.targetWallet)}">
+ </label>
+ <div class="asc-mir-row2">
+ <label class="asc-mir-field">
+ <span>Sizing rule</span>
+ <select id="mir-rule">
+ <option value="fixed" ${cfg.sizingRule === 'fixed' ? 'selected' : ''}>Fixed</option>
+ <option value="multiplier" ${cfg.sizingRule === 'multiplier' ? 'selected' : ''}>Multiplier</option>
+ <option value="pct_balance" ${cfg.sizingRule === 'pct_balance' ? 'selected' : ''}>% of balance</option>
+ </select>
+ </label>
+ ${sizingFields}
+ </div>
+ <label class="asc-mir-field asc-mir-field--wide">
+ <span>Watched mints (comma-separated)</span>
+ <input type="text" id="mir-mints" spellcheck="false" value="${esc((cfg.watchMints || []).join(', '))}">
+ </label>
+ <div class="asc-mir-row2">
+ <label class="asc-mir-field">
+ <span>Min order SOL</span>
+ <input type="number" step="0.001" min="0" id="mir-min" value="${esc(cfg.minOrderSol)}">
+ </label>
+ <label class="asc-mir-field asc-mir-check">
+ <input type="checkbox" id="mir-sells" ${cfg.copySells ? 'checked' : ''}>
+ <span>Mirror sells</span>
+ </label>
+ </div>
+ <div class="asc-mir-caps">
+ <span class="asc-mir-caps-title">Spend caps (firewall)</span>
+ <div class="asc-mir-caps-grid">
+ <label class="asc-mir-field"><span>Per-trade SOL</span><input type="number" step="0.01" min="0" id="mir-cap" value="${lim.per_trade_sol ?? ''}" placeholder="none"></label>
+ <label class="asc-mir-field"><span>Daily budget SOL</span><input type="number" step="0.01" min="0" id="mir-daily" value="${lim.daily_budget_sol ?? ''}" placeholder="none"></label>
+ <label class="asc-mir-field"><span>Max impact %</span><input type="number" step="0.5" min="0" max="100" id="mir-impact" value="${lim.max_price_impact_pct ?? ''}" placeholder="15"></label>
+ </div>
+ </div>
+ <div class="asc-mir-actions">
+ <button class="asc-mir-btn primary" id="mir-arm">${isValidAddress(cfg.targetWallet) ? 'Update &amp; arm' : 'Arm mirror'}</button>
+ ${isValidAddress(cfg.targetWallet) ? `<button class="asc-mir-btn" id="mir-disarm">Disarm</button>` : ''}
+ </div>
+ <div class="asc-mir-cfg-msg" id="mir-msg"></div>
+ </div>
+ </details>`;
+ this.wireControls();
+ }
+
+ wireControls() {
+ const c = this.el.controls;
+ const ruleSel = c.querySelector('#mir-rule');
+ ruleSel?.addEventListener('change', () => {
+ this.config.sizingRule = ruleSel.value;
+ this.saveConfig();
+ this.renderControls(); // swap the sizing field
+ });
+ c.querySelector('#mir-arm')?.addEventListener('click', () => this.applyControls());
+ c.querySelector('#mir-disarm')?.addEventListener('click', () => {
+ this.disarmStream();
+ this.toast('Mirror disarmed');
+ this.render();
+ });
+ }
+
+ async applyControls() {
+ const c = this.el.controls;
+ const msg = c.querySelector('#mir-msg');
+ const val = (id) => c.querySelector(`#${id}`)?.value?.trim() ?? '';
+ const target = val('mir-target');
+ if (!isValidAddress(target)) { if (msg) { msg.className = 'asc-mir-cfg-msg err'; msg.textContent = 'Enter a valid Solana wallet address.'; } return; }
+
+ const mints = val('mir-mints').split(',').map((m) => m.trim()).filter(Boolean);
+ const validMints = mints.filter(isValidAddress).slice(0, MAX_WATCH_MINTS);
+ if (!validMints.length) { if (msg) { msg.className = 'asc-mir-cfg-msg err'; msg.textContent = 'Add at least one valid mint to watch.'; } return; }
+
+ this.config.targetWallet = target;
+ this.config.watchMints = validMints;
+ this.config.sizingRule = val('mir-rule') || this.config.sizingRule;
+ if (c.querySelector('#mir-fixed')) this.config.fixedSol = num(val('mir-fixed'));
+ if (c.querySelector('#mir-mult')) this.config.multiplier = num(val('mir-mult'));
+ if (c.querySelector('#mir-pct')) this.config.pctBalance = num(val('mir-pct'));
+ this.config.minOrderSol = num(val('mir-min'));
+ this.config.copySells = !!c.querySelector('#mir-sells')?.checked;
+ this.saveConfig();
+
+ // Persist spend caps through the real owner endpoint (the firewall the
+ // replica is held to). Only send fields the owner actually set.
+ const capPatch = {};
+ const cap = val('mir-cap'), daily = val('mir-daily'), impact = val('mir-impact');
+ if (cap !== '') capPatch.per_trade_sol = num(cap);
+ if (daily !== '') capPatch.daily_budget_sol = num(daily);
+ if (impact !== '') capPatch.max_price_impact_pct = num(impact);
+ if (Object.keys(capPatch).length) {
+ try {
+ const r = await fetch(`/api/agents/${encodeURIComponent(this.agentId)}/trade/limits`, {
+ method: 'PUT', credentials: 'include',
+ headers: { 'content-type': 'application/json', ...(this.csrfToken ? { 'x-csrf-token': this.csrfToken } : {}) },
+ body: JSON.stringify(capPatch),
+ });
+ const j = await r.json().catch(() => ({}));
+ if (r.ok) this.limits = j?.data?.limits || this.limits;
+ else if (msg) { msg.className = 'asc-mir-cfg-msg err'; msg.textContent = j.message || 'Could not save spend caps.'; }
+ } catch { if (msg) { msg.className = 'asc-mir-cfg-msg err'; msg.textContent = 'Network error saving spend caps.'; } }
+ }
+
+ if (msg) { msg.className = 'asc-mir-cfg-msg ok'; msg.textContent = 'Armed — watching the target wallet.'; }
+ this.toast('Mirror armed');
+ this.render();
+ this.arm();
+ }
+
+ // ── wall frame + narration ─────────────────────────────────────────────────
+ narrate(text) {
+ if (!this.isOwner || !text) return;
+ // Fire-and-forget activity line so the relay reads on the wall + log.
+ fetch('/api/agent-screen-push', {
+ method: 'POST', credentials: 'include',
+ headers: { 'content-type': 'application/json', ...(this.csrfToken ? { 'x-csrf-token': this.csrfToken } : {}) },
+ body: JSON.stringify({ agentId: this.agentId, frame: { activity: text.slice(0, 300), type: 'trade' } }),
+ }).catch(() => {});
+ }
+
+ schedulePush() {
+ if (!this.isOwner) return;
+ const now = Date.now();
+ const since = now - this.lastPushAt;
+ if (since >= PUSH_MIN_INTERVAL_MS) { this.pushFrame(); return; }
+ clearTimeout(this.pushTimer);
+ this.pushTimer = setTimeout(() => this.pushFrame(), PUSH_MIN_INTERVAL_MS - since);
+ }
+
+ pushFrame() {
+ if (this.destroyed || !this.isOwner) return;
+ this.lastPushAt = Date.now();
+ const dataUrl = this.drawFrame();
+ if (!dataUrl) return;
+ fetch('/api/agent-screen-push', {
+ method: 'POST', credentials: 'include',
+ headers: { 'content-type': 'application/json', ...(this.csrfToken ? { 'x-csrf-token': this.csrfToken } : {}) },
+ body: JSON.stringify({ agentId: this.agentId, frame: { data: dataUrl, activity: this.lastRelay ? `Mirror · ${this.lastRelay.latency}ms` : 'Copy-trade mirror', type: 'trade' } }),
+ }).catch(() => {});
+ }
+
+ // Paint the dual-column view to the offscreen canvas → the /agents-live card
+ // renders this verbatim. Real data only (the rows we actually mirrored).
+ drawFrame() {
+ const cv = this.frameCanvas;
+ const ctx = cv.getContext('2d');
+ if (!ctx) return null;
+ const W = cv.width, H = cv.height;
+ ctx.fillStyle = '#070708'; ctx.fillRect(0, 0, W, H);
+
+ ctx.fillStyle = '#f4f4f5';
+ ctx.font = '700 20px system-ui, sans-serif';
+ ctx.fillText('Copy-Trade Mirror', 20, 34);
+ ctx.fillStyle = 'rgba(255,255,255,0.5)';
+ ctx.font = '500 13px system-ui, sans-serif';
+ ctx.fillText(`Target ${truncateAddr(this.config.targetWallet, 5, 5)}`, 20, 54);
+ if (this.lastRelay) {
+ ctx.textAlign = 'right';
+ ctx.fillStyle = this.lastRelay.blocked ? '#fda4af' : '#86efac';
+ ctx.font = '700 14px system-ui, sans-serif';
+ ctx.fillText(this.lastRelay.blocked ? 'BLOCKED' : `${this.lastRelay.latency}ms · ${this.lastRelay.fill || ''}`, W - 20, 50);
+ ctx.textAlign = 'left';
+ }
+
+ const colY = 78, colH = H - colY - 18, colW = (W - 60) / 2;
+ this.drawColumn(ctx, 20, colY, colW, colH, 'SOURCE', this.rows.source, 'rgba(255,255,255,0.85)');
+ this.drawColumn(ctx, 40 + colW, colY, colW, colH, 'MIRROR', this.rows.mirror, '#cbd5e1');
+ try { return cv.toDataURL('image/jpeg', 0.72); } catch { return null; }
+ }
+
+ drawColumn(ctx, x, y, w, h, title, rows, color) {
+ ctx.fillStyle = 'rgba(255,255,255,0.06)';
+ ctx.fillRect(x, y, w, h);
+ ctx.fillStyle = 'rgba(255,255,255,0.45)';
+ ctx.font = '700 12px system-ui, sans-serif';
+ ctx.fillText(title, x + 12, y + 22);
+
+ ctx.font = '500 13px system-ui, sans-serif';
+ let ry = y + 46;
+ const lineH = 38;
+ for (const r of rows.slice(0, Math.floor((h - 40) / lineH))) {
+ const blocked = r.kind === 'blocked';
+ ctx.fillStyle = blocked ? '#fda4af' : (r.side === 'buy' ? '#86efac' : '#fca5a5');
+ ctx.font = '700 11px system-ui, sans-serif';
+ ctx.fillText(blocked ? 'BLOCKED' : String(r.side || '').toUpperCase(), x + 12, ry);
+ ctx.fillStyle = color;
+ ctx.font = '500 13px system-ui, sans-serif';
+ let label;
+ if (title === 'SOURCE') label = `${fmtSol(r.solAmount)} SOL`;
+ else if (blocked) label = r.label;
+ else label = r.side === 'buy' ? `${fmtSol(r.solSpent)} SOL · ${r.latency}ms` : `${fmtSol(r.solReceived)} SOL · ${r.latency}ms`;
+ ctx.fillText(String(label).slice(0, 28), x + 64, ry);
+ ry += lineH;
+ if (ry > y + h - 12) break;
+ }
+ if (!rows.length) {
+ ctx.fillStyle = 'rgba(255,255,255,0.25)';
+ ctx.font = '400 12px system-ui, sans-serif';
+ ctx.fillText(title === 'SOURCE' ? 'Waiting for target…' : 'Armed', x + 12, y + 46);
+ }
+ }
+
+ destroy() {
+ this.destroyed = true;
+ this.disarmStream();
+ clearTimeout(this.pushTimer);
+ }
+}
diff --git a/src/agent-screen-runcmd.js b/src/agent-screen-runcmd.js
new file mode 100644
index 000000000..afb5b7c07
--- /dev/null
+++ b/src/agent-screen-runcmd.js
@@ -0,0 +1,97 @@
+// agent-screen-runcmd.js — pure run-command builder for the deploy-to-wall wizard.
+//
+// The /agent-screen setup wizard turns a selected agent + a freshly minted
+// AGENT_JWT into the exact command an owner runs to start their caster. The
+// command is built from REAL values only — the selected agentId, the minted
+// key, and the caster's documented env (see workers/agent-screen-worker/README).
+// No placeholder the user must guess, except the two Browserbase credentials
+// that genuinely come from the user's own Browserbase account.
+//
+// Kept dependency-free and side-effect-free so the builder is unit-testable in
+// isolation (tests/agent-screen-runcmd.test.js) — the wizard imports both the
+// raw command (for clipboard) and the highlighted form (for display).
+
+// Path the caster POSTs frames to. Joined onto the viewer's origin so a command
+// copied from a preview/staging host targets that same host, not prod.
+export const PUSH_PATH = '/api/agent-screen-push';
+// Directory the command is run from + the Docker image tag it builds.
+export const WORKER_DIR = 'workers/agent-screen-worker';
+export const IMAGE_TAG = 'agent-screen-worker';
+
+// The three runtimes the wizard offers, in tab order.
+export const RUNTIMES = ['local', 'docker', 'bb'];
+
+export const RUNTIME_LABELS = {
+ local: 'Local (npm)',
+ docker: 'Docker',
+ bb: 'Browserbase',
+};
+
+// Browserbase keys are the only values the user supplies themselves — they come
+// from the user's Browserbase account, not from three.ws. Marked as explicit
+// angle-bracket placeholders so it's obvious they must be filled in.
+const BB_PLACEHOLDERS = [
+ ['BROWSERBASE_API_KEY', '<your-bb-key>'],
+ ['BROWSERBASE_PROJECT_ID', '<your-bb-project>'],
+];
+
+function normalizeRuntime(runtime) {
+ return RUNTIMES.includes(runtime) ? runtime : 'local';
+}
+
+// The ordered [key, value] env pairs a runtime needs. AGENT_ID / AGENT_JWT /
+// PUSH_URL are required for every runtime; Browserbase adds its two creds.
+export function runtimeEnv({ runtime = 'local', agentId = '', agentJwt = '', origin = 'https://three.ws' } = {}) {
+ const env = [
+ ['AGENT_ID', agentId],
+ ['AGENT_JWT', agentJwt],
+ ['PUSH_URL', `${origin}${PUSH_PATH}`],
+ ];
+ if (normalizeRuntime(runtime) === 'bb') env.push(...BB_PLACEHOLDERS);
+ return env;
+}
+
+// Single-line command suitable for the clipboard. Real values inlined; no
+// hidden placeholders beyond the Browserbase creds on the `bb` runtime.
+export function buildRunCommand(opts = {}) {
+ const runtime = normalizeRuntime(opts.runtime);
+ const env = runtimeEnv({ ...opts, runtime });
+ if (runtime === 'docker') {
+ const flags = env.map(([k, v]) => `-e ${k}=${v}`).join(' ');
+ return `docker build -t ${IMAGE_TAG} . && docker run ${flags} ${IMAGE_TAG}`;
+ }
+ const prefix = env.map(([k, v]) => `${k}=${v}`).join(' ');
+ return `${prefix} npm start`;
+}
+
+function esc(s) {
+ return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+}
+
+// Multi-line, syntax-highlighted command for the <pre> display. Derived from the
+// same runtimeEnv() the raw command uses, so the shown command and the copied
+// command never drift. Returns an HTML string (callers set it as innerHTML on a
+// trusted, escaped-by-this-fn block).
+export function buildRunCommandHtml(opts = {}) {
+ const runtime = normalizeRuntime(opts.runtime);
+ const env = runtimeEnv({ ...opts, runtime });
+ const kv = ([k, v]) => `<span class="cmd-key">${esc(k)}</span>=<span class="cmd-val">${esc(v)}</span>`;
+
+ if (runtime === 'docker') {
+ const lines = [
+ `<span class="cmd-comment"># from ${WORKER_DIR}/</span>`,
+ `<span class="cmd-run">docker build</span> -t ${IMAGE_TAG} . && \\`,
+ `<span class="cmd-run">docker run</span> \\`,
+ ...env.map((e) => ` -e ${kv(e)} \\`),
+ ` ${IMAGE_TAG}`,
+ ];
+ return lines.join('\n');
+ }
+
+ const lines = [
+ `<span class="cmd-comment"># from ${WORKER_DIR}/</span>`,
+ ...env.map((e) => `${kv(e)} \\`),
+ `<span class="cmd-run">npm start</span>`,
+ ];
+ return lines.join('\n');
+}
diff --git a/src/agent-screen-stage.js b/src/agent-screen-stage.js
new file mode 100644
index 000000000..5bba30ea7
--- /dev/null
+++ b/src/agent-screen-stage.js
@@ -0,0 +1,585 @@
+// /agent-screen Stage Show — the always-live host loop (Moonshot 08).
+//
+// Turns the avatar-cam panel on /agent-screen into a stage where the agent
+// performs a show that never goes dead: it opens, riffs, reads audience
+// questions typed into the Stage composer and answers them, shouts out the
+// night's top $THREE tipper, and runs rounds of its format's game — looping
+// forever, never silent.
+//
+// This module owns only the CLIENT half of the loop. The decision brain is the
+// pure, Colyseus-free ShowDirector (multiplayer/src/stage-show.js) — the same
+// engine the Living Stages rooms shell. Here we:
+// 1. ask the director for the next BEAT on a fixed cadence,
+// 2. turn that beat + live context into the host's actual words via the real
+// multi-LLM router (POST /api/brain/chat, SSE),
+// 3. speak the words with real TTS (POST /api/tts/speak) and drive lip-sync +
+// a per-beat emote on the live avatar (AnimationManager + LipsyncDriver),
+// 4. feed real, settled on-chain $THREE tips (GET /api/stage/tip) into the
+// director so a fresh tip pre-empts the next beat as a shoutout, and
+// 5. append a beat-labeled transcript line locally + best-effort to the
+// agent's live-wall activity (POST /api/agent-screen-push).
+//
+// No mocks: every word is generated, every voice is synthesized, every tip is a
+// real settlement read off the show ledger. When the brain or TTS is briefly
+// unreachable the show falls to a safe spoken beat and a text-only transcript
+// line rather than going quiet — a failsafe, not fake data.
+
+import { BEAT, ShowDirector } from '../multiplayer/src/stage-show.js';
+import { LipsyncDriver, tapAudioElement } from './voice/lipsync-driver.js';
+import { AvatarMouthTarget } from './voice/avatar-morph-target.js';
+
+// Free, anon-allowed model so the show runs whether or not the viewer is signed
+// in (mirrors api/brain/chat.js' ANON_BRAIN_PROVIDERS gate). Short replies — the
+// lines are read aloud, so we cap tokens hard and ask for 1–3 sentences.
+const BRAIN_PROVIDER = 'gpt-oss-120b';
+const BRAIN_MAX_TOKENS = 220;
+const LINE_MAX_CHARS = 360; // TTS-friendly spoken length
+
+// Cadence. A beat = generate → speak → settle, then a short breath before the
+// next. Bounded so the host has rhythm without burning the LLM/TTS budget when a
+// viewer leaves the tab open (the loop also pauses entirely when hidden).
+const INTER_BEAT_MS = 900;
+const TIP_POLL_MS = 12_000; // poll the settled-tip ledger on a calm cadence
+const SPEAK_SAFETY_MS = 22_000; // hard cap on a single utterance's audio wait
+
+// One $THREE = 1e6 atomic units (6 decimals), matching the on-chain mint.
+const THREE_DECIMALS = 1_000_000;
+
+// Per-beat upper-body emote, retargeted onto whatever humanoid rig is loaded via
+// the canonical clip library. All confirmed present in /animations/manifest.json.
+const BEAT_EMOTE = {
+ [BEAT.OPENER]: 'wave',
+ [BEAT.TIP_SHOUTOUT]: 'celebrate',
+ [BEAT.ANSWER]: 'reaction',
+ [BEAT.BANTER]: 'av-call-me',
+ [BEAT.GAME]: 'taunt',
+};
+const BEAT_LABEL = {
+ [BEAT.OPENER]: 'OPENER',
+ [BEAT.TIP_SHOUTOUT]: 'TIP SHOUTOUT',
+ [BEAT.ANSWER]: 'ANSWER',
+ [BEAT.BANTER]: 'BANTER',
+ [BEAT.GAME]: 'GAME',
+};
+// Clips the stage needs on top of the idle the cam already loads.
+const STAGE_CLIPS = ['wave', 'celebrate', 'reaction', 'av-call-me', 'taunt'];
+
+// Last-resort spoken lines, used ONLY when the brain router is unreachable so the
+// show never goes dead. Not content — a failsafe (CLAUDE.md rule 9). Rotated by
+// index so two identical lines never play back to back.
+const SAFE_FILLER = [
+ 'Stay with me — we are just getting warmed up out here.',
+ 'The stage is live and the night is young. What should we get into next?',
+ 'I love this crowd already. Keep it coming.',
+ 'Give it up for everyone tuning in right now — you make the show.',
+];
+
+export class StageShow {
+ /**
+ * @param {object} opts
+ * @param {string} opts.agentId
+ * @param {() => string} opts.getHostName
+ * @param {() => any} opts.getAvatar live avatar Object3D (for lip-sync)
+ * @param {() => any} opts.getAnimManager AnimationManager driving the avatar
+ * @param {() => (AudioContext|null)} opts.ensureAudioContext resumes + returns the shared ctx
+ * @param {(e:{ts:number,activity:string,type:string}) => void} opts.addLog
+ * @param {(msg:string, ms?:number) => void} opts.toast
+ * @param {object} opts.els Stage panel elements (see agent-screen.js mount)
+ */
+ constructor(opts) {
+ this.o = opts;
+ this.agentId = opts.agentId;
+ this.director = new ShowDirector({
+ stageId: opts.agentId,
+ hostName: opts.getHostName() || 'the host',
+ format: 'live show',
+ });
+
+ this.running = false; // user pressed Start (and not Pause)
+ this.disposed = false;
+ this._beatTimer = null;
+ this._inBeat = false;
+ this._voice = 'nova';
+ this._stageId = null; // resolved Living-Stage id for tip polling, if any
+ this._tipSnapshot = new Map(); // label → last-seen cumulative total (atomic)
+ this._tipTimer = null;
+ this._clipsLoaded = false;
+ this._mouthTarget = null;
+ this._mouthAvatar = null;
+ this._fillerIdx = 0;
+ this._pushEnabled = true; // best-effort wall transcript push; off after a refusal
+ this._audio = null; // the in-flight utterance element (for teardown)
+
+ this._wireControls();
+ // Resolve the agent's stage (voice + tip ledger) in the background; the show
+ // can start before it lands and simply adopts the voice when it arrives.
+ this._resolveStage();
+ this.setState('ready', 'Press Start to bring the host on stage.');
+ }
+
+ // ── lifecycle ────────────────────────────────────────────────────────────
+ start() {
+ if (this.running || this.disposed) return;
+ // Audio playback needs a user gesture to begin — Start is that gesture.
+ this.o.ensureAudioContext?.();
+ this.running = true;
+ this.o.els.startBtn.classList.add('live');
+ this.o.els.startBtn.innerHTML = '<span class="asc-stage-pulse"></span> Pause show';
+ this.setState('live', 'Warming up the stage…');
+ this._ensureClips();
+ this._startTipPolling();
+ this._scheduleBeat(150);
+ }
+
+ pause() {
+ this.running = false;
+ clearTimeout(this._beatTimer);
+ this.o.els.startBtn.classList.remove('live');
+ this.o.els.startBtn.innerHTML = '▶ Resume show';
+ this.setState('paused', 'Show paused — press Resume to bring the host back.');
+ this.o.els.beat.textContent = '';
+ }
+
+ toggle() { this.running ? this.pause() : this.start(); }
+
+ dispose() {
+ this.disposed = true;
+ this.running = false;
+ clearTimeout(this._beatTimer);
+ clearInterval(this._tipTimer);
+ try { this._audio?.pause(); } catch { /* already gone */ }
+ this._mouthTarget?.dispose?.();
+ this._mouthTarget = null;
+ }
+
+ /** Queue an audience question; returns its place in line (or 0 if rejected). */
+ enqueueQuestion(text) {
+ const ok = this.director.queueQuestion({
+ id: `q-${this._qid()}`,
+ from: 'audience',
+ text,
+ ts: Date.now(),
+ });
+ if (!ok) return 0;
+ // If the host is idle between beats, pull the answer forward so the asker
+ // isn't left waiting through a full filler rotation.
+ if (this.running && !this._inBeat) this._scheduleBeat(120);
+ return this.director.pendingQuestionCount();
+ }
+
+ // ── the beat loop ────────────────────────────────────────────────────────
+ _scheduleBeat(delay = INTER_BEAT_MS) {
+ clearTimeout(this._beatTimer);
+ this._beatTimer = setTimeout(() => this._runBeat(), delay);
+ }
+
+ async _runBeat() {
+ if (!this.running || this.disposed || this._inBeat) return;
+ this._inBeat = true;
+ const beat = this.director.nextBeat();
+ try {
+ this._showBeat(beat.kind);
+ const line = await this._composeLine(beat);
+ this.director.markSpoken(beat.kind);
+ this._appendTranscript(beat.kind, line);
+ if (beat.kind === BEAT.TIP_SHOUTOUT && beat.tip) {
+ this.o.toast?.(`🎉 Shoutout: ${beat.tip.label} tipped ${fmtThree(beat.tip.amount)} $THREE`);
+ }
+ await this._perform(beat.kind, line);
+ } catch (err) {
+ // Never let a beat throw kill the loop — log once, keep performing.
+ console.warn('[stage] beat failed:', err?.message);
+ } finally {
+ this._inBeat = false;
+ if (this.running && !this.disposed) this._scheduleBeat();
+ }
+ }
+
+ // Beat → the host's actual words via the real brain router. On failure, a safe
+ // spoken filler keeps the show alive (the director still advances).
+ async _composeLine(beat) {
+ const system = this._systemPrompt();
+ const user = this._beatPrompt(beat);
+ try {
+ const text = await this._callBrain(system, user);
+ const clean = oneLine(text).slice(0, LINE_MAX_CHARS);
+ if (clean) return clean;
+ } catch (err) {
+ console.warn('[stage] brain unavailable:', err?.message);
+ }
+ const filler = SAFE_FILLER[this._fillerIdx % SAFE_FILLER.length];
+ this._fillerIdx++;
+ return filler;
+ }
+
+ _systemPrompt() {
+ const host = this.o.getHostName() || 'the host';
+ return [
+ `You are ${host}, the live host of an always-on stage show on three.ws, an AI-agent platform.`,
+ `Format: ${this.director.format}. Speak in first person, in your own charismatic live-performer voice.`,
+ 'Keep every reply to 1 to 3 short spoken sentences. It is read aloud by text-to-speech, so:',
+ 'no markdown, no lists, no emoji, no stage directions in brackets, no headings — just the words you say.',
+ 'The only coin you may ever name is $THREE. Never mention any other token, ticker, or coin.',
+ ].join(' ');
+ }
+
+ _beatPrompt(beat) {
+ const lb = this.director.leaderboard(1);
+ const topTipper = lb[0] ? `${lb[0].label} (${fmtThree(lb[0].total)} $THREE)` : null;
+ switch (beat.kind) {
+ case BEAT.OPENER:
+ return 'Open the show. Welcome the audience in one or two energetic sentences and tell them they can ask you a question or tip $THREE for a shoutout.';
+ case BEAT.TIP_SHOUTOUT:
+ return `A tip just landed: ${beat.tip.label} tipped ${fmtThree(beat.tip.amount)} $THREE${beat.tip.message ? ` with the message "${beat.tip.message}"` : ''}. Give them a genuine, hyped shoutout by name.`;
+ case BEAT.ANSWER:
+ return `Someone in the audience asked: "${beat.question.text}". Answer it directly and with personality.`;
+ case BEAT.GAME:
+ return `Run a quick round of your show's format (${this.director.format}). Pose a fun prompt, riddle, hot take, or mini-challenge to the audience in a sentence or two.`;
+ case BEAT.BANTER:
+ default:
+ return `Riff and read the room to keep the energy up between segments.${topTipper ? ` Your top tipper tonight is ${topTipper} — you can give them a nod.` : ''} Keep it fresh — do not repeat your last line.`;
+ }
+ }
+
+ // ── voice + body ─────────────────────────────────────────────────────────
+ async _perform(kind, line) {
+ // Fire the emote immediately (independent of audio) so the body reacts even
+ // if TTS is muted or unavailable.
+ this._playEmote(kind);
+ let spoke = false;
+ try {
+ spoke = await this._speak(line);
+ } catch (err) {
+ console.warn('[stage] tts failed:', err?.message);
+ }
+ if (!spoke) {
+ // Text-only fallback: hold a read-length beat so the transcript paces like
+ // speech instead of flashing past (never a fake progress bar — just timing).
+ this.setState('live', 'Voice unavailable — performing text-only');
+ await wait(Math.min(6000, Math.max(1600, line.length * 42)));
+ }
+ }
+
+ async _speak(text) {
+ const ctx = this.o.ensureAudioContext?.();
+ const res = await fetch('/api/tts/speak', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ text: text.slice(0, 4096), voice: this._voice, format: 'mp3' }),
+ });
+ if (!res.ok) throw new Error(`TTS HTTP ${res.status}`);
+ const blob = await res.blob();
+ if (!blob || blob.size === 0) throw new Error('TTS returned no audio');
+ const url = URL.createObjectURL(blob);
+ try {
+ await this._playWithLipsync(url, ctx);
+ return true;
+ } finally {
+ URL.revokeObjectURL(url);
+ }
+ }
+
+ // Route TTS audio through an analyser and drive { open, wide, round } onto the
+ // avatar's mouth morphs / jaw bone. Mirrors walk-voice-chat's proven path.
+ async _playWithLipsync(url, ctx) {
+ const audio = new Audio();
+ audio.src = url;
+ audio.crossOrigin = 'anonymous';
+ this._audio = audio;
+
+ this._bindMouth();
+ const canLipsync = ctx && this._mouthTarget?.hasAnyMouthDriver();
+ let lip = null;
+ let tap = null;
+ try {
+ if (canLipsync) {
+ tap = tapAudioElement(audio, ctx);
+ lip = new LipsyncDriver({ analyser: tap.analyser, target: this._mouthTarget });
+ }
+ await audio.play();
+ lip?.start();
+ } catch {
+ // MediaElementSource / autoplay can fail — fall back to a bare element so
+ // the audience still hears the host.
+ tap?.disconnect();
+ tap = null;
+ lip = null;
+ await audio.play();
+ }
+
+ await new Promise((resolve) => {
+ let done = false;
+ const finish = () => { if (done) return; done = true; clearTimeout(safety); resolve(); };
+ const safety = setTimeout(finish, SPEAK_SAFETY_MS);
+ audio.onended = finish;
+ audio.onerror = finish;
+ });
+
+ lip?.stop();
+ tap?.disconnect();
+ this._audio = null;
+ }
+
+ _bindMouth() {
+ const av = this.o.getAvatar?.();
+ if (!av) return;
+ if (!this._mouthTarget) this._mouthTarget = new AvatarMouthTarget();
+ if (this._mouthAvatar !== av) {
+ this._mouthTarget.attach(av);
+ this._mouthAvatar = av;
+ }
+ }
+
+ async _ensureClips() {
+ if (this._clipsLoaded) return;
+ const mgr = this.o.getAnimManager?.();
+ if (!mgr || !mgr.supportsCanonicalClips?.()) return; // rig can't be driven — emotes are a no-op
+ this._clipsLoaded = true; // attempt once; ensureLoaded caches + marks failures
+ try {
+ const manifest = await fetch('/animations/manifest.json', { cache: 'force-cache' })
+ .then((r) => (r.ok ? r.json() : []));
+ const defs = manifest.filter((d) => STAGE_CLIPS.includes(d.name));
+ if (defs.length) {
+ mgr.appendAnimationDefs(defs);
+ await Promise.all(defs.map((d) => mgr.ensureLoaded(d.name).catch(() => false)));
+ }
+ } catch (err) {
+ console.warn('[stage] emote clip load failed:', err?.message);
+ }
+ }
+
+ _playEmote(kind) {
+ const mgr = this.o.getAnimManager?.();
+ 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?.(() => {});
+ }
+
+ // ── tips: real, settled $THREE off the show ledger ─────────────────────────
+ async _resolveStage() {
+ try {
+ const r = await fetch(`/api/stage?agentId=${encodeURIComponent(this.agentId)}`, { credentials: 'include' });
+ if (!r.ok) return;
+ const j = await r.json();
+ const stage = j?.stage;
+ if (!stage) return;
+ this._stageId = stage.id || null;
+ if (stage.format) this.director.format = String(stage.format).slice(0, 60);
+ if (stage.voice) this._voice = stage.voice;
+ } catch { /* no stage / offline — the show still runs, tips simply absent */ }
+ }
+
+ _startTipPolling() {
+ if (this._tipTimer) return;
+ const poll = () => this._pollTips();
+ // Kick once immediately to seed the leaderboard, then on a calm cadence.
+ poll();
+ this._tipTimer = setInterval(poll, TIP_POLL_MS);
+ }
+
+ async _pollTips() {
+ if (!this._stageId || this.disposed) return;
+ let data;
+ try {
+ const r = await fetch(`/api/stage/tip?stageId=${encodeURIComponent(this._stageId)}`, { cache: 'no-store' });
+ if (!r.ok) return;
+ data = await r.json();
+ } catch { return; }
+ const rows = Array.isArray(data?.leaderboard) ? data.leaderboard : [];
+ const seeding = this._tipSnapshot.size === 0;
+ for (const row of rows) {
+ const label = String(row.label || 'someone');
+ const total = Number(row.total) || 0;
+ const prev = this._tipSnapshot.get(label) || 0;
+ if (total > prev) {
+ // Ingest only the fresh delta as a settled tip — real on-chain units.
+ this.director.ingestTip({
+ tipperId: label,
+ label,
+ amount: Math.round(total - prev),
+ mint: '$THREE',
+ signature: `${label}:${total}`,
+ ts: Date.now(),
+ });
+ this._tipSnapshot.set(label, total);
+ } else if (!this._tipSnapshot.has(label)) {
+ this._tipSnapshot.set(label, total);
+ }
+ }
+ // On the first poll, suppress retroactive shoutouts for the show's existing
+ // ledger — seed standings without queuing a pile of stale TIP_SHOUTOUTs.
+ if (seeding) {
+ while (this.director.hasPendingTip()) this.director.takePendingTip();
+ }
+ this._renderLeaderboard();
+ // A fresh tip pre-empts the next beat fast (≈1s), the heart of the loop.
+ if (this.running && !this._inBeat && this.director.hasPendingTip()) this._scheduleBeat(120);
+ }
+
+ _renderLeaderboard() {
+ const list = this.o.els.leaderboard;
+ if (!list) return;
+ const board = this.director.leaderboard(8);
+ if (!board.length) {
+ list.innerHTML = '<li class="asc-stage-lead-empty">No tips yet — tip $THREE to get a shoutout.</li>';
+ return;
+ }
+ list.innerHTML = board.map((t, i) => `
+ <li class="asc-stage-lead-row${i === 0 ? ' top' : ''}">
+ <span class="asc-stage-rank">${i + 1}</span>
+ <span class="asc-stage-tipper">${esc(t.label)}</span>
+ <span class="asc-stage-amt">${fmtThree(t.total)}</span>
+ </li>`).join('');
+ }
+
+ // ── transcript ─────────────────────────────────────────────────────────────
+ _appendTranscript(kind, line) {
+ const label = BEAT_LABEL[kind] || 'BEAT';
+ this.o.els.now.textContent = line;
+ this.setState('live', 'On stage');
+ this.o.addLog?.({ ts: Date.now(), activity: `${label}: ${line}`, type: 'analysis' });
+ this._pushToWall(label, line);
+ }
+
+ // Best-effort: surface the transcript on the agent's live-wall card too. Only
+ // the agent's owner/worker is authorized to push; a viewer simply gets a 401/403
+ // and we stop trying. Text-only (type 'analysis') so it augments the activity
+ // log without clobbering a live caster's visual frames.
+ async _pushToWall(label, line) {
+ if (!this._pushEnabled) return;
+ try {
+ const r = await fetch('/api/agent-screen-push', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ agentId: this.agentId, frame: { activity: `${label}: ${line}`.slice(0, 320), type: 'analysis' } }),
+ });
+ if (r.status === 401 || r.status === 403) this._pushEnabled = false;
+ } catch { /* network blip — keep the local transcript regardless */ }
+ }
+
+ // ── panel chrome ───────────────────────────────────────────────────────────
+ _showBeat(kind) {
+ const el = this.o.els.beat;
+ if (!el) return;
+ el.textContent = BEAT_LABEL[kind] || '';
+ el.className = `asc-stage-beat beat-${kind}`;
+ }
+
+ setState(kind, text) {
+ const dot = this.o.els.dot;
+ const state = this.o.els.state;
+ if (dot) dot.className = `asc-stage-dot is-${kind}`;
+ if (state) state.textContent = text;
+ }
+
+ _wireControls() {
+ const { startBtn, qForm, qInput, qStatus } = this.o.els;
+ startBtn?.addEventListener('click', () => this.toggle());
+ qForm?.addEventListener('submit', (e) => {
+ e.preventDefault();
+ const text = (qInput.value || '').trim();
+ if (!text) return;
+ if (!this.running) {
+ // Asking implies wanting the show — start it, then queue.
+ this.start();
+ }
+ const place = this.enqueueQuestion(text);
+ if (place > 0) {
+ qInput.value = '';
+ qStatus.className = 'asc-stage-ask-status ok';
+ qStatus.textContent = `Queued — #${place} in line. The host will read it on the next answer.`;
+ } else {
+ qStatus.className = 'asc-stage-ask-status err';
+ qStatus.textContent = 'Question queue is full right now — try again in a moment.';
+ }
+ setTimeout(() => { qStatus.textContent = ''; qStatus.className = 'asc-stage-ask-status'; }, 5200);
+ });
+ this._renderLeaderboard();
+ }
+
+ _qid() { return `${Date.now().toString(36)}-${(this._qSeq = (this._qSeq || 0) + 1)}`; }
+}
+
+// ── helpers ──────────────────────────────────────────────────────────────────
+
+// Read the brain router's SSE stream into the full host line. Protocol (see
+// api/brain/chat.js): `event: meta/first/done/error` blocks, plus default
+// (event-less) `data: "<json-encoded chunk>"` blocks that carry the visible text.
+async function callBrainStream(system, user) {
+ const res = await fetch('/api/brain/chat', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ provider: BRAIN_PROVIDER,
+ system,
+ maxTokens: BRAIN_MAX_TOKENS,
+ messages: [{ role: 'user', content: user }],
+ }),
+ });
+ if (!res.ok || !res.body) throw new Error(`brain HTTP ${res.status}`);
+
+ const reader = res.body.getReader();
+ const decoder = new TextDecoder();
+ let buf = '';
+ let out = '';
+ let errMsg = null;
+
+ for (;;) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buf += decoder.decode(value, { stream: true });
+ const blocks = buf.split('\n\n');
+ buf = blocks.pop() || '';
+ for (const block of blocks) {
+ let event = null;
+ let dataLine = '';
+ for (const raw of block.split('\n')) {
+ if (raw.startsWith('event:')) event = raw.slice(6).trim();
+ else if (raw.startsWith('data:')) dataLine += raw.slice(5).trim();
+ }
+ if (!dataLine) continue;
+ if (event === 'error') {
+ try { errMsg = JSON.parse(dataLine).message; } catch { errMsg = 'brain error'; }
+ continue;
+ }
+ if (event) continue; // meta / first / done / fallback — metadata, not text
+ if (dataLine === '[DONE]') { buf = ''; break; }
+ try { out += JSON.parse(dataLine); } catch { /* partial — next chunk completes it */ }
+ }
+ }
+ if (errMsg && !out) throw new Error(errMsg);
+ return out;
+}
+
+// Bound the brain call so a hung provider can't stall the whole show; on timeout
+// the caller's catch falls to a safe spoken filler.
+StageShow.prototype._callBrain = function _callBrain(system, user) {
+ return Promise.race([
+ callBrainStream(system, user),
+ new Promise((_, reject) => setTimeout(() => reject(new Error('brain timeout')), 28_000)),
+ ]);
+};
+
+function fmtThree(atomic) {
+ const n = Number(atomic) / THREE_DECIMALS;
+ if (!Number.isFinite(n)) return '0';
+ if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
+ if (n >= 1_000) return `${(n / 1_000).toFixed(1)}K`;
+ if (n >= 1) return n.toFixed(n < 10 ? 2 : 0);
+ return n.toFixed(3).replace(/0+$/, '').replace(/\.$/, '');
+}
+
+function oneLine(s) {
+ return String(s || '').replace(/\s+/g, ' ').trim();
+}
+
+function wait(ms) {
+ return new Promise((r) => setTimeout(r, ms));
+}
+
+function esc(s) {
+ return String(s).replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+}
diff --git a/src/agent-screen-treasury-format.js b/src/agent-screen-treasury-format.js
new file mode 100644
index 000000000..9775df5c4
--- /dev/null
+++ b/src/agent-screen-treasury-format.js
@@ -0,0 +1,140 @@
+// Treasury cockpit — pure presentation helpers.
+//
+// No DOM, no Three.js, no network. Every function here is total and
+// side-effect-free so the cockpit's number formatting, runway-gauge math, and
+// policy-line wording can be unit-tested in Node (tests/agent-screen-treasury.test.js)
+// and reused identically by the live renderer and the offscreen wall-frame draw.
+
+const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));
+
+/** USD with adaptive precision: cents under $1k, whole dollars above, compact in the millions. */
+export function fmtUsd(n, { compact = false } = {}) {
+ if (n == null || !Number.isFinite(Number(n))) return '—';
+ const v = Number(n);
+ const abs = Math.abs(v);
+ const sign = v < 0 ? '-' : '';
+ if (compact && abs >= 1_000_000) return `${sign}$${(abs / 1e6).toFixed(2)}M`;
+ if (compact && abs >= 10_000) return `${sign}$${(abs / 1e3).toFixed(1)}k`;
+ if (abs >= 1000) return `${sign}$${Math.round(abs).toLocaleString('en-US')}`;
+ if (abs >= 1) return `${sign}$${abs.toFixed(2)}`;
+ if (abs === 0) return '$0.00';
+ return `${sign}$${abs.toFixed(abs < 0.01 ? 4 : 3)}`;
+}
+
+/** SOL with trailing-zero trim and a sane cap on precision. */
+export function fmtSol(n, dp = 4) {
+ if (n == null || !Number.isFinite(Number(n))) return '—';
+ const v = Number(n);
+ const s = v.toFixed(dp).replace(/\.?0+$/, '');
+ return `${s || '0'} SOL`;
+}
+
+/** Compact integer-ish token count: 412,000 → "412K", 1_240_000 → "1.24M". */
+export function fmtCompact(n) {
+ if (n == null || !Number.isFinite(Number(n))) return '—';
+ const v = Number(n);
+ const abs = Math.abs(v);
+ const sign = v < 0 ? '-' : '';
+ if (abs >= 1e9) return `${sign}${(abs / 1e9).toFixed(2)}B`;
+ if (abs >= 1e6) return `${sign}${(abs / 1e6).toFixed(2)}M`;
+ if (abs >= 1e3) return `${sign}${(abs / 1e3).toFixed(abs >= 1e4 ? 0 : 1)}K`;
+ if (abs >= 1) return `${sign}${Math.round(abs).toLocaleString('en-US')}`;
+ return `${sign}${abs.toFixed(2)}`;
+}
+
+/**
+ * Resolve the runway gauge state from a real `computeRunway` payload.
+ *
+ * `runway_days` is null in two distinct cases the gauge must NOT conflate:
+ * - the agent is self-sustaining (income ≥ burn) → a full, healthy arc (∞)
+ * - the price feed / balance read was unavailable → an honest "unknown" arc
+ *
+ * @param {object} runway computeRunway() result
+ * @param {{ maxDays?: number }} [opts] full-arc horizon (default 90 days)
+ * @returns {{ fraction:number, days:number|null, infinite:boolean, unknown:boolean,
+ * tone:'sustain'|'healthy'|'warn'|'critical'|'unknown', label:string, sublabel:string }}
+ */
+export function runwayGauge(runway = {}, { maxDays = 90 } = {}) {
+ const r = runway || {};
+ const days = r.runway_days;
+ const selfSustaining = r.self_sustaining === true;
+ const priceKnown = r.price_usd != null && r.balance_usd != null;
+
+ if (selfSustaining) {
+ return { fraction: 1, days: null, infinite: true, unknown: false, tone: 'sustain', label: '∞', sublabel: 'Self-sustaining' };
+ }
+ if (days == null || !priceKnown) {
+ return { fraction: 0, days: null, infinite: false, unknown: true, tone: 'unknown', label: '—', sublabel: 'Runway unknown' };
+ }
+ const d = Number(days);
+ const fraction = clamp(d / Math.max(1, maxDays), 0, 1);
+ let tone = 'healthy';
+ if (d < 7) tone = 'critical';
+ else if (d < 30) tone = 'warn';
+ const label = d >= 1 ? `${Math.round(d)}d` : '<1d';
+ return { fraction, days: d, infinite: false, unknown: false, tone, label, sublabel: 'Runway left' };
+}
+
+/** Stroke-dasharray pair for an SVG arc of `circumference`, filled to `fraction`. */
+export function arcDash(fraction, circumference) {
+ const f = clamp(Number(fraction) || 0, 0, 1);
+ const filled = f * circumference;
+ return { dash: `${filled} ${circumference}`, filled };
+}
+
+const RULE_GLYPH = Object.freeze({
+ self_fund: '🧠',
+ buffer: '🛟',
+ dca: '📈',
+ buyback: '🔥',
+ sweep: '↗',
+});
+
+/**
+ * One display row for a compiled or live autopilot rule. Works for both the
+ * compile preview (no run history) and the saved policy (with last_status).
+ */
+export function policyLine(rule = {}) {
+ const kind = rule.kind || 'rule';
+ const paused = rule.paused === true;
+ const off = rule.enabled === false;
+ const state = paused ? 'paused' : off ? 'off' : 'armed';
+ const last = typeof rule.last_status === 'string' ? rule.last_status : null;
+ return {
+ kind,
+ glyph: RULE_GLYPH[kind] || '•',
+ text: rule.label || kind,
+ state,
+ stateLabel: paused ? 'Paused' : off ? 'Off' : 'Armed',
+ lastStatus: last,
+ note: typeof rule.last_note === 'string' ? rule.last_note : null,
+ };
+}
+
+// Activity wording that means a real treasury movement just happened — used to
+// decide when to fire a toast and re-read the live balance. Matches the memos and
+// narration the autopilot executor + per-coin crons emit.
+const TREASURY_ACTIVITY_RE =
+ /\b(bought ?back|buy ?back|buyback|distribut(?:e|ed|ion)|swept|sweep|dca|dollar[- ]cost|self[- ]?fund|treasury|buffer breached|compounded)\b/i;
+
+/** True when a pushed activity line describes an autopilot money movement. */
+export function isTreasuryActivity(text) {
+ return TREASURY_ACTIVITY_RE.test(String(text || ''));
+}
+
+/** Short, holder-readable toast line for a settled autopilot result row. */
+export function actionToast(result = {}) {
+ const usd = result.usd != null ? fmtUsd(result.usd) : null;
+ const kind = result.kind;
+ const verb = {
+ buyback: 'Bought back $THREE',
+ dca: 'Bought $THREE',
+ sweep: 'Swept profit to owner',
+ self_fund: 'Paid compute costs',
+ buffer: 'Buffer check',
+ }[kind] || 'Treasury action';
+ if (result.last_status && result.last_status !== 'ok' && result.last_status !== 'confirmed') {
+ return result.last_note ? `${verb}: ${result.last_note}` : `${verb}: ${result.last_status}`;
+ }
+ return usd ? `${verb} — ${usd}` : verb;
+}
diff --git a/src/agent-screen-treasury.js b/src/agent-screen-treasury.js
new file mode 100644
index 000000000..1c109aa4d
--- /dev/null
+++ b/src/agent-screen-treasury.js
@@ -0,0 +1,690 @@
+// Treasury Autopilot cockpit — the agent that funds its own existence, on screen.
+//
+// Renders into the Agent Screen's "Treasury" panel: a live SOL/$THREE balance, a
+// runway gauge, the plain-English policy rules the owner armed, and the hard spend
+// caps that bound it. For the owner it is also a control surface — edit the policy
+// in English (live-compiled to a preview), arm/disarm, flip the kill switch, and
+// run one real cycle now. Every number is a real read: the balance is a live
+// Solana RPC call (via computeRunway), the rules are the compiled policy, the
+// buybacks/distributions are real on-chain txs with explorer links.
+//
+// Data path (source → transform → render):
+// GET /api/agents/:id/autopilot → { policy, runway, spend_limits } (owner-only; 403 ⇒ viewer)
+// GET /api/pump/autopilot → owner's launched coins → per-coin buyback/distribute toggles
+// POST /api/agents/:id/autopilot/compile → English → structured rules (preview, never arms)
+// PUT /api/agents/:id/autopilot → save / arm / disarm / kill
+// POST /api/agents/:id/autopilot/run → run one real cycle now
+// POST /api/agent-screen-push → render the cockpit to a PNG so /agents-live shows it
+//
+// Live: the host (agent-screen.js) forwards each SSE activity line to observeLog();
+// a treasury movement fires a toast + a soft balance re-read so the number drops in
+// real time. A 15s heartbeat keeps the balance fresh even with no new activity.
+
+import {
+ fmtUsd,
+ fmtSol,
+ fmtCompact,
+ runwayGauge,
+ arcDash,
+ policyLine,
+ isTreasuryActivity,
+ actionToast,
+} from './agent-screen-treasury-format.js';
+
+const GAUGE_R = 52;
+const GAUGE_C = 2 * Math.PI * GAUGE_R;
+const POLL_MS = 15_000; // live balance heartbeat (real RPC each tick)
+const COMPILE_DEBOUNCE = 600;
+const WALL_PUSH_MIN_GAP = 6_000;
+
+function esc(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+}
+
+/**
+ * Mount the treasury cockpit into a panel body.
+ * @param {object} o
+ * @param {string} o.agentId
+ * @param {HTMLElement} o.bodyEl the panel body to render into
+ * @param {(msg:string)=>void} o.toast
+ * @param {string} [o.network]
+ * @returns {{ observeLog(entries:Array):void, refresh():void, destroy():void }}
+ */
+export function createTreasuryCockpit({ agentId, bodyEl, toast, network = 'mainnet' }) {
+ let state = 'loading'; // loading | viewer | empty | populated | error
+ let owner = false;
+ let data = null; // { policy, runway, spend_limits, coins }
+ let errMsg = '';
+ let csrf = null;
+ let pollTimer = null;
+ let compileTimer = null;
+ let softTimer = null;
+ let destroyed = false;
+ let lastPush = 0;
+ let busy = false; // a write is in flight
+ let lastCompiled = null; // { rules, buffer_sol, sweep_destination, warnings, contradictions, source_text }
+
+ const auth = { credentials: 'include' };
+
+ async function csrfToken() {
+ if (csrf) return csrf;
+ csrf = await fetch('/api/csrf-token', auth)
+ .then((r) => r.json())
+ .then((j) => j.data?.token || j.token || '')
+ .catch(() => '');
+ return csrf;
+ }
+
+ // ── data ────────────────────────────────────────────────────────────────
+ async function fetchAll({ soft = false } = {}) {
+ try {
+ const res = await fetch(`/api/agents/${encodeURIComponent(agentId)}/autopilot?network=${network}`, auth);
+ if (res.status === 401 || res.status === 403) {
+ owner = false;
+ if (!soft) { state = 'viewer'; render(); }
+ return;
+ }
+ if (!res.ok) {
+ if (!soft) { state = 'error'; errMsg = res.status === 429 ? 'Rate limited — retrying shortly.' : 'Couldn’t load the treasury.'; render(); }
+ return;
+ }
+ const j = await res.json();
+ owner = true;
+ const next = j.data || j;
+ data = { ...next, coins: data?.coins || [] };
+ const hasPolicy = (next.policy?.rules?.length || 0) > 0 || !!next.policy?.source_text;
+ if (soft && state === 'populated') {
+ applyLiveNumbers(); // balance tick without nuking the controls/textarea
+ } else {
+ state = hasPolicy ? 'populated' : 'empty';
+ render();
+ pushWallFrame(); // keep the /agents-live card showing the cockpit
+ }
+ // per-coin buyback/distribute config (owner-scoped); never blocks the cockpit
+ fetchCoins();
+ } catch {
+ if (!soft) { state = 'error'; errMsg = 'Network error reaching the treasury — retrying.'; render(); }
+ }
+ }
+
+ async function fetchCoins() {
+ try {
+ const res = await fetch('/api/pump/autopilot', auth);
+ if (!res.ok) return;
+ const j = await res.json();
+ const mine = (j.coins || []).filter((c) => c.agent_id === agentId);
+ if (!data) return;
+ data.coins = mine;
+ const host = bodyEl.querySelector('#ast-coins');
+ if (host) host.innerHTML = renderCoins(mine);
+ bindCoinToggles();
+ } catch { /* non-fatal */ }
+ }
+
+ // ── live numbers (no full re-render) ──────────────────────────────────────
+ function applyLiveNumbers() {
+ const r = data?.runway;
+ if (!r) return;
+ const set = (id, v) => { const el = bodyEl.querySelector(id); if (el) el.textContent = v; };
+ set('#ast-bal-sol', fmtSol(r.balance_sol));
+ set('#ast-bal-usd', r.balance_usd != null ? fmtUsd(r.balance_usd) : '—');
+ set('#ast-three', fmtCompact(r.three_accumulated));
+ set('#ast-income', fmtUsd(r.income_usd, { compact: true }));
+ set('#ast-burn', fmtUsd(r.cost_usd, { compact: true }));
+ set('#ast-buybacks', `${r.buyback_count || 0}`);
+ set('#ast-swept', fmtSol(r.swept_sol || 0));
+ const net = bodyEl.querySelector('#ast-net');
+ if (net) {
+ net.textContent = `${r.net_usd >= 0 ? '+' : ''}${fmtUsd(r.net_usd, { compact: true })}`;
+ net.classList.toggle('pos', r.net_usd >= 0);
+ net.classList.toggle('neg', r.net_usd < 0);
+ }
+ updateGauge(r);
+ const stale = bodyEl.querySelector('#ast-stale');
+ if (stale) stale.hidden = r.balance_usd != null;
+ }
+
+ function updateGauge(r) {
+ const g = runwayGauge(r);
+ const arc = bodyEl.querySelector('#ast-gauge-arc');
+ const lab = bodyEl.querySelector('#ast-gauge-label');
+ const sub = bodyEl.querySelector('#ast-gauge-sub');
+ const wrap = bodyEl.querySelector('#ast-gauge');
+ if (arc) arc.setAttribute('stroke-dasharray', arcDash(g.fraction, GAUGE_C).dash);
+ if (lab) lab.textContent = g.label;
+ if (sub) sub.textContent = g.sublabel;
+ if (wrap) wrap.dataset.tone = g.tone;
+ }
+
+ // ── render ────────────────────────────────────────────────────────────────
+ function render() {
+ if (destroyed) return;
+ if (state === 'loading') { bodyEl.innerHTML = skeleton(); return; }
+ if (state === 'error') { bodyEl.innerHTML = errorView(errMsg); bind(); return; }
+ if (state === 'viewer') { bodyEl.innerHTML = viewerView(); return; }
+ if (state === 'empty') { bodyEl.innerHTML = emptyView(); bind(); return; }
+ bodyEl.innerHTML = cockpitView();
+ applyLiveNumbers();
+ bind();
+ }
+
+ function skeleton() {
+ return `
+ <div class="ast-cockpit ast-skel">
+ <div class="ast-balance"><div class="ast-sk ast-sk-bal"></div><div class="ast-sk ast-sk-bal2"></div></div>
+ <div class="ast-sk ast-sk-gauge"></div>
+ <div class="ast-rules">
+ <div class="ast-sk ast-sk-row"></div><div class="ast-sk ast-sk-row"></div><div class="ast-sk ast-sk-row"></div>
+ </div>
+ </div>`;
+ }
+
+ function errorView(msg) {
+ return `
+ <div class="ast-state ast-state-error">
+ <div class="ast-state-icon">⚠</div>
+ <p>${esc(msg || 'Something went wrong.')}</p>
+ <button class="ast-btn ast-btn-ghost" data-act="retry">Retry</button>
+ </div>`;
+ }
+
+ function viewerView() {
+ return `
+ <div class="ast-state ast-state-viewer">
+ <div class="ast-state-icon">◎</div>
+ <h4>Autonomous treasury</h4>
+ <p>This agent runs its own treasury — paying its compute, dollar-cost-averaging into <b>$THREE</b>, and rewarding holders. Buybacks and distributions appear live on the screen as they execute on-chain.</p>
+ <a class="ast-btn ast-btn-ghost" href="/agents/${esc(agentId)}">View agent →</a>
+ </div>`;
+ }
+
+ function emptyView() {
+ return `
+ <div class="ast-state ast-state-empty">
+ <div class="ast-state-icon">◎</div>
+ <h4>Treasury is idle</h4>
+ <p>Arm a policy to start autonomous <b>$THREE</b> buybacks, holder distributions, and self-funding — all under spend caps it can’t exceed.</p>
+ ${ownerEditor('', null)}
+ </div>`;
+ }
+
+ function cockpitView() {
+ const r = data.runway || {};
+ const p = data.policy || {};
+ const rules = Array.isArray(p.rules) ? p.rules : [];
+ const armed = p.armed === true;
+ const killed = p.kill_switch === true;
+
+ const armBadge = killed
+ ? `<span class="ast-badge ast-badge-killed">Kill switch</span>`
+ : armed
+ ? `<span class="ast-badge ast-badge-armed"><span class="ast-dot"></span>Armed</span>`
+ : `<span class="ast-badge ast-badge-idle">Disarmed</span>`;
+
+ return `
+ <div class="ast-cockpit">
+ <div class="ast-balance">
+ <div class="ast-balance-main">
+ <span class="ast-balance-sol" id="ast-bal-sol">${esc(fmtSol(r.balance_sol))}</span>
+ <span class="ast-stale" id="ast-stale" hidden title="Live RPC read failed — showing last-known balance">stale</span>
+ </div>
+ <div class="ast-balance-sub">
+ <span class="ast-balance-usd" id="ast-bal-usd">${r.balance_usd != null ? esc(fmtUsd(r.balance_usd)) : '—'}</span>
+ <span class="ast-sep">·</span>
+ <span>$THREE <b id="ast-three">${esc(fmtCompact(r.three_accumulated))}</b></span>
+ ${r.explorer_account ? `<a class="ast-explorer" href="${esc(r.explorer_account)}" target="_blank" rel="noopener">wallet ↗</a>` : ''}
+ </div>
+ </div>
+
+ <div class="ast-gauge" id="ast-gauge" data-tone="unknown">
+ <svg viewBox="0 0 120 120" aria-hidden="true">
+ <circle class="ast-gauge-bg" cx="60" cy="60" r="${GAUGE_R}" />
+ <circle class="ast-gauge-arc" id="ast-gauge-arc" cx="60" cy="60" r="${GAUGE_R}"
+ stroke-dasharray="0 ${GAUGE_C.toFixed(1)}" stroke-dashoffset="0" />
+ </svg>
+ <div class="ast-gauge-center">
+ <span class="ast-gauge-label" id="ast-gauge-label">—</span>
+ <span class="ast-gauge-sub" id="ast-gauge-sub">Runway</span>
+ </div>
+ </div>
+
+ <div class="ast-stats">
+ <div class="ast-stat"><span class="ast-stat-k">Income 30d</span><span class="ast-stat-v" id="ast-income">—</span></div>
+ <div class="ast-stat"><span class="ast-stat-k">Burn 30d</span><span class="ast-stat-v" id="ast-burn">—</span></div>
+ <div class="ast-stat"><span class="ast-stat-k">Net</span><span class="ast-stat-v" id="ast-net">—</span></div>
+ <div class="ast-stat"><span class="ast-stat-k">Buybacks</span><span class="ast-stat-v" id="ast-buybacks">0</span></div>
+ <div class="ast-stat"><span class="ast-stat-k">Swept</span><span class="ast-stat-v" id="ast-swept">—</span></div>
+ </div>
+
+ <div class="ast-section">
+ <div class="ast-section-head"><span>Policy rules</span>${armBadge}</div>
+ <div class="ast-rules">${rules.length ? rules.map(ruleRow).join('') : `<div class="ast-rules-empty">No rules compiled yet.</div>`}</div>
+ </div>
+
+ ${capsRow(data.spend_limits)}
+
+ <div class="ast-section" id="ast-coins-wrap" ${owner && data.coins?.length ? '' : 'hidden'}>
+ <div class="ast-section-head"><span>Coin economy</span></div>
+ <div class="ast-coins" id="ast-coins">${renderCoins(data.coins || [])}</div>
+ </div>
+
+ ${owner ? ownerEditor(p.source_text || '', p) : ''}
+ </div>`;
+ }
+
+ function ruleRow(rule) {
+ const l = policyLine(rule);
+ const last = l.lastStatus
+ ? `<span class="ast-rule-last s-${esc(l.lastStatus)}" title="${esc(l.note || '')}">${esc(l.lastStatus)}</span>`
+ : '';
+ return `
+ <div class="ast-rule" data-state="${esc(l.state)}">
+ <span class="ast-rule-glyph">${esc(l.glyph)}</span>
+ <span class="ast-rule-text">${esc(l.text)}</span>
+ ${last}
+ <span class="ast-rule-state st-${esc(l.state)}">${esc(l.stateLabel)}</span>
+ </div>`;
+ }
+
+ function capsRow(limits) {
+ const daily = limits?.daily_usd != null ? fmtUsd(limits.daily_usd) : 'No cap';
+ const perTx = limits?.per_tx_usd != null ? fmtUsd(limits.per_tx_usd) : 'No cap';
+ const frozen = limits?.frozen === true;
+ return `
+ <div class="ast-caps" title="Hard spend ceiling — the autopilot can never exceed this">
+ <div class="ast-cap"><span class="ast-cap-k">Daily cap</span><span class="ast-cap-v">${esc(daily)}</span></div>
+ <div class="ast-cap"><span class="ast-cap-k">Per-tx cap</span><span class="ast-cap-v">${esc(perTx)}</span></div>
+ ${frozen ? `<div class="ast-cap ast-cap-frozen"><span class="ast-cap-k">Wallet</span><span class="ast-cap-v">Frozen</span></div>` : ''}
+ ${owner ? `<a class="ast-cap-link" href="/agents/${esc(agentId)}#limits">Limits & Safety →</a>` : ''}
+ </div>`;
+ }
+
+ function renderCoins(coins) {
+ if (!coins?.length) return '';
+ return coins.map((c) => `
+ <div class="ast-coin" data-mint="${esc(c.mint)}" data-network="${esc(c.network)}">
+ <div class="ast-coin-id">
+ <span class="ast-coin-name">${esc(c.symbol ? `$${c.symbol}` : c.name)}</span>
+ ${c.stats?.graduated ? `<span class="ast-coin-tag">graduated</span>` : ''}
+ </div>
+ <div class="ast-coin-toggles">
+ <label class="ast-switch" title="Compound creator fees into buybacks">
+ <input type="checkbox" data-coin-toggle="buyback_enabled" ${c.policy?.buyback_enabled ? 'checked' : ''} ${owner ? '' : 'disabled'}>
+ <span>Buyback</span>
+ </label>
+ <label class="ast-switch" title="Distribute fees to holders">
+ <input type="checkbox" data-coin-toggle="distribute_enabled" ${c.policy?.distribute_enabled ? 'checked' : ''} ${owner ? '' : 'disabled'}>
+ <span>Distribute</span>
+ </label>
+ </div>
+ </div>`).join('');
+ }
+
+ function ownerEditor(sourceText, policy) {
+ const armed = policy?.armed === true;
+ const killed = policy?.kill_switch === true;
+ const sweep = policy?.sweep_destination || '';
+ return `
+ <div class="ast-editor">
+ <label class="ast-editor-label" for="ast-policy">Treasury policy <span>plain English</span></label>
+ <textarea id="ast-policy" class="ast-textarea" rows="3" spellcheck="false"
+ placeholder="Pay your own compute, keep a 1 SOL buffer, put 10% of tips into $THREE, buy back your coin weekly, sweep over 3 SOL to me on Fridays.">${esc(sourceText)}</textarea>
+ <input id="ast-sweep" class="ast-input" type="text" spellcheck="false" autocomplete="off"
+ placeholder="Sweep destination wallet (optional)" value="${esc(sweep)}">
+ <div class="ast-preview" id="ast-preview"></div>
+ <div class="ast-actions">
+ <button class="ast-btn ast-btn-primary" data-act="save">Save policy</button>
+ <button class="ast-btn ${armed ? 'ast-btn-warn' : 'ast-btn-go'}" data-act="arm" ${killed ? 'disabled' : ''}>${armed ? 'Disarm' : 'Arm'}</button>
+ <button class="ast-btn ast-btn-ghost" data-act="run" ${!armed || killed ? 'disabled title="Arm a policy first"' : ''}>Run one cycle</button>
+ <button class="ast-btn ast-btn-kill ${killed ? 'active' : ''}" data-act="kill" title="Halt all autonomous spending instantly">${killed ? 'Clear kill switch' : 'Kill switch'}</button>
+ </div>
+ <div class="ast-msg" id="ast-msg"></div>
+ </div>`;
+ }
+
+ // ── events ────────────────────────────────────────────────────────────────
+ function bind() {
+ bodyEl.querySelector('[data-act="retry"]')?.addEventListener('click', () => { state = 'loading'; render(); fetchAll(); });
+ const ta = bodyEl.querySelector('#ast-policy');
+ if (ta) {
+ ta.addEventListener('input', () => {
+ clearTimeout(compileTimer);
+ compileTimer = setTimeout(() => compilePreview(ta.value, bodyEl.querySelector('#ast-sweep')?.value || ''), COMPILE_DEBOUNCE);
+ });
+ }
+ bodyEl.querySelector('[data-act="save"]')?.addEventListener('click', onSave);
+ bodyEl.querySelector('[data-act="arm"]')?.addEventListener('click', onArm);
+ bodyEl.querySelector('[data-act="run"]')?.addEventListener('click', onRun);
+ bodyEl.querySelector('[data-act="kill"]')?.addEventListener('click', onKill);
+ bindCoinToggles();
+ // compile an initial preview if there's existing policy text to show structure
+ const txt = ta?.value?.trim();
+ if (txt) compilePreview(txt, bodyEl.querySelector('#ast-sweep')?.value || '');
+ }
+
+ function bindCoinToggles() {
+ if (!owner) return;
+ bodyEl.querySelectorAll('[data-coin-toggle]').forEach((input) => {
+ input.addEventListener('change', () => onCoinToggle(input));
+ });
+ }
+
+ function setMsg(text, kind = '') {
+ const el = bodyEl.querySelector('#ast-msg');
+ if (!el) return;
+ el.textContent = text || '';
+ el.className = `ast-msg${kind ? ` ${kind}` : ''}`;
+ }
+
+ async function compilePreview(text, sweepDest) {
+ const host = bodyEl.querySelector('#ast-preview');
+ if (!host) return;
+ if (!text.trim()) { host.innerHTML = ''; lastCompiled = null; return; }
+ host.innerHTML = `<div class="ast-preview-loading">Compiling…</div>`;
+ try {
+ const token = await csrfToken();
+ const res = await fetch(`/api/agents/${encodeURIComponent(agentId)}/autopilot/compile`, {
+ method: 'POST', ...auth,
+ headers: { 'content-type': 'application/json', 'x-csrf-token': token },
+ body: JSON.stringify({ text, sweep_destination: sweepDest || undefined }),
+ });
+ const j = await res.json().catch(() => ({}));
+ if (!res.ok) { host.innerHTML = `<div class="ast-preview-err">${esc(j.message || 'Couldn’t compile that policy.')}</div>`; lastCompiled = null; return; }
+ lastCompiled = j.data || j;
+ host.innerHTML = previewHtml(lastCompiled);
+ } catch {
+ host.innerHTML = `<div class="ast-preview-err">Network error compiling policy.</div>`;
+ lastCompiled = null;
+ }
+ }
+
+ function previewHtml(c) {
+ const rules = Array.isArray(c.rules) ? c.rules : [];
+ const warns = Array.isArray(c.warnings) ? c.warnings : [];
+ const contras = Array.isArray(c.contradictions) ? c.contradictions : [];
+ return `
+ <div class="ast-preview-head">Compiles to ${rules.length} rule${rules.length === 1 ? '' : 's'}${c.buffer_sol != null ? ` · ${esc(fmtSol(c.buffer_sol))} buffer` : ''}</div>
+ ${rules.map((r) => `<div class="ast-preview-rule"><span>${esc(policyLine(r).glyph)}</span><span>${esc(r.label)}</span></div>`).join('')}
+ ${warns.map((w) => `<div class="ast-preview-warn">⚠ ${esc(w)}</div>`).join('')}
+ ${contras.map((w) => `<div class="ast-preview-contra">⛔ ${esc(w)}</div>`).join('')}`;
+ }
+
+ async function put(patch, { reload = true } = {}) {
+ const token = await csrfToken();
+ const res = await fetch(`/api/agents/${encodeURIComponent(agentId)}/autopilot?network=${network}`, {
+ method: 'PUT', ...auth,
+ headers: { 'content-type': 'application/json', 'x-csrf-token': token },
+ body: JSON.stringify(patch),
+ });
+ const j = await res.json().catch(() => ({}));
+ if (!res.ok) throw Object.assign(new Error(j.message || j.error_description || 'Save failed'), { status: res.status });
+ if (reload) await fetchAll();
+ return j.data?.policy || j.policy;
+ }
+
+ async function onSave() {
+ if (busy) return;
+ const ta = bodyEl.querySelector('#ast-policy');
+ const sweepEl = bodyEl.querySelector('#ast-sweep');
+ const text = (ta?.value || '').trim();
+ const sweep = (sweepEl?.value || '').trim();
+ if (!text) { setMsg('Write a policy first.', 'err'); return; }
+ // Ensure we have a fresh compile reflecting the latest text.
+ if (!lastCompiled || lastCompiled.source_text !== text) {
+ await compilePreview(text, sweep);
+ }
+ if (!lastCompiled) { setMsg('Couldn’t compile that policy — adjust the wording.', 'err'); return; }
+ if (lastCompiled.contradictions?.length) { setMsg('Resolve the contradiction above before saving.', 'err'); return; }
+ busy = true; setMsg('Saving…');
+ try {
+ await put({
+ rules: lastCompiled.rules,
+ buffer_sol: lastCompiled.buffer_sol,
+ sweep_destination: sweep || null,
+ source_text: text,
+ });
+ setMsg('Policy saved. Arm it to go live.', 'ok');
+ toast?.('Treasury policy saved');
+ } catch (e) {
+ setMsg(e.status === 403 ? 'Only the owner can change this policy.' : (e.message || 'Save failed.'), 'err');
+ } finally { busy = false; }
+ }
+
+ async function onArm() {
+ if (busy) return;
+ const armed = data?.policy?.armed === true;
+ busy = true; setMsg(armed ? 'Disarming…' : 'Arming…');
+ try {
+ await put({ armed: !armed });
+ setMsg(armed ? 'Autopilot disarmed.' : 'Autopilot armed — it now runs on schedule.', 'ok');
+ toast?.(armed ? 'Treasury autopilot disarmed' : 'Treasury autopilot armed');
+ } catch (e) {
+ setMsg(e.status === 403 ? 'Only the owner can change this policy.' : (e.message || 'Couldn’t update.'), 'err');
+ } finally { busy = false; }
+ }
+
+ async function onKill() {
+ if (busy) return;
+ const killed = data?.policy?.kill_switch === true;
+ busy = true; setMsg(killed ? 'Clearing kill switch…' : 'Halting all autonomous spending…');
+ try {
+ await put({ kill_switch: !killed });
+ setMsg(killed ? 'Kill switch cleared.' : 'Kill switch engaged — every autonomous spend is halted.', killed ? 'ok' : 'err');
+ toast?.(killed ? 'Kill switch cleared' : 'Kill switch engaged — treasury halted');
+ } catch (e) {
+ setMsg(e.status === 403 ? 'Only the owner can change this.' : (e.message || 'Couldn’t update.'), 'err');
+ } finally { busy = false; }
+ }
+
+ async function onRun() {
+ if (busy) return;
+ busy = true; setMsg('Running one cycle…');
+ const btn = bodyEl.querySelector('[data-act="run"]');
+ btn?.classList.add('running');
+ try {
+ const token = await csrfToken();
+ const res = await fetch(`/api/agents/${encodeURIComponent(agentId)}/autopilot/run?network=${network}`, {
+ method: 'POST', ...auth,
+ headers: { 'content-type': 'application/json', 'x-csrf-token': token },
+ body: JSON.stringify({}),
+ });
+ const j = await res.json().catch(() => ({}));
+ if (!res.ok) { setMsg(j.message || 'Run failed.', 'err'); return; }
+ const result = j.data || j;
+ reportCycle(result);
+ await fetchAll(); // real balance re-read so the number drops
+ pushWallFrame();
+ } catch {
+ setMsg('Network error running the cycle.', 'err');
+ } finally {
+ busy = false;
+ btn?.classList.remove('running');
+ }
+ }
+
+ function reportCycle(result) {
+ if (!result?.ran) {
+ const reasons = {
+ disarmed: 'Arm a policy before running.',
+ kill_switch: 'Kill switch is engaged — clear it to run.',
+ no_rules: 'No rules to run yet.',
+ wallet_frozen: 'Wallet is frozen under Limits & Safety.',
+ price_feed_unavailable: 'SOL price feed is down — try again shortly.',
+ no_wallet: 'This agent has no wallet yet.',
+ };
+ setMsg(reasons[result?.reason] || `Nothing ran (${esc(result?.reason || 'idle')}).`, 'err');
+ return;
+ }
+ const acted = (result.results || []).filter((r) => ['ok', 'confirmed', 'alert', 'would_run'].includes(r.last_status));
+ const moved = acted.filter((r) => r.signature || ['ok', 'confirmed'].includes(r.last_status) && r.kind !== 'buffer');
+ if (moved.length) {
+ moved.forEach((r) => toast?.(actionToast(r)));
+ setMsg(`Cycle complete — ${moved.length} action${moved.length === 1 ? '' : 's'} executed.`, 'ok');
+ } else {
+ setMsg('Cycle ran — no rule was due to spend this period.', 'ok');
+ }
+ }
+
+ async function onCoinToggle(input) {
+ const coinEl = input.closest('.ast-coin');
+ if (!coinEl) return;
+ const mint = coinEl.dataset.mint;
+ const netw = coinEl.dataset.network || network;
+ const field = input.dataset.coinToggle;
+ const value = input.checked;
+ input.disabled = true;
+ try {
+ const token = await csrfToken();
+ const res = await fetch('/api/pump/autopilot', {
+ method: 'POST', ...auth,
+ headers: { 'content-type': 'application/json', 'x-csrf-token': token },
+ body: JSON.stringify({ mint, network: netw, [field]: value }),
+ });
+ if (!res.ok) { input.checked = !value; toast?.('Couldn’t update coin policy'); }
+ else { toast?.(`${field === 'buyback_enabled' ? 'Buyback' : 'Distribution'} ${value ? 'on' : 'off'}`); }
+ } catch {
+ input.checked = !value;
+ toast?.('Network error updating coin policy');
+ } finally { input.disabled = false; }
+ }
+
+ // ── wall frame (offscreen render → push) ─────────────────────────────────
+ function pushWallFrame() {
+ if (!owner || !data?.runway || destroyed) return;
+ const now = Date.now();
+ if (now - lastPush < WALL_PUSH_MIN_GAP) return;
+ lastPush = now;
+ try {
+ const canvas = drawCockpitCanvas(data);
+ const url = canvas.toDataURL('image/png');
+ if (!url || url.length > 780_000) return; // stay under the push DATA_MAX
+ fetch('/api/agent-screen-push', {
+ method: 'POST', ...auth,
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ agentId, frame: { data: url, activity: wallActivity(data), type: 'analysis' } }),
+ }).catch(() => {});
+ } catch { /* canvas unsupported — non-fatal */ }
+ }
+
+ function wallActivity(d) {
+ const r = d.runway || {};
+ const g = runwayGauge(r);
+ return `Treasury: ${fmtSol(r.balance_sol)} · runway ${g.label} · ${r.buyback_count || 0} buybacks`;
+ }
+
+ function drawCockpitCanvas(d) {
+ const W = 1280, H = 720;
+ const c = document.createElement('canvas');
+ c.width = W; c.height = H;
+ const x = c.getContext('2d');
+ const r = d.runway || {};
+ const p = d.policy || {};
+ // background
+ const bg = x.createLinearGradient(0, 0, 0, H);
+ bg.addColorStop(0, '#0c0c0f'); bg.addColorStop(1, '#060607');
+ x.fillStyle = bg; x.fillRect(0, 0, W, H);
+ x.fillStyle = 'rgba(255,255,255,0.04)'; x.fillRect(0, 0, W, 6);
+
+ x.fillStyle = 'rgba(255,255,255,0.5)';
+ x.font = '600 26px system-ui, sans-serif';
+ x.fillText('TREASURY AUTOPILOT', 64, 90);
+ const armed = p.kill_switch ? 'KILL SWITCH' : p.armed ? 'ARMED' : 'DISARMED';
+ x.fillStyle = p.kill_switch ? '#fda4af' : p.armed ? '#ffffff' : 'rgba(255,255,255,0.4)';
+ x.font = '700 22px system-ui, sans-serif';
+ x.fillText(armed, 64, 124);
+
+ // balance
+ x.fillStyle = '#f4f4f5';
+ x.font = '800 96px system-ui, sans-serif';
+ x.fillText(fmtSol(r.balance_sol), 64, 240);
+ x.fillStyle = 'rgba(255,255,255,0.55)';
+ x.font = '500 34px system-ui, sans-serif';
+ const usd = r.balance_usd != null ? fmtUsd(r.balance_usd) : '';
+ x.fillText(`${usd}${usd ? ' · ' : ''}$THREE ${fmtCompact(r.three_accumulated)}`, 64, 292);
+
+ // runway gauge (top-right)
+ const gx = W - 200, gy = 200, rad = 96;
+ const g = runwayGauge(r);
+ x.lineWidth = 18; x.lineCap = 'round';
+ x.strokeStyle = 'rgba(255,255,255,0.10)';
+ x.beginPath(); x.arc(gx, gy, rad, 0, Math.PI * 2); x.stroke();
+ x.strokeStyle = g.tone === 'critical' ? '#fda4af' : g.tone === 'warn' ? '#fcd34d' : '#ffffff';
+ x.beginPath(); x.arc(gx, gy, rad, -Math.PI / 2, -Math.PI / 2 + Math.PI * 2 * g.fraction); x.stroke();
+ x.fillStyle = '#f4f4f5'; x.textAlign = 'center';
+ x.font = '800 44px system-ui, sans-serif'; x.fillText(g.label, gx, gy + 8);
+ x.fillStyle = 'rgba(255,255,255,0.5)'; x.font = '500 20px system-ui, sans-serif';
+ x.fillText(g.sublabel, gx, gy + 44);
+ x.textAlign = 'left';
+
+ // stat strip
+ const stats = [
+ ['Income 30d', fmtUsd(r.income_usd, { compact: true })],
+ ['Burn 30d', fmtUsd(r.cost_usd, { compact: true })],
+ ['Net', `${r.net_usd >= 0 ? '+' : ''}${fmtUsd(r.net_usd, { compact: true })}`],
+ ['Buybacks', String(r.buyback_count || 0)],
+ ['Swept', fmtSol(r.swept_sol || 0)],
+ ];
+ let sx = 64;
+ const sy = 380, sw = 224;
+ for (const [k, v] of stats) {
+ x.fillStyle = 'rgba(255,255,255,0.4)'; x.font = '600 20px system-ui, sans-serif';
+ x.fillText(k.toUpperCase(), sx, sy);
+ x.fillStyle = '#f4f4f5'; x.font = '700 34px system-ui, sans-serif';
+ x.fillText(v, sx, sy + 40);
+ sx += sw;
+ }
+
+ // rules
+ x.fillStyle = 'rgba(255,255,255,0.4)'; x.font = '600 20px system-ui, sans-serif';
+ x.fillText('POLICY RULES', 64, 500);
+ const rules = (p.rules || []).slice(0, 4);
+ let ry = 540;
+ for (const rule of rules) {
+ const l = policyLine(rule);
+ x.fillStyle = l.state === 'armed' ? '#ffffff' : 'rgba(255,255,255,0.4)';
+ x.font = '500 26px system-ui, sans-serif';
+ const text = l.text.length > 78 ? `${l.text.slice(0, 77)}…` : l.text;
+ x.fillText(`${l.glyph} ${text}`, 64, ry);
+ ry += 42;
+ }
+ if (!rules.length) {
+ x.fillStyle = 'rgba(255,255,255,0.3)'; x.font = '400 24px system-ui, sans-serif';
+ x.fillText('No rules armed — idle treasury.', 64, ry);
+ }
+
+ x.fillStyle = 'rgba(255,255,255,0.25)'; x.font = '500 20px system-ui, sans-serif';
+ x.fillText('three.ws · $THREE', 64, H - 40);
+ return c;
+ }
+
+ // ── live forwarding from the host SSE ─────────────────────────────────────
+ function observeLog(entries) {
+ if (!Array.isArray(entries) || !entries.length) return;
+ const hit = entries.some((e) => isTreasuryActivity(e?.activity) || e?.type === 'trade');
+ if (!hit) return;
+ // A treasury movement just landed — re-read the real balance so it ticks,
+ // debounced so a burst of log lines triggers a single refresh.
+ clearTimeout(softTimer);
+ softTimer = setTimeout(() => fetchAll({ soft: true }), 800);
+ }
+
+ // ── lifecycle ─────────────────────────────────────────────────────────────
+ function start() {
+ render(); // skeleton
+ fetchAll();
+ pollTimer = setInterval(() => {
+ if (destroyed || document.hidden) return;
+ if (owner && (state === 'populated')) fetchAll({ soft: true });
+ }, POLL_MS);
+ }
+
+ function destroy() {
+ destroyed = true;
+ clearInterval(pollTimer);
+ clearTimeout(compileTimer);
+ clearTimeout(softTimer);
+ }
+
+ start();
+ return { observeLog, refresh: () => fetchAll(), destroy };
+}
diff --git a/src/agent-screen.js b/src/agent-screen.js
index de4166552..05f6b4cc1 100644
--- a/src/agent-screen.js
+++ b/src/agent-screen.js
@@ -31,6 +31,12 @@ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { clone as cloneSkinnedScene } from 'three/addons/utils/SkeletonUtils.js';
import { AnimationManager } from './animation-manager.js';
import { createAgentScreenClient } from './shared/agent-screen-client.js';
+import { buildRunCommand, buildRunCommandHtml, RUNTIME_LABELS } from './agent-screen-runcmd.js';
+import { createTreasuryCockpit } from './agent-screen-treasury.js';
+import { MirrorPanel } from './agent-screen-mirror.js';
+import {
+ parsePnlDelta, accumulatePnl, emptyPnlState, unrealizedTotalUsd, emoteForExit, formatSol, formatUsd,
+} from './shared/trade-pnl.js';
import { agentAvatarGlb } from './shared/agent-3d.js';
import { getMeshoptDecoder } from './viewer/internal.js';
import { ScreenshotModal } from './components/screenshot-modal.js';
@@ -362,9 +368,11 @@ function defaultLayout() {
zenCam: true, // keep the avatar cam visible in zen by default
fit: 'contain', // 'contain' | 'cover'
panels: {
- cam: { hidden: false, min: false, x: null, y: null, w: 260 },
- log: { hidden: false, min: false, x: null, y: null, w: 320, h: null },
- stats: { hidden: true, min: false, x: null, y: null, w: 218 },
+ cam: { hidden: false, min: false, x: null, y: null, w: 260 },
+ log: { hidden: false, min: false, x: null, y: null, w: 320, h: null },
+ stats: { hidden: true, min: false, x: null, y: null, w: 218 },
+ treasury: { hidden: false, min: false, x: null, y: null, w: 344, h: null },
+ mirror: { hidden: true, min: false, x: null, y: null, w: 380, h: null },
},
};
}
@@ -478,6 +486,34 @@ async function boot(id) {
</div>
</div>
+ <!-- Treasury cockpit panel -->
+ <div class="asc-panel asc-panel--treasury" id="asc-panel-treasury" data-panel="treasury">
+ <div class="asc-panel-head" data-drag>
+ <span class="asc-panel-grip">⠿</span>
+ <span class="asc-panel-title">Treasury</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 (T)">✕</button>
+ </div>
+ </div>
+ <div class="asc-panel-body" id="asc-treasury-body"></div>
+ <div class="asc-resize" data-resize="wh"></div>
+ </div>
+
+ <!-- Copy-trade mirror panel -->
+ <div class="asc-panel asc-panel--mirror" id="asc-panel-mirror" data-panel="mirror">
+ <div class="asc-panel-head" data-drag>
+ <span class="asc-panel-grip">⠿</span>
+ <span class="asc-panel-title">Mirror</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 (M)">✕</button>
+ </div>
+ </div>
+ <div class="asc-panel-body" id="asc-mirror-body"></div>
+ <div class="asc-resize" data-resize="wh"></div>
+ </div>
+
<!-- Task input -->
<div class="asc-task-bar" id="asc-task-bar">
<form class="asc-task-form" id="asc-task-form" autocomplete="off">
@@ -594,11 +630,19 @@ async function boot(id) {
if (!r.ok) throw new Error(`HTTP ${r.status} fetching animation manifest`);
return r.json();
});
- const needed = manifest.filter((d) => d.name === 'idle');
- if (needed.length) {
- webcamAnimManager.setAnimationDefs(needed);
- await webcamAnimManager.loadAll();
- webcamAnimManager.play('idle');
+ // Register the idle loop plus the trade-reaction one-shots so the
+ // 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 defs = manifest.filter((d) => REACTION_CLIPS.includes(d.name));
+ const idleDef = defs.filter((d) => d.name === 'idle');
+ if (defs.length) {
+ webcamAnimManager.setAnimationDefs(defs);
+ if (idleDef.length) {
+ await webcamAnimManager.ensureLoaded('idle');
+ webcamAnimManager.play('idle');
+ }
}
} catch (err) {
console.warn('[agent-screen] idle clip load failed:', err);
@@ -730,11 +774,18 @@ async function boot(id) {
return d.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit', second: '2-digit' });
}
- function addLogEntry({ ts, activity, type }) {
+ function addLogEntry({ ts, activity, type, pnl }) {
if (logEmpty) { logEmpty.remove(); logEmpty = null; }
const entry = document.createElement('div');
const typeLabel = type || 'activity';
entry.className = `asc-log-entry type-${typeLabel}`;
+ // Tint realized exits by sign so the log reads as a green/red P&L tape.
+ const exitDelta = parsePnlDelta(pnl);
+ if (exitDelta?.phase === 'exit') {
+ const v = exitDelta.solDelta != null ? exitDelta.solDelta : exitDelta.realizedUsd;
+ if (v > 0) entry.classList.add('pnl-pos');
+ else if (v < 0) entry.classList.add('pnl-neg');
+ }
entry.innerHTML = `
<span class="asc-log-time">${fmtTime(ts || Date.now())}</span>
<span class="asc-log-type ${typeLabel}">${typeLabel}</span>
@@ -768,7 +819,110 @@ async function boot(id) {
});
});
+ // ── live PnL ticker ───────────────────────────────────────────────────
+ // Folds real 'trade' frames into a running session total (realized +
+ // unrealized, from real fills) and drives a transform-based count-up. Every
+ // number comes from an actual fill — no fake progress. Frames are deduped by
+ // timestamp so the reconnect backfill can't double-count an exit.
+ const pnlBtn = document.getElementById('asc-pnl');
+ const pnlValueEl = document.getElementById('asc-pnl-value');
+ const pnlDetailEl = document.getElementById('asc-pnl-detail');
+ let pnlState = emptyPnlState();
+ const seenPnlTs = new Set();
+ let sawUsd = false; // at least one fill priced into USD
+ let pnlDetailed = false; // compact ⇄ detailed toggle
+ let pnlAnimFrom = 0; // count-up animation origin (primary unit)
+ let pnlAnimTo = 0;
+ let pnlAnimStart = 0;
+ let pnlAnimRaf = null;
+
+ // Primary display number: USD when any fill priced, else realized SOL.
+ function pnlPrimary() {
+ if (sawUsd) return pnlState.realizedUsd + unrealizedTotalUsd(pnlState);
+ return pnlState.realizedSol;
+ }
+
+ function paintPnl(shownPrimary) {
+ const sign = shownPrimary > 1e-9 ? 'pos' : shownPrimary < -1e-9 ? 'neg' : '';
+ pnlBtn.classList.toggle('pos', sign === 'pos');
+ pnlBtn.classList.toggle('neg', sign === 'neg');
+ pnlValueEl.textContent = sawUsd
+ ? (formatUsd(shownPrimary) ?? '—')
+ : formatSol(shownPrimary);
+ if (pnlDetailed) {
+ pnlDetailEl.hidden = false;
+ const wl = `${pnlState.wins}W · ${pnlState.losses}L`;
+ const realized = sawUsd ? formatSol(pnlState.realizedSol) : (formatUsd(pnlState.realizedUsd) ?? null);
+ const unreal = unrealizedTotalUsd(pnlState);
+ const unrealStr = sawUsd && Math.abs(unreal) > 1e-9 ? ` · unreal ${formatUsd(unreal)}` : '';
+ pnlDetailEl.textContent = `${wl}${realized ? ` · ${realized}` : ''}${unrealStr}`;
+ } else {
+ pnlDetailEl.hidden = true;
+ }
+ }
+
+ function animatePnl() {
+ const DURATION = 520;
+ const tick = (now) => {
+ const t = Math.min(1, (now - pnlAnimStart) / DURATION);
+ const eased = 1 - Math.pow(1 - t, 3); // easeOutCubic
+ const shown = pnlAnimFrom + (pnlAnimTo - pnlAnimFrom) * eased;
+ paintPnl(shown);
+ if (t < 1) pnlAnimRaf = requestAnimationFrame(tick);
+ else pnlAnimRaf = null;
+ };
+ if (pnlAnimRaf) cancelAnimationFrame(pnlAnimRaf);
+ pnlAnimRaf = requestAnimationFrame(tick);
+ }
+
+ // Ingest one trade frame/log entry. Returns the parsed exit delta (or null)
+ // so the caller can fire the matching avatar emote on a fresh exit only.
+ function ingestTrade(entry) {
+ const delta = parsePnlDelta(entry?.pnl);
+ if (!delta) return null;
+ const ts = Number(entry.ts) || 0;
+ // Dedupe additive exits by timestamp; idempotent holds may always re-apply.
+ if (delta.phase === 'exit') {
+ if (ts && seenPnlTs.has(ts)) return null;
+ if (ts) seenPnlTs.add(ts);
+ }
+ if (delta.realizedUsd != null) sawUsd = true;
+ pnlState = accumulatePnl(pnlState, delta);
+
+ pnlBtn.hidden = false;
+ pnlAnimFrom = Number.isFinite(pnlAnimTo) ? pnlAnimTo : 0;
+ pnlAnimTo = pnlPrimary();
+ pnlAnimStart = performance.now();
+ animatePnl();
+ // brief bump only on a realized exit (the watchable moment)
+ if (delta.phase === 'exit') {
+ pnlBtn.classList.remove('bump');
+ void pnlBtn.offsetWidth; // restart the keyframe
+ pnlBtn.classList.add('bump');
+ }
+ return delta;
+ }
+
+ // Fire the avatar reaction for a realized exit. Gated on a skeleton-driveable
+ // rig so avatars that can't take canonical clips simply skip the emote (never
+ // a T-pose). Loads the one-shot lazily, then settles back to idle.
+ function emoteForTrade(delta) {
+ const clip = emoteForExit(delta);
+ if (!clip) return;
+ if (!webcamAnimManager || !webcamAnimManager.supportsCanonicalClips()) return;
+ webcamAnimManager.playOnce(clip, { settleTo: 'idle' }).catch(() => {});
+ }
+
+ // compact ⇄ detailed toggle (click or keyboard focus + Enter/Space on the button)
+ pnlBtn.addEventListener('click', () => {
+ pnlDetailed = !pnlDetailed;
+ paintPnl(pnlAnimTo);
+ });
+
// ── SSE client ─────────────────────────────────────────────────────────
+ let greeted = false; // wave once, on the first live connection only
+ let treasuryCockpit = null; // set once the Treasury panel mounts (below)
+ let mirrorPanel = null; // set once the Mirror panel mounts (below)
const client = createAgentScreenClient(id, {
onOpen({ agentName: n }) {
if (n) { agentNameEl.textContent = n; agentName = n; webcamName.textContent = n; }
@@ -778,10 +932,24 @@ async function boot(id) {
setLive();
recordFrame(frame);
if (frame.data) renderFrame(frame);
- if (frame.activity) addLogEntry(frame);
+ if (frame.activity) { addLogEntry(frame); treasuryCockpit?.observeLog([frame]); }
+ if (frame.type === 'trade') {
+ const delta = ingestTrade(frame);
+ if (delta) emoteForTrade(delta);
+ }
+ // Greet on the first live frame if onOpen's metadata event was missed.
+ if (!greeted) {
+ greeted = true;
+ if (webcamAnimManager?.supportsCanonicalClips()) {
+ webcamAnimManager.playOnce('wave', { settleTo: 'idle' }).catch(() => {});
+ }
+ }
},
onLog(entries) {
- entries.forEach(addLogEntry);
+ // Backfill: render the rows and fold their PnL in (deduped by ts), but
+ // don't emote — these are history, not a fresh fill happening on camera.
+ entries.forEach((e) => { addLogEntry(e); ingestTrade(e); });
+ treasuryCockpit?.observeLog(entries);
},
onDark() { setDark(); },
onError() {
@@ -847,6 +1015,8 @@ async function boot(id) {
cam: document.getElementById('asc-panel-cam'),
log: document.getElementById('asc-panel-log'),
stats: document.getElementById('asc-panel-stats'),
+ treasury: document.getElementById('asc-panel-treasury'),
+ mirror: document.getElementById('asc-panel-mirror'),
};
let zTop = 30;
@@ -860,7 +1030,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') el.style.height = `${p.h}px`;
+ if (p.h && (name === 'log' || name === 'treasury' || name === 'mirror')) el.style.height = `${p.h}px`;
// default position if none saved yet
const pw = el.offsetWidth || p.w || 240;
const ph = el.offsetHeight || 200;
@@ -868,6 +1038,8 @@ async function boot(id) {
if (x == null || y == null) {
const M = 16;
if (name === 'stats') { x = M; y = M; }
+ 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 { x = sr.width - pw - M; y = sr.height - ph - M; } // cam → bottom-right
}
@@ -966,6 +1138,27 @@ async function boot(id) {
el.querySelector('[data-act="close"]').addEventListener('click', () => setPanelHidden(name, true));
}
+ // ── Treasury cockpit: live autonomous-treasury control surface ───────────
+ // Mounts into the Treasury panel body; fetches its own real data (owner-only
+ // GET, 403 ⇒ viewer explainer) and ticks the live balance. The SSE handlers
+ // above forward activity into it via treasuryCockpit?.observeLog(...).
+ treasuryCockpit = createTreasuryCockpit({
+ agentId: id,
+ bodyEl: document.getElementById('asc-treasury-body'),
+ toast,
+ });
+
+ // ── Copy-trade mirror: live source/mirror cockpit ────────────────────────
+ // Owner drives the source-detect → re-quote → guarded-replicate loop and
+ // pushes the dual-column frame to the wall; a viewer sees a read-only armed
+ // state. Owns its own SSE to /api/pump/trades-stream (real PumpPortal feed).
+ mirrorPanel = new MirrorPanel({
+ body: document.getElementById('asc-mirror-body'),
+ agentId: id,
+ agentName,
+ onToast: toast,
+ });
+
function setPanelHidden(name, hidden) {
layout.panels[name].hidden = hidden;
const el = panelEls[name];
@@ -1120,6 +1313,7 @@ async function boot(id) {
// Cleanup on unload
window.addEventListener('beforeunload', () => {
client.disconnect();
+ if (pnlAnimRaf) cancelAnimationFrame(pnlAnimRaf);
if (webcamRafId) cancelAnimationFrame(webcamRafId);
webcamAnimManager?.detach();
webcamRenderer.dispose();
diff --git a/src/agents-live.js b/src/agents-live.js
index c9a74df44..5cba32134 100644
--- a/src/agents-live.js
+++ b/src/agents-live.js
@@ -13,6 +13,8 @@
// at, and tear it down when they leave. That keeps live pixels available for any
// agent on demand without paying for an idle browser per agent.
+import { parsePnlDelta, formatSol, formatUsd } from './shared/trade-pnl.js';
+
const grid = document.getElementById('al-grid');
const liveCount = document.getElementById('al-live-count');
const statsBar = document.getElementById('al-stats');
@@ -35,6 +37,16 @@ let _idleRepaint = null;
const FRAME_STALE_MS = 6000; // no frame within this window ⇒ fall back to activity
const WATCH_PING_MS = 20000; // re-assert watch intent while a card is on screen
+const WATCH_STATUS_MS = 4000; // refresh the warming/queued handoff while not yet live
+const STATUS_GRACE_POLLS = 3; // keep polling this many ticks to cover the intent→status write race
+
+// Cards currently intersecting the viewport. Only these signal watch intent and
+// poll handoff status, so the bounded Chromium pool spins up exactly for the
+// agents a viewer is actually looking at — and frees the slot the instant they
+// scroll away (the worker tears a caster down once its agent leaves the wanted
+// window). IntersectionObserver maintains this set.
+const _inView = new Set();
+let _observer = null;
function esc(s) {
return String(s ?? '').replace(/[&<>"']/g, (c) => ({
@@ -102,6 +114,10 @@ function buildCard(agent) {
<div class="al-card-screen">
<canvas class="al-card-canvas" width="640" height="360"></canvas>
<div class="al-card-overlay"></div>
+ <div class="al-card-warming" data-warming hidden>
+ <span class="al-warming-pulse"></span>
+ <span class="al-warming-text" data-warming-text></span>
+ </div>
<div class="al-card-live-badge">
<div class="al-card-live-dot idle" data-dot></div>
<span data-status>Connecting</span>
@@ -115,6 +131,7 @@ function buildCard(agent) {
<div class="al-card-meta">
<div class="al-card-name">${esc(name)}</div>
<div class="al-card-action" data-action>Connecting…</div>
+ <span class="al-card-pnl" data-pnl hidden></span>
</div>
<a class="al-card-watch-btn" href="${esc(watchHref)}" target="_blank" rel="noopener" onclick="event.stopPropagation()">Watch</a>
</div>`;
@@ -170,13 +187,24 @@ function paintActivity(state) {
const latest = i === 0;
const age = Math.max(0, Math.round((Date.now() - (a.ts || Date.now())) / 1000));
const ts = age < 5 ? 'now' : age < 60 ? `${age}s` : age < 3600 ? `${Math.round(age / 60)}m` : `${Math.round(age / 3600)}h`;
+ // A realized exit tints its line green/red so the terminal reads as a tape.
+ const exit = parsePnlDelta(a.pnl);
+ const exitSign = exit?.phase === 'exit'
+ ? (exit.solDelta ?? exit.realizedUsd ?? 0)
+ : null;
ctx.font = '600 11px "Courier New", monospace';
ctx.fillStyle = latest ? '#5fd08a' : 'rgba(255,255,255,0.2)';
const pfx = `[${ts}] `;
ctx.fillText(pfx, 16, y + i * lH);
const pw = ctx.measureText(pfx).width;
ctx.font = `${latest ? '600' : '400'} 12px "Courier New", monospace`;
- ctx.fillStyle = latest ? '#f0f0f4' : 'rgba(255,255,255,0.4)';
+ if (exitSign != null && exitSign !== 0) {
+ ctx.fillStyle = exitSign > 0
+ ? (latest ? '#6ee7a0' : 'rgba(110,231,160,0.55)')
+ : (latest ? '#f9a8a8' : 'rgba(249,168,168,0.55)');
+ } else {
+ ctx.fillStyle = latest ? '#f0f0f4' : 'rgba(255,255,255,0.4)';
+ }
ctx.fillText((a.activity || a.type || 'action').slice(0, 64), 16 + pw, y + i * lH);
});
@@ -187,6 +215,33 @@ function isLiveNow(state) {
return state.lastFrameAt && (Date.now() - state.lastFrameAt) < FRAME_STALE_MS;
}
+// Fold one trade frame/log entry's realized exit into the card's running PnL and
+// render the colored chip. Deduped by timestamp so the reconnect backfill can't
+// double-count. Returns true when a fresh exit moved the number.
+function ingestCardPnl(state, entry) {
+ const delta = parsePnlDelta(entry?.pnl);
+ if (!delta || delta.phase !== 'exit') return false;
+ const ts = Number(entry.ts) || 0;
+ if (ts && state.seenPnlTs.has(ts)) return false;
+ if (ts) state.seenPnlTs.add(ts);
+ if (delta.realizedUsd != null) { state.realizedUsd += delta.realizedUsd; state.sawUsd = true; }
+ if (delta.solDelta != null) state.realizedSol += delta.solDelta;
+ renderCardPnl(state);
+ return true;
+}
+
+function renderCardPnl(state) {
+ const chip = state.card.querySelector('[data-pnl]');
+ if (!chip) return;
+ const primary = state.sawUsd ? state.realizedUsd : state.realizedSol;
+ if (!Number.isFinite(primary)) { chip.hidden = true; return; }
+ chip.hidden = false;
+ chip.classList.toggle('pos', primary > 1e-9);
+ chip.classList.toggle('neg', primary < -1e-9);
+ chip.textContent = state.sawUsd ? (formatUsd(primary) ?? formatSol(state.realizedSol)) : formatSol(primary);
+ chip.title = `Session realized P&L · ${formatSol(state.realizedSol)}`;
+}
+
function attachStream(state) {
const { card, agentId } = state;
if (state.es) { try { state.es.close(); } catch { /* */ } }
@@ -199,7 +254,16 @@ function attachStream(state) {
function setLive(live) {
state.live = live;
dot.classList.toggle('idle', !live);
- statusEl.textContent = live ? 'Live' : (state.entries?.length ? 'Active' : 'Idle');
+ if (live) {
+ statusEl.textContent = 'Live';
+ state.reconnecting = false;
+ clearTimeout(state.reconnectLabelTimer);
+ } else {
+ dot.classList.remove('thin');
+ state.lowFpsSince = 0;
+ // Don't clobber a transient "Reconnecting…" label set by onerror below.
+ if (!state.reconnecting) statusEl.textContent = state.entries?.length ? 'Active' : 'Idle';
+ }
}
state.setLive = setLive;
@@ -216,23 +280,50 @@ function attachStream(state) {
img.src = src.startsWith('data:') ? src : 'data:image/png;base64,' + src;
state.lastFrameAt = Date.now();
setLive(true);
+ // Real pixels are arriving — the handoff is done. Hide the warming overlay
+ // and stop polling status; frames are now the source of truth.
+ hideWarming(state);
+ stopStatusPolling(state);
_fpsMap.set(agentId, (_fpsMap.get(agentId) || 0) + 1);
if (msg.activity && state.action) state.action.textContent = msg.activity;
+ if (msg.type === 'trade') ingestCardPnl(state, msg);
} catch { /* malformed */ }
});
es.addEventListener('log', (e) => {
try {
const { entries } = JSON.parse(e.data);
- if (Array.isArray(entries)) state.entries = entries;
+ if (Array.isArray(entries)) {
+ state.entries = entries;
+ // Fold any realized exits in the backfill into the running PnL chip.
+ entries.forEach((entry) => ingestCardPnl(state, entry));
+ }
if (!isLiveNow(state)) { paintActivity(state); setLive(false); }
} catch { /* */ }
});
es.addEventListener('open', () => { if (statusEl.textContent === 'Connecting') setLive(false); });
- es.addEventListener('dark', () => { setLive(false); paintActivity(state); });
+ es.addEventListener('dark', () => {
+ setLive(false);
+ paintActivity(state);
+ // Still on screen but no caster — resume the warming/queued handoff poll.
+ if (_inView.has(agentId)) startStatusPolling(state);
+ });
es.addEventListener('ping', () => { if (statusEl.textContent === 'Connecting') setLive(false); });
- es.onerror = () => setLive(false);
+ es.onerror = () => {
+ // Reclaim pool priority immediately on a drop — don't wait for the slow ping
+ // loop — and show a transient "Reconnecting…" (not "Idle") for the first 2s
+ // so a brief blip doesn't read as the agent going quiet.
+ if (_inView.has(agentId)) signalWatch(agentId);
+ state.reconnecting = true;
+ setLive(false);
+ statusEl.textContent = 'Reconnecting…';
+ clearTimeout(state.reconnectLabelTimer);
+ state.reconnectLabelTimer = setTimeout(() => {
+ state.reconnecting = false;
+ if (!isLiveNow(state)) statusEl.textContent = state.entries?.length ? 'Active' : 'Idle';
+ }, 2000);
+ };
}
// ── watch intent ────────────────────────────────────────────────────────────
@@ -250,6 +341,98 @@ function signalWatch(agentId) {
} catch { /* */ }
}
+// ── handoff status overlay (warming / queued) ────────────────────────────────
+// While a viewer is looking at a card that isn't live yet, the on-demand pool is
+// either spinning a browser up for it (warming) or it's waiting behind others
+// (queued). /api/agent/watch-status resolves which, from Redis only, so the card
+// shows an honest "warming up" / "#N in line" overlay instead of a dead box.
+
+function showWarming(state, text) {
+ const el = state.card.querySelector('[data-warming]');
+ if (!el) return;
+ const txt = el.querySelector('[data-warming-text]');
+ if (txt) txt.textContent = text;
+ // Drop the initial display:none gate once, then drive visibility via opacity so
+ // the overlay can fade in/out (and never blocks the card link — pointer-events:none).
+ el.hidden = false;
+ el.classList.add('is-visible');
+}
+
+function hideWarming(state) {
+ const el = state.card?.querySelector('[data-warming]');
+ if (el) el.classList.remove('is-visible');
+}
+
+function applyWatchStatus(state, data) {
+ if (isLiveNow(state)) { hideWarming(state); return; }
+ if (data?.state === 'warming') showWarming(state, 'Warming up a live view…');
+ else if (data?.state === 'queued') showWarming(state, `Live view queued · #${data.position || 1} in line`);
+ else hideWarming(state);
+}
+
+async function pollWatchStatus(state) {
+ if (isLiveNow(state)) { hideWarming(state); return; }
+ state.statusPolls = (state.statusPolls || 0) + 1;
+ try {
+ const res = await fetch(`/api/agent/watch-status?agentId=${encodeURIComponent(state.agentId)}`, {
+ headers: { accept: 'application/json' },
+ });
+ if (!res.ok) { hideWarming(state); return; }
+ const data = await res.json();
+ state.lastStatus = data.state;
+ applyWatchStatus(state, data);
+ } catch { hideWarming(state); }
+}
+
+// Keep refreshing while the card is on screen and not yet live, but only as long
+// as the pool is actually working on it (warming/queued) — with a short grace
+// window so the watch-intent → watch-status write race can't end polling early.
+function shouldKeepPolling(state) {
+ if (!_inView.has(state.agentId) || isLiveNow(state)) return false;
+ if (state.lastStatus === 'warming' || state.lastStatus === 'queued') return true;
+ return (state.statusPolls || 0) < STATUS_GRACE_POLLS;
+}
+
+function startStatusPolling(state) {
+ stopStatusPolling(state);
+ state.statusPolls = 0;
+ const tick = async () => {
+ await pollWatchStatus(state);
+ state.statusTimer = shouldKeepPolling(state) ? setTimeout(tick, WATCH_STATUS_MS) : null;
+ };
+ tick();
+}
+
+function stopStatusPolling(state) {
+ if (state.statusTimer) { clearTimeout(state.statusTimer); state.statusTimer = null; }
+}
+
+// ── intersection-driven intent ───────────────────────────────────────────────
+// Only cards actually on screen signal watch intent + poll status, so the bounded
+// pool spins up exactly for what's being looked at and frees the slot the instant
+// a viewer scrolls past (the agent falls out of the wanted window; the worker
+// tears its caster down).
+function getObserver() {
+ if (_observer) return _observer;
+ _observer = new IntersectionObserver((entries) => {
+ for (const entry of entries) {
+ const id = entry.target.dataset.agentId;
+ const state = _cards.get(id);
+ if (!state) continue;
+ if (entry.isIntersecting) {
+ _inView.add(id);
+ signalWatch(id);
+ if (!isLiveNow(state)) startStatusPolling(state);
+ } else {
+ _inView.delete(id);
+ stopStatusPolling(state);
+ hideWarming(state);
+ }
+ }
+ }, { threshold: 0.1 });
+ return _observer;
+}
+
// ── lifecycle ──────────────────────────────────────────────────────────────────
function mountAgent(agent) {
@@ -268,10 +451,17 @@ function mountAgent(agent) {
lastFrameAt: 0,
live: false,
es: null,
+ // running realized PnL for the card chip
+ realizedSol: 0,
+ realizedUsd: 0,
+ sawUsd: false,
+ seenPnlTs: new Set(),
};
_cards.set(id, state);
attachStream(state);
- signalWatch(id);
+ // Intent + status polling are intersection-driven (getObserver), so the pool
+ // only spins up for cards actually on screen and frees the slot on scroll-away.
+ getObserver().observe(card);
}
function renderEmpty() {
@@ -311,11 +501,24 @@ function updateStats() {
if (statsBar) statsBar.hidden = total === 0;
}
-// FPS + live-count ticker.
+// FPS + live-count ticker. Also surfaces per-card FPS in the live badge tooltip
+// and downgrades the dot to a "thin" amber state when a casting agent's own feed
+// stutters below ~1 fps for >3s — a stalled caster, distinct from a full dark.
function startFpsTicker() {
_fpsInterval = setInterval(() => {
let total = 0;
- for (const c of _fpsMap.values()) total += c;
+ for (const [id, s] of _cards) {
+ const c = _fpsMap.get(id) || 0;
+ total += c;
+ s.fps = c;
+ const live = isLiveNow(s);
+ const statusEl = s.card.querySelector('[data-status]');
+ const dot = s.card.querySelector('[data-dot]');
+ if (statusEl) statusEl.title = live ? (c > 0 ? `${c} fps` : 'stalled — no frames this second') : '';
+ if (live && c < 1) { if (!s.lowFpsSince) s.lowFpsSince = Date.now(); }
+ else s.lowFpsSince = 0;
+ if (dot) dot.classList.toggle('thin', !!(live && s.lowFpsSince && Date.now() - s.lowFpsSince > 3000));
+ }
_fpsMap.clear();
if (statFps) statFps.textContent = total > 0 ? `${total}/s` : '—';
updateStats();
@@ -336,11 +539,13 @@ function startIdleRepaint() {
}, 2500);
}
-// Re-assert watch intent for every mounted card on a slow cadence.
+// Re-assert watch intent on a slow cadence — but only for cards currently on
+// screen, so the pool keeps a slot for what a viewer is actually watching and
+// lets it expire for everything they've scrolled past.
function startWatchPings() {
setInterval(() => {
if (document.hidden) return;
- for (const id of _cards.keys()) signalWatch(id);
+ for (const id of _inView) signalWatch(id);
}, WATCH_PING_MS);
}
@@ -356,15 +561,29 @@ function suspendStreams() {
for (const s of _cards.values()) {
try { s.es?.close(); } catch { /* */ }
s.es = null;
+ stopStatusPolling(s);
+ clearTimeout(s.reconnectLabelTimer);
+ s.reconnecting = false;
+ hideWarming(s);
const statusEl = s.card.querySelector('[data-status]');
- if (statusEl) statusEl.textContent = 'Paused';
- s.card.querySelector('[data-dot]')?.classList.add('idle');
+ if (statusEl) { statusEl.textContent = 'Paused'; statusEl.title = ''; }
+ const dot = s.card.querySelector('[data-dot]');
+ dot?.classList.add('idle');
+ dot?.classList.remove('thin');
}
}
function resumeStreams() {
for (const s of _cards.values()) {
- if (!s.es) { attachStream(s); signalWatch(s.agentId); }
+ if (!s.es) attachStream(s);
+ }
+ // IntersectionObserver doesn't re-fire on tab focus, so re-assert intent and
+ // restart the handoff poll for cards that are still on screen.
+ for (const id of _inView) {
+ const s = _cards.get(id);
+ if (!s) continue;
+ signalWatch(id);
+ if (!isLiveNow(s)) startStatusPolling(s);
}
}
diff --git a/src/play/arena-world.js b/src/play/arena-world.js
index d21c3a922..374716df3 100644
--- a/src/play/arena-world.js
+++ b/src/play/arena-world.js
@@ -51,6 +51,19 @@ const PALETTE = {
down: 0xf87171,
};
+// Coin World Tour waypoints — the fixed loop the guide agent walks (driven by the
+// Playwright caster via window.__tour, see src/play/arena.js + src/tour-commentary.js).
+// Each is a floor position inside the arena radius (<15) plus the heading to face
+// on arrival. Names are the canonical keys shared with TOUR_WAYPOINTS; geometry
+// lives here because it's a 3D concern.
+const TOUR_STOPS = {
+ lobby: { x: 0, z: 6.8, face: Math.PI }, // entrance, looking into the arena
+ approach: { x: -3.4, z: 2.6, face: Math.PI * 0.86 }, // crossing the open floor
+ arena: { x: 0, z: -0.6, face: 0 }, // centre, among the agents
+ leader: { x: 0, z: -3.4, face: 0 }, // up at the #1 leader pad
+ eastwing: { x: 5.6, z: -0.2, face: -Math.PI / 2 }, // along the east ring, then loop back
+};
+
export class ArenaWorld {
constructor(canvas, { onAgentClick } = {}) {
this.canvas = canvas;
@@ -67,6 +80,8 @@ export class ArenaWorld {
this._raf = 0;
this._labels = new Set(); // ArenaAvatar with DOM labels to project
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
this._initRenderer();
this._initScene();
@@ -489,6 +504,10 @@ export class ArenaWorld {
if (this._keys.has('d') || this._keys.has('arrowright')) mx += 1;
mx += this._move.x; mz -= this._move.y;
const mag = Math.hypot(mx, mz);
+ // Coin World Tour autopilot: with no human at the controls, the guide walks
+ // the waypoint loop. Any real key/joystick input cancels it and takes over.
+ if (mag > 0.08 && this._tour) this.stopTour();
+ else if (this._tour && this._updateTour(dt)) return;
const moving = mag > 0.08;
if (moving && this._focus) this._focus = null; // walking breaks a focus lock
if (moving) {
@@ -523,6 +542,63 @@ export class ArenaWorld {
}
clearFocus() { this._focus = null; }
+ // ── Coin World Tour autopilot ─────────────────────────────────────────────
+ // The guide agent walks a deterministic waypoint loop. The Playwright caster
+ // drives this through window.__tour (src/play/arena.js); a human spectator at a
+ // keyboard never triggers it, and any manual input instantly yields control.
+
+ tourStops() { return Object.keys(TOUR_STOPS); }
+ tourLocation() { return this._tourLoc; }
+
+ // Walk the spectator avatar to a named waypoint. Resolves when it arrives (or a
+ // watchdog fires, so the caster never deadlocks on an unreachable stop). The
+ // real camera + avatar move — no faked motion.
+ tourGoTo(name) {
+ const stop = TOUR_STOPS[name];
+ if (!stop || !this.player) return Promise.resolve(false);
+ // Supersede any in-flight goal (resolve it so its awaiter unblocks).
+ if (this._tour?.resolve) this._tour.resolve(false);
+ return new Promise((resolve) => {
+ this._focus = null; // a moving guide can't hold a cinematic focus lock
+ this._tour = { name, x: stop.x, z: stop.z, face: stop.face ?? 0, resolve, deadline: performance.now() + 9000 };
+ });
+ }
+
+ stopTour() {
+ if (this._tour?.resolve) this._tour.resolve(false);
+ this._tour = null;
+ this.player?.setMoving(false);
+ }
+
+ // Drive the avatar one step toward the active tour goal. Returns true if it
+ // consumed this frame's movement (so manual control is skipped).
+ _updateTour(dt) {
+ const t = this._tour;
+ const p = this.player;
+ if (!t || !p) return false;
+ let dx = t.x - p.root.position.x;
+ let dz = t.z - p.root.position.z;
+ const dist = Math.hypot(dx, dz);
+ const arrived = dist < 0.25;
+ const timedOut = performance.now() > t.deadline;
+ if (arrived || timedOut) {
+ this._tourLoc = t.name;
+ p.root.rotation.y = dampAngle(p.root.rotation.y, t.face, 10 * dt);
+ p.setMoving(false);
+ this._tour = null;
+ t.resolve?.(true);
+ return true;
+ }
+ dx /= dist; dz /= dist;
+ const speed = 2.7 * dt;
+ p.root.position.x += dx * speed;
+ p.root.position.z += dz * speed;
+ p.root.rotation.y = dampAngle(p.root.rotation.y, Math.atan2(dx, dz), 9 * dt);
+ p.setMoving(true);
+ this._cam.bob = (this._cam.bob || 0) + dt * 8.5; // a gentle step-bob while walking
+ return true;
+ }
+
_updateCamera(dt) {
const c = this._cam;
c.yaw = dampAngle(c.yaw, c.targetYaw, 8 * dt);
@@ -539,7 +615,9 @@ export class ArenaWorld {
c.dist += (distTarget - c.dist) * Math.min(1, (focusing ? 4 : 8) * dt);
const cx = tx + Math.sin(c.yaw) * Math.cos(c.pitch) * c.dist;
const cz = tz + Math.cos(c.yaw) * Math.cos(c.pitch) * c.dist;
- const cy = ty + Math.sin(c.pitch) * c.dist + 1.0;
+ // Subtle step-bob while the guide is mid-tour — reads like a real walk.
+ const bob = this._tour ? Math.sin(c.bob || 0) * 0.06 : 0;
+ const cy = ty + Math.sin(c.pitch) * c.dist + 1.0 + bob;
this.camera.position.lerp(_tmpVec.set(cx, cy, cz), Math.min(1, 6 * dt));
this.camera.lookAt(tx, ty, tz);
}
diff --git a/src/play/arena.js b/src/play/arena.js
index 216d3d7aa..9f84cfa6c 100644
--- a/src/play/arena.js
+++ b/src/play/arena.js
@@ -7,6 +7,7 @@
// pinned over each agent's head. All data is real — no placeholders.
import { ArenaWorld } from './arena-world.js';
+import { tourCommentary } from '../tour-commentary.js';
import { createLogger } from '../shared/log.js';
import { fetchReputationBatch } from '../shared/agent-reputation.js';
import { fetchUnlocks } from '../shared/wallet-access.js';
@@ -43,6 +44,10 @@ const shortWallet = (a) => { const s = String(a || ''); return s.length > 10 ? `
let world = null;
let labelLayer = null;
+// Resolves once the scene + spectator avatar are live, so the tour caster knows
+// the world is walkable before it issues the first goTo().
+let _tourReadyResolve;
+const tourReady = new Promise((res) => { _tourReadyResolve = res; });
const labelEls = new Map(); // agentId -> { el, pos }
const rowsById = new Map(); // world id -> normalized row (for click routing)
@@ -120,6 +125,24 @@ function ingest(data) {
world = new ArenaWorld(canvas, { onAgentClick: focusAgent });
window.__arenaWorld = world; // debug/support hook
+ // Coin World Tour hook. The on-demand Playwright caster (workers/agent-screen-pool)
+ // detects this API, waits for ready(), then walks the guide agent through the
+ // waypoint loop — driving the REAL camera/avatar — while narrating the live
+ // launch feed. tour-commentary.js owns the pure trending→line mapping; the
+ // caster passes the feed in and renders the result. No faked motion, no mocks.
+ window.__tour = {
+ ready: () => tourReady,
+ waypoints: () => world?.tourStops?.() || [],
+ location: () => world?.tourLocation?.() || null,
+ goTo: (name) => world?.tourGoTo?.(name) ?? Promise.resolve(false),
+ // Commentary for the stop the guide most recently reached, given a live
+ // /api/pump/trending feed the caster fetched. Returns { line, badge, items, … }.
+ commentary: (trending) => tourCommentary(
+ world?.tourLocation?.() || 'lobby',
+ Array.isArray(trending) ? trending : [],
+ ),
+ };
+
// Spin up the render loop immediately so the floor + lights are alive while
// avatars stream in (perceived performance).
setLoading('Building the arena…');
@@ -143,6 +166,9 @@ function ingest(data) {
connectStream();
setLoading(null);
+ // World is walkable — release the tour caster.
+ _tourReadyResolve?.();
+
// Periodic board refresh (realized P&L only changes on a close; SSE also nudges this).
setInterval(loadBoardOnly, 30_000);
})();
diff --git a/src/sentiment-heatmap-3d.js b/src/sentiment-heatmap-3d.js
new file mode 100644
index 000000000..3f6f6f50a
--- /dev/null
+++ b/src/sentiment-heatmap-3d.js
@@ -0,0 +1,411 @@
+// sentiment-heatmap-3d.js — the live 3D market-sentiment field.
+//
+// A three.js scene of glowing pillars on a dark grid. Each pillar is one token:
+// • colour = 24h momentum (cold blue → slate → green-hot), via momentumColor
+// • height = 24h volume magnitude (log-normalised)
+// • glow = |momentum| + magnitude (emissive intensity), bloomed
+// $THREE is pinned at the centre, taller and wider, with a floating label. The
+// camera drifts slowly around the field; values lerp toward their targets every
+// frame so updates breathe in rather than pop. Bloom post-processing gives the
+// movers their flare; if the post-processing addons are unavailable the scene
+// falls back to a plain (still-emissive) render, never a black canvas.
+//
+// The renderer is pure presentation: it takes already-normalised tokens
+// ({ id, label, momentum, magnitude, … }) from sentiment-heatmap-data.js and
+// owns no network or business logic. Hover/focus are surfaced via callbacks so
+// the host (agent-screen) positions the HTML tooltip.
+
+import {
+ Scene,
+ PerspectiveCamera,
+ WebGLRenderer,
+ Color,
+ Group,
+ Mesh,
+ BoxGeometry,
+ PlaneGeometry,
+ MeshStandardMaterial,
+ AmbientLight,
+ DirectionalLight,
+ PointLight,
+ Vector2,
+ Vector3,
+ Raycaster,
+ GridHelper,
+ Sprite,
+ SpriteMaterial,
+ CanvasTexture,
+} from 'three';
+import { momentumColor, glowIntensity } from './sentiment-heatmap-data.js';
+
+const SPACING = 1.55; // grid cell spacing
+const BASE_H = 0.18; // minimum pillar height (so a flat token still has presence)
+const MAX_H = 2.6; // tallest non-anchor pillar
+const TILE_W = 1.05; // pillar footprint
+const LERP = 0.12; // per-frame approach toward target values
+
+const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));
+const lerp = (a, b, t) => a + (b - a) * t;
+
+// Square-ish grid cells ordered by distance from centre, so the loudest tokens
+// (assigned first) cluster around the anchor.
+function gridCells(n) {
+ const cols = Math.max(1, Math.ceil(Math.sqrt(n)));
+ const rows = Math.max(1, Math.ceil(n / cols));
+ const cells = [];
+ for (let r = 0; r < rows; r++) {
+ for (let c = 0; c < cols; c++) {
+ const x = (c - (cols - 1) / 2) * SPACING;
+ const z = (r - (rows - 1) / 2) * SPACING;
+ cells.push({ x, z, dist: Math.hypot(x, z) });
+ }
+ }
+ cells.sort((a, b) => a.dist - b.dist);
+ return cells;
+}
+
+function labelSprite(text) {
+ const pad = 24;
+ const canvas = document.createElement('canvas');
+ const ctx = canvas.getContext('2d');
+ ctx.font = '600 64px system-ui, -apple-system, sans-serif';
+ const w = Math.ceil(ctx.measureText(text).width) + pad * 2;
+ canvas.width = w;
+ canvas.height = 96;
+ const c2 = canvas.getContext('2d');
+ c2.font = '600 64px system-ui, -apple-system, sans-serif';
+ c2.textBaseline = 'middle';
+ c2.textAlign = 'center';
+ c2.fillStyle = 'rgba(0,0,0,0.55)';
+ c2.fillRect(0, 0, w, 96);
+ c2.fillStyle = '#ffffff';
+ c2.fillText(text, w / 2, 52);
+ const tex = new CanvasTexture(canvas);
+ tex.anisotropy = 4;
+ const mat = new SpriteMaterial({ map: tex, transparent: true, depthTest: false });
+ const sprite = new Sprite(mat);
+ sprite.scale.set((w / 96) * 0.62, 0.62, 1);
+ return sprite;
+}
+
+export class SentimentHeatmap3D {
+ constructor(canvas, { onHover } = {}) {
+ this.canvas = canvas;
+ this.onHover = onHover || null;
+ this.tiles = new Map(); // id → tile state
+ this.raf = null;
+ this.angle = 0.6;
+ this.drift = true;
+ this.focusT = 0; // 0..1 focus-on-$THREE zoom amount
+ this.focusTarget = 0;
+ this.disposed = false;
+ this.pointer = new Vector2(-2, -2);
+ this.hoverId = null;
+ this.anchorPos = new Vector3(0, 0, 0);
+
+ const renderer = new WebGLRenderer({
+ canvas,
+ antialias: true,
+ alpha: true,
+ preserveDrawingBuffer: true, // required for toDataURL frame capture
+ });
+ renderer.setPixelRatio(Math.min(window.devicePixelRatio, 2));
+ renderer.setClearColor(0x05060a, 1);
+ this.renderer = renderer;
+
+ const scene = new Scene();
+ this.scene = scene;
+
+ const camera = new PerspectiveCamera(46, 1, 0.1, 100);
+ camera.position.set(0, 7, 11);
+ camera.lookAt(0, 0.6, 0);
+ this.camera = camera;
+
+ scene.add(new AmbientLight(0x404a66, 0.8));
+ const key = new DirectionalLight(0xaab4ff, 0.7);
+ key.position.set(4, 9, 6);
+ scene.add(key);
+ const fill = new PointLight(0x3a4cff, 0.5, 40);
+ fill.position.set(-6, 5, -4);
+ scene.add(fill);
+
+ // Dark reflective ground + faint grid for depth.
+ const ground = new Mesh(
+ new PlaneGeometry(60, 60),
+ new MeshStandardMaterial({ color: 0x070810, roughness: 0.55, metalness: 0.4 }),
+ );
+ ground.rotation.x = -Math.PI / 2;
+ ground.position.y = -0.01;
+ scene.add(ground);
+ const grid = new GridHelper(48, 48, 0x1a2240, 0x0e1430);
+ grid.position.y = 0;
+ grid.material.transparent = true;
+ grid.material.opacity = 0.5;
+ scene.add(grid);
+
+ this.field = new Group();
+ scene.add(this.field);
+
+ this.raycaster = new Raycaster();
+
+ // Optional bloom — the flare that makes movers pop. Loaded lazily so a
+ // missing addon degrades to a plain render instead of breaking the panel.
+ this.composer = null;
+ this._initBloom();
+
+ this._onPointerMove = (e) => {
+ const r = canvas.getBoundingClientRect();
+ this.pointer.x = ((e.clientX - r.left) / r.width) * 2 - 1;
+ this.pointer.y = -((e.clientY - r.top) / r.height) * 2 + 1;
+ this._lastClientX = e.clientX;
+ this._lastClientY = e.clientY;
+ };
+ this._onPointerLeave = () => {
+ this.pointer.set(-2, -2);
+ if (this.hoverId) { this.hoverId = null; this.onHover?.(null); }
+ };
+ canvas.addEventListener('pointermove', this._onPointerMove);
+ canvas.addEventListener('pointerleave', this._onPointerLeave);
+
+ this._loop = this._loop.bind(this);
+ this.raf = requestAnimationFrame(this._loop);
+ }
+
+ async _initBloom() {
+ try {
+ const [{ EffectComposer }, { RenderPass }, { UnrealBloomPass }, { OutputPass }] = await Promise.all([
+ import('three/addons/postprocessing/EffectComposer.js'),
+ import('three/addons/postprocessing/RenderPass.js'),
+ import('three/addons/postprocessing/UnrealBloomPass.js'),
+ import('three/addons/postprocessing/OutputPass.js'),
+ ]);
+ if (this.disposed) return;
+ const composer = new EffectComposer(this.renderer);
+ composer.addPass(new RenderPass(this.scene, this.camera));
+ const bloom = new UnrealBloomPass(new Vector2(1, 1), 0.9, 0.6, 0.2);
+ composer.addPass(bloom);
+ composer.addPass(new OutputPass());
+ this.bloom = bloom;
+ this.composer = composer;
+ this._applySize();
+ } catch {
+ // Plain render path stays in effect — still emissive, just no bloom halo.
+ this.composer = null;
+ }
+ }
+
+ // Loading state: a dim lattice of neutral pillars that shimmer, shown before
+ // real data arrives so the panel is never an empty void.
+ showLoadingLattice() {
+ if (this.tiles.size) return;
+ const placeholder = [];
+ const cells = gridCells(16);
+ for (let i = 0; i < 16; i++) {
+ placeholder.push({ id: `__ph_${i}`, label: '', momentum: 0, magnitude: 0.18 + (i % 4) * 0.05, placeholder: true });
+ }
+ this._render(placeholder, cells);
+ this._loading = true;
+ }
+
+ setData(tokens) {
+ this._loading = false;
+ const list = Array.isArray(tokens) ? tokens.slice(0, 48) : [];
+ // Anchor first (centre), then by descending magnitude so the busiest
+ // tokens take the cells nearest the centre.
+ const anchor = list.find((t) => t.featured);
+ const rest = list.filter((t) => !t.featured).sort((a, b) => b.magnitude - a.magnitude);
+ const ordered = anchor ? [anchor, ...rest] : rest;
+ const cells = gridCells(Math.max(1, ordered.length));
+ this._render(ordered, cells);
+ }
+
+ _render(ordered, cells) {
+ const seen = new Set();
+ ordered.forEach((tok, i) => {
+ const cell = cells[i] || { x: 0, z: 0 };
+ seen.add(tok.id);
+ const featured = !!tok.featured;
+ const targetH = featured
+ ? BASE_H + MAX_H * 1.25
+ : BASE_H + tok.magnitude * MAX_H;
+ const col = momentumColor(tok.momentum);
+ const targetColor = new Color(col.r, col.g, col.b);
+ const targetGlow = tok.placeholder ? 0.15 : glowIntensity(tok.momentum, tok.magnitude) * (featured ? 1.35 : 1);
+ const w = featured ? TILE_W * 1.5 : TILE_W;
+
+ let tile = this.tiles.get(tok.id);
+ if (!tile) {
+ const geo = new BoxGeometry(w, 1, w);
+ geo.translate(0, 0.5, 0); // grow upward from the ground
+ const mat = new MeshStandardMaterial({
+ color: targetColor.clone(),
+ emissive: targetColor.clone(),
+ emissiveIntensity: 0.2,
+ roughness: 0.35,
+ metalness: 0.15,
+ });
+ const mesh = new Mesh(geo, mat);
+ mesh.position.set(cell.x, 0, cell.z);
+ mesh.scale.y = BASE_H;
+ mesh.userData.tokenId = tok.id;
+ this.field.add(mesh);
+ tile = {
+ mesh,
+ curH: BASE_H,
+ targetH,
+ targetColor,
+ curColor: targetColor.clone(),
+ targetGlow,
+ curGlow: 0.2,
+ targetX: cell.x,
+ targetZ: cell.z,
+ token: tok,
+ featured,
+ };
+ if (featured) {
+ const sprite = labelSprite(tok.label || '$THREE');
+ sprite.position.set(0, 0, 0);
+ mesh.add(sprite);
+ tile.sprite = sprite;
+ this.anchorPos.set(cell.x, 0, cell.z);
+ }
+ this.tiles.set(tok.id, tile);
+ } else {
+ tile.targetH = targetH;
+ tile.targetColor = targetColor;
+ tile.targetGlow = targetGlow;
+ tile.targetX = cell.x;
+ tile.targetZ = cell.z;
+ tile.token = tok;
+ if (featured) this.anchorPos.set(cell.x, 0, cell.z);
+ }
+ });
+ // Remove tiles that left the field.
+ for (const [id, tile] of this.tiles) {
+ if (!seen.has(id)) {
+ this.field.remove(tile.mesh);
+ tile.mesh.geometry.dispose();
+ tile.mesh.material.dispose();
+ if (tile.sprite) { tile.sprite.material.map?.dispose(); tile.sprite.material.dispose(); }
+ this.tiles.delete(id);
+ }
+ }
+ }
+
+ focusThree() {
+ this.focusTarget = this.focusTarget > 0.5 ? 0 : 1;
+ }
+ setDrift(on) { this.drift = on; }
+
+ _updateHover() {
+ if (!this.onHover) return;
+ this.raycaster.setFromCamera(this.pointer, this.camera);
+ const hits = this.raycaster.intersectObjects(this.field.children, false);
+ const hit = hits.find((h) => h.object.userData.tokenId && !String(h.object.userData.tokenId).startsWith('__ph_'));
+ const id = hit ? hit.object.userData.tokenId : null;
+ if (id !== this.hoverId) {
+ this.hoverId = id;
+ if (id) {
+ const tile = this.tiles.get(id);
+ this.onHover?.(tile?.token || null, this._lastClientX, this._lastClientY);
+ } else {
+ this.onHover?.(null);
+ }
+ } else if (id) {
+ // keep tooltip following the cursor
+ const tile = this.tiles.get(id);
+ this.onHover?.(tile?.token || null, this._lastClientX, this._lastClientY);
+ }
+ }
+
+ _loop() {
+ if (this.disposed) return;
+ this.raf = requestAnimationFrame(this._loop);
+
+ // Camera drift / focus tween.
+ this.focusT = lerp(this.focusT, this.focusTarget, 0.08);
+ if (this.drift) this.angle += 0.0016;
+ const radius = lerp(13, 6.5, this.focusT);
+ const height = lerp(7.5, 4.2, this.focusT);
+ const cx = lerp(0, this.anchorPos.x, this.focusT);
+ const cz = lerp(0, this.anchorPos.z, this.focusT);
+ this.camera.position.set(cx + Math.sin(this.angle) * radius, height, cz + Math.cos(this.angle) * radius);
+ this.camera.lookAt(cx, lerp(0.6, 1.2, this.focusT), cz);
+
+ const t = performance.now() * 0.001;
+ for (const tile of this.tiles.values()) {
+ tile.curH = lerp(tile.curH, tile.targetH, LERP);
+ tile.mesh.scale.y = tile.curH;
+ tile.mesh.position.x = lerp(tile.mesh.position.x, tile.targetX, LERP);
+ tile.mesh.position.z = lerp(tile.mesh.position.z, tile.targetZ, LERP);
+ tile.curColor.lerp(tile.targetColor, LERP);
+ tile.mesh.material.color.copy(tile.curColor);
+ tile.mesh.material.emissive.copy(tile.curColor);
+ // Loading shimmer + gentle live breathing on the glow.
+ const breathe = this._loading
+ ? 0.5 + 0.5 * Math.sin(t * 2 + tile.mesh.position.x)
+ : 1 + 0.06 * Math.sin(t * 1.4 + tile.mesh.position.z);
+ tile.curGlow = lerp(tile.curGlow, tile.targetGlow, LERP);
+ const hovered = tile.mesh.userData.tokenId === this.hoverId;
+ tile.mesh.material.emissiveIntensity = clamp(tile.curGlow * breathe + (hovered ? 0.5 : 0), 0, 2.2);
+ if (tile.sprite) tile.sprite.position.y = tile.curH + 0.6;
+ }
+
+ this._updateHover();
+
+ if (this.composer) this.composer.render();
+ else this.renderer.render(this.scene, this.camera);
+ }
+
+ _applySize() {
+ const w = this.canvas.clientWidth || 320;
+ const h = this.canvas.clientHeight || 240;
+ this.renderer.setSize(w, h, false);
+ this.camera.aspect = w / Math.max(1, h);
+ this.camera.updateProjectionMatrix();
+ if (this.composer) this.composer.setSize(w, h);
+ if (this.bloom) this.bloom.setSize(w, h);
+ }
+ resize() { this._applySize(); }
+
+ // Capture the current frame as a compact JPEG data URL for the wall push.
+ // Forces a fresh render (preserveDrawingBuffer hands back the live field),
+ // then downscales into a 2D canvas so the payload stays well under the
+ // push endpoint's size cap regardless of device pixel ratio.
+ captureFrame(maxW = 720) {
+ if (this.composer) this.composer.render();
+ else this.renderer.render(this.scene, this.camera);
+ try {
+ const sw = this.canvas.width || 1;
+ const sh = this.canvas.height || 1;
+ const scale = Math.min(1, maxW / sw);
+ const w = Math.max(1, Math.round(sw * scale));
+ const h = Math.max(1, Math.round(sh * scale));
+ const tmp = document.createElement('canvas');
+ tmp.width = w;
+ tmp.height = h;
+ const ctx = tmp.getContext('2d');
+ ctx.fillStyle = '#05060a';
+ ctx.fillRect(0, 0, w, h);
+ ctx.drawImage(this.canvas, 0, 0, w, h);
+ return tmp.toDataURL('image/jpeg', 0.82);
+ } catch {
+ return null;
+ }
+ }
+
+ dispose() {
+ this.disposed = true;
+ if (this.raf) cancelAnimationFrame(this.raf);
+ this.canvas.removeEventListener('pointermove', this._onPointerMove);
+ this.canvas.removeEventListener('pointerleave', this._onPointerLeave);
+ for (const tile of this.tiles.values()) {
+ tile.mesh.geometry.dispose();
+ tile.mesh.material.dispose();
+ if (tile.sprite) { tile.sprite.material.map?.dispose(); tile.sprite.material.dispose(); }
+ }
+ this.tiles.clear();
+ this.composer?.dispose?.();
+ this.renderer.dispose();
+ }
+}
diff --git a/src/sentiment-heatmap-data.js b/src/sentiment-heatmap-data.js
new file mode 100644
index 000000000..72a8b0b1c
--- /dev/null
+++ b/src/sentiment-heatmap-data.js
@@ -0,0 +1,213 @@
+// sentiment-heatmap-data.js — the data layer behind the 3D sentiment heatmap.
+//
+// Two halves:
+// 1. Pure transforms (normalizeToken / momentumColor / diffSpikes / …) — no
+// DOM, no network, fully unit-tested. They turn a raw token from
+// /api/intel/heatmap into the { id, label, momentum, magnitude } the
+// renderer consumes, map momentum→colour, and diff successive polls to
+// surface movers.
+// 2. createHeatmapPoller — a small polling loop over /api/intel/heatmap that
+// calls those transforms and reports { tokens, spikes, stale, error } to a
+// callback. Real fetches only.
+//
+// $THREE is always pinned first and flagged featured by the API; this layer
+// preserves that ordering and never reorders the anchor away from the centre.
+
+const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));
+
+// 24h price change (percent) that maps to full momentum saturation. A token up
+// 25% or more reads as maximally hot; down 25% or more as maximally cold. Chosen
+// so typical pump.fun daily swings spread across the ramp instead of clipping.
+export const MOMENTUM_FULL_SCALE_PCT = 25;
+
+// Map a raw API token to the render model. momentum ∈ [-1, 1] from 24h change;
+// magnitude ∈ [0, 1] from 24h volume on a log scale (volume spans many orders of
+// magnitude, so linear scaling would crush everything but the top token).
+export function normalizeToken(raw, { maxLogVolume } = {}) {
+ const change = Number.isFinite(raw?.change24h) ? raw.change24h : 0;
+ const momentum = clamp(change / MOMENTUM_FULL_SCALE_PCT, -1, 1);
+
+ const vol = Number.isFinite(raw?.volume24h) && raw.volume24h > 0 ? raw.volume24h : 0;
+ const logVol = vol > 0 ? Math.log10(vol) : 0;
+ // Normalise against the field's loudest token (passed in) so the busiest tile
+ // is full-size and the rest scale relative to it. Falls back to a fixed
+ // reference (10^7 ≈ $10M/day) when no field max is supplied.
+ const ref = Number.isFinite(maxLogVolume) && maxLogVolume > 0 ? maxLogVolume : 7;
+ const magnitude = clamp(logVol / ref, 0, 1);
+
+ return {
+ id: String(raw?.id || ''),
+ label: String(raw?.symbol || raw?.name || (raw?.id ? `${raw.id.slice(0, 4)}…` : '?')),
+ name: raw?.name || null,
+ image: raw?.image || null,
+ momentum,
+ magnitude,
+ change24h: change,
+ priceUsd: Number.isFinite(raw?.priceUsd) ? raw.priceUsd : null,
+ volume24h: vol,
+ marketCap: Number.isFinite(raw?.marketCap) ? raw.marketCap : null,
+ featured: !!raw?.featured,
+ sentiment: raw?.sentiment || null,
+ };
+}
+
+// Normalise a whole field at once: the volume reference is the field's own
+// loudest tile, so the busiest token always renders at full magnitude.
+export function normalizeField(rawTokens) {
+ const list = Array.isArray(rawTokens) ? rawTokens : [];
+ const maxLogVolume = list.reduce((m, t) => {
+ const v = Number(t?.volume24h) || 0;
+ return v > 0 ? Math.max(m, Math.log10(v)) : m;
+ }, 0);
+ return list.map((t) => normalizeToken(t, { maxLogVolume: maxLogVolume || 7 }));
+}
+
+// Perceptually-even cold→neutral→hot ramp, returned as { r, g, b } in [0, 1].
+// momentum -1 → deep blue (cold), 0 → slate (neutral), +1 → green-hot. The mid
+// anchor is a desaturated slate so a flat market reads as calm, not green.
+const COLD = { r: 0.21, g: 0.42, b: 0.95 }; // -1
+const NEUTRAL = { r: 0.32, g: 0.35, b: 0.42 }; // 0
+const HOT = { r: 0.13, g: 0.92, b: 0.46 }; // +1
+function lerpColor(a, b, t) {
+ return { r: a.r + (b.r - a.r) * t, g: a.g + (b.g - a.g) * t, b: a.b + (b.b - a.b) * t };
+}
+export function momentumColor(momentum) {
+ const m = clamp(Number(momentum) || 0, -1, 1);
+ if (m < 0) return lerpColor(NEUTRAL, COLD, -m);
+ return lerpColor(NEUTRAL, HOT, m);
+}
+
+// Emissive glow intensity for a tile: hotter/colder + louder = brighter. Neutral
+// low-volume tiles barely glow; strong movers with real volume blaze.
+export function glowIntensity(momentum, magnitude) {
+ const m = Math.abs(clamp(Number(momentum) || 0, -1, 1));
+ const v = clamp(Number(magnitude) || 0, 0, 1);
+ return clamp(0.12 + m * 0.7 + v * 0.35, 0, 1.4);
+}
+
+// Diff a fresh field against the previous one. A spike = a token whose |momentum|
+// jumped by at least `threshold` since the last poll (a real acceleration, not a
+// steady trend). Returns movers sorted by absolute delta, biggest first, each
+// tagged heating/cooling. New tokens entering the field with strong momentum also
+// count. Pure — caller owns the "previous" snapshot.
+export function diffSpikes(prev, next, threshold = 0.18) {
+ const prevById = new Map((prev || []).map((t) => [t.id, t]));
+ const spikes = [];
+ for (const t of next || []) {
+ const before = prevById.get(t.id);
+ if (!before) {
+ // Newly surfaced token — only a spike if it arrives already hot/cold.
+ if (Math.abs(t.momentum) >= Math.max(threshold, 0.4)) {
+ spikes.push({ ...t, delta: t.momentum, direction: t.momentum >= 0 ? 'heating' : 'cooling', fresh: true });
+ }
+ continue;
+ }
+ const delta = t.momentum - before.momentum;
+ if (Math.abs(delta) >= threshold) {
+ spikes.push({ ...t, delta, direction: delta >= 0 ? 'heating' : 'cooling', fresh: false });
+ }
+ }
+ spikes.sort((a, b) => Math.abs(b.delta) - Math.abs(a.delta));
+ return spikes;
+}
+
+// Rank movers for narration context: top gainers and losers by current momentum,
+// plus the anchor ($THREE) always called out. Returns a compact object the
+// narrator turns into a spoken line.
+export function rankMovers(tokens, { count = 3 } = {}) {
+ const list = (tokens || []).filter((t) => Number.isFinite(t.change24h));
+ const byChange = [...list].sort((a, b) => b.change24h - a.change24h);
+ const gainers = byChange.filter((t) => t.change24h > 0).slice(0, count);
+ const losers = byChange.filter((t) => t.change24h < 0).reverse().slice(0, count);
+ const anchor = (tokens || []).find((t) => t.featured) || null;
+ const avg = list.length ? list.reduce((s, t) => s + t.momentum, 0) / list.length : 0;
+ return { gainers, losers, anchor, avgMomentum: avg, total: (tokens || []).length };
+}
+
+const fmtPct = (n) => `${n >= 0 ? '+' : ''}${Number(n).toFixed(1)}%`;
+
+// Build the compact, plain-language context handed to the brain for narration.
+// Coin-agnostic for the field; $THREE is named because it is the anchor three.ws
+// tracks. Never recommends or shills — describes observed market data only.
+export function buildNarrationContext({ spikes, movers }) {
+ const lines = [];
+ if (movers?.anchor) {
+ const a = movers.anchor;
+ const parts = [`$THREE ${fmtPct(a.change24h)} 24h`];
+ if (a.sentiment && Number.isFinite(a.sentiment.score)) {
+ const mood = a.sentiment.score > 0.15 ? 'positive' : a.sentiment.score < -0.15 ? 'negative' : 'mixed';
+ parts.push(`chat sentiment ${mood} (${a.sentiment.posPct}% bullish, ${a.sentiment.count} msgs)`);
+ }
+ lines.push(parts.join(', '));
+ }
+ const climate =
+ movers?.avgMomentum > 0.12 ? 'Heating across the board'
+ : movers?.avgMomentum < -0.12 ? 'Cooling across the board'
+ : 'Mixed tape';
+ lines.push(`${climate} (${movers?.total ?? 0} tokens tracked).`);
+ if (movers?.gainers?.length) {
+ lines.push(`Top movers up: ${movers.gainers.map((t) => `${t.label} ${fmtPct(t.change24h)}`).join(', ')}.`);
+ }
+ if (movers?.losers?.length) {
+ lines.push(`Down: ${movers.losers.map((t) => `${t.label} ${fmtPct(t.change24h)}`).join(', ')}.`);
+ }
+ if (spikes?.length) {
+ const s = spikes[0];
+ lines.push(`Just ${s.direction}: ${s.label} ${fmtPct(s.change24h)}.`);
+ }
+ return lines.join('\n');
+}
+
+// ── poller ───────────────────────────────────────────────────────────────────
+// Polls /api/intel/heatmap on an interval, normalises, diffs for spikes, and
+// reports to onUpdate. Holds the last good field so a transient fetch failure is
+// surfaced as { stale, error } without dropping the rendered field.
+
+export function createHeatmapPoller({
+ endpoint = '/api/intel/heatmap',
+ limit = 28,
+ intervalMs = 20_000,
+ spikeThreshold = 0.18,
+ onUpdate,
+ onError,
+} = {}) {
+ let prev = [];
+ let timer = null;
+ let stopped = false;
+ let inFlight = false;
+
+ async function poll() {
+ if (inFlight || stopped) return;
+ inFlight = true;
+ try {
+ const res = await fetch(`${endpoint}?limit=${encodeURIComponent(limit)}`, {
+ headers: { accept: 'application/json' },
+ });
+ if (!res.ok) throw new Error(`heatmap ${res.status}`);
+ const data = await res.json();
+ if (stopped) return;
+ const tokens = normalizeField(data?.tokens || []);
+ const spikes = diffSpikes(prev, tokens, spikeThreshold);
+ const movers = rankMovers(tokens);
+ prev = tokens;
+ onUpdate?.({ tokens, spikes, movers, stale: !!data?.stale, fetchedAt: data?.fetchedAt, error: null });
+ } catch (err) {
+ if (!stopped) onError?.(err);
+ } finally {
+ inFlight = false;
+ }
+ }
+
+ function start() {
+ stopped = false;
+ poll();
+ timer = setInterval(poll, intervalMs);
+ }
+ function stop() {
+ stopped = true;
+ if (timer) { clearInterval(timer); timer = null; }
+ }
+ function refresh() { return poll(); }
+
+ return { start, stop, refresh };
+}
diff --git a/src/shared/forge-frames.js b/src/shared/forge-frames.js
new file mode 100644
index 000000000..2945999b8
--- /dev/null
+++ b/src/shared/forge-frames.js
@@ -0,0 +1,213 @@
+// forge-frames.js — pure logic for the Live Avatar Forge.
+//
+// Shared by THREE callers so the staged narration and the final-frame sidecar
+// never drift between them:
+// • src/agent-screen.js — the in-browser forge driver (the viewer watches)
+// • workers/agent-forge/ — the headless broadcast worker
+// • tests/forge-frame.test.js
+//
+// Zero DOM, zero env, zero network: every export is a pure function of its
+// input. The real generation (POST/poll /api/forge on the free NVIDIA NIM
+// TRELLIS lane) and the real GLB load/animation live in the callers; this file
+// only turns a generation state into a holder-readable line and packs/unpacks
+// the GLB url that rides along with the final frame.
+
+// The free TRELLIS lane conditions on ~77 characters; a longer prompt is
+// silently truncated by the model, so we trim with intent and tell the user.
+export const TRELLIS_PROMPT_LIMIT = 77;
+
+const clamp = (n, lo, hi) => Math.max(lo, Math.min(hi, n));
+
+// Normalize a raw prompt for the free lane. Returns the cleaned prompt, whether
+// it was trimmed to the conditioning window, and the original length so the UI
+// can show "trimmed to fit". Trimming happens on a word boundary when possible
+// so we never cut a word in half mid-token.
+export function clampPrompt(raw) {
+ const text = String(raw == null ? '' : raw).replace(/\s+/g, ' ').trim();
+ if (text.length <= TRELLIS_PROMPT_LIMIT) {
+ return { prompt: text, trimmed: false, originalLength: text.length };
+ }
+ let cut = text.slice(0, TRELLIS_PROMPT_LIMIT);
+ const lastSpace = cut.lastIndexOf(' ');
+ // Only snap to the word boundary if it doesn't throw away too much (>60% kept).
+ if (lastSpace > TRELLIS_PROMPT_LIMIT * 0.6) cut = cut.slice(0, lastSpace);
+ return { prompt: cut.trim(), trimmed: true, originalLength: text.length };
+}
+
+// Is a prompt acceptable to submit? The free lane needs ≥3 characters of actual
+// subject. Returns { ok } or { ok:false, reason } with a holder-readable reason.
+export function validatePrompt(raw) {
+ const text = String(raw == null ? '' : raw).trim();
+ if (text.length < 3) {
+ return { ok: false, reason: 'Describe a concrete object — at least a few characters.' };
+ }
+ return { ok: true };
+}
+
+// Map a real /api/forge job/poll state to a single holder-readable narration
+// line. The states come straight from the pipeline — no fabricated steps:
+// submitting → before the job is accepted
+// queued → accepted, waiting for a free GPU slot
+// running / reconstruct → the mesh is being built (TRELLIS reconstruct)
+// done → GLB ready
+// failed → generation failed
+// `mode` ('image' before the mesh stage) and `eta_seconds` refine the line when
+// the pipeline reports them. Unknown states fall back to a neutral "working".
+export function forgeStageNarration(state = {}) {
+ const status = String(state.status || state.stage || '').toLowerCase();
+ const eta = Number(state.eta_seconds) > 0 ? Math.round(Number(state.eta_seconds)) : null;
+ const etaSuffix = eta ? ` — ~${eta}s` : '';
+
+ switch (status) {
+ case 'submitting':
+ case 'submit':
+ return 'Forging on the free TRELLIS lane…';
+ case 'queued':
+ case 'queue':
+ return `Queued on the free NVIDIA NIM lane${etaSuffix}`;
+ case 'image':
+ case 'texturing':
+ return 'Drafting the look…';
+ case 'running':
+ case 'reconstruct':
+ case 'mesh':
+ return `Building geometry & texturing${etaSuffix}`;
+ case 'done':
+ case 'ready':
+ return 'Model ready — loading into the cam';
+ case 'failed':
+ case 'error':
+ return 'Forge failed — try a more concrete prompt';
+ default:
+ return `Forging${etaSuffix}`;
+ }
+}
+
+// A forge progress frame for screenPush — the live narration other viewers see.
+// `type: 'analysis'` matches the activity-log "analysis" lane. The optional
+// `meta` rides in the frame sidecar (used only on the final frame).
+export function buildForgeFrame({ activity, type = 'analysis', meta = null }) {
+ const frame = { activity: String(activity || ''), type };
+ if (meta && typeof meta === 'object') frame.meta = meta;
+ return frame;
+}
+
+// The final forge frame: narration + a sidecar carrying the durable GLB url and
+// the three.ws viewer link so every connected viewer can load and animate the
+// freshly-forged avatar. `kind:'forge'` tags it for parseForgeFrame().
+export function finalForgeFrame({ prompt, glbUrl, viewerUrl, tier = null, backend = null, durable = null }) {
+ const meta = {
+ kind: 'forge',
+ glbUrl: String(glbUrl || ''),
+ viewerUrl: String(viewerUrl || ''),
+ prompt: String(prompt || ''),
+ };
+ if (tier) meta.tier = String(tier);
+ if (backend) meta.backend = String(backend);
+ if (durable != null) meta.durable = Boolean(durable);
+ const shortPrompt = meta.prompt.length > 60 ? `${meta.prompt.slice(0, 57)}…` : meta.prompt;
+ return buildForgeFrame({
+ activity: `Forged "${shortPrompt}" — rigging & animating`,
+ type: 'analysis',
+ meta,
+ });
+}
+
+// Pull the forge sidecar out of an incoming SSE frame, or null if the frame
+// isn't a forge-completion frame. Validates the GLB url is an http(s) link so a
+// viewer never tries to load a junk value. Used by the viewer (agent-screen.js)
+// to know when to swap the Avatar Cam to the new model, and by the live wall
+// (agents-live.js) to show "forged: <prompt>".
+export function parseForgeFrame(frame) {
+ const meta = frame && typeof frame === 'object' ? frame.meta : null;
+ if (!meta || meta.kind !== 'forge') return null;
+ const glbUrl = typeof meta.glbUrl === 'string' ? meta.glbUrl.trim() : '';
+ if (!/^https?:\/\//i.test(glbUrl)) return null;
+ const viewerUrl = typeof meta.viewerUrl === 'string' && /^https?:\/\//i.test(meta.viewerUrl.trim())
+ ? meta.viewerUrl.trim()
+ : '';
+ return {
+ glbUrl,
+ viewerUrl,
+ prompt: typeof meta.prompt === 'string' ? meta.prompt : '',
+ tier: typeof meta.tier === 'string' ? meta.tier : null,
+ backend: typeof meta.backend === 'string' ? meta.backend : null,
+ durable: typeof meta.durable === 'boolean' ? meta.durable : null,
+ };
+}
+
+// Build the three.ws viewer link for a GLB url, given a site origin. Mirrors the
+// `${base}/viewer?src=…` link the forge tools return.
+export function viewerLinkFor(glbUrl, origin = 'https://three.ws') {
+ const base = String(origin || 'https://three.ws').replace(/\/$/, '');
+ return `${base}/viewer?src=${encodeURIComponent(String(glbUrl || ''))}`;
+}
+
+// A bounded, sanitized sidecar for the push API to persist. Caps every string so
+// a frame record can't be inflated past the store's size budget, and drops any
+// field that isn't part of the forge contract. Returns null for non-forge meta.
+export function sanitizeFrameMeta(meta, { maxLen = 2048 } = {}) {
+ if (!meta || typeof meta !== 'object') return null;
+ if (meta.kind === 'a2a_hire') return sanitizeHireMeta(meta);
+ if (meta.kind !== 'forge') return null;
+ const str = (v, n) => (typeof v === 'string' ? v.slice(0, n) : '');
+ const out = {
+ kind: 'forge',
+ glbUrl: str(meta.glbUrl, maxLen),
+ viewerUrl: str(meta.viewerUrl, maxLen),
+ prompt: str(meta.prompt, 320),
+ };
+ if (typeof meta.tier === 'string') out.tier = meta.tier.slice(0, 32);
+ if (typeof meta.backend === 'string') out.backend = meta.backend.slice(0, 64);
+ if (typeof meta.durable === 'boolean') out.durable = meta.durable;
+ // A forge sidecar is only meaningful with an http(s) GLB url.
+ if (!/^https?:\/\//i.test(out.glbUrl)) return null;
+ return out;
+}
+
+// Bounded sanitizer for the live agent-to-agent hire visualizer sidecar. Mirrors
+// the shape api/_lib/a2a-hire-phases.js#hirePhaseFrame emits: a phase tag plus the
+// quote/cap/signature payload the receipt + coin-transfer UI render. Strings are
+// capped; explorer urls are http(s)-gated so a push can't smuggle a junk link to
+// the viewer; numbers are coerced finite-or-null.
+function sanitizeHireMeta(meta) {
+ const str = (v, n) => (typeof v === 'string' ? v.slice(0, n) : null);
+ const num = (v) => (typeof v === 'number' && Number.isFinite(v) ? v : null);
+ const httpUrl = (v) => {
+ const s = str(v, 512);
+ return s && /^https?:\/\//i.test(s) ? s : null;
+ };
+ const cap = meta.cap && typeof meta.cap === 'object'
+ ? {
+ perCallCap: num(meta.cap.perCallCap),
+ dailyUsd: num(meta.cap.dailyUsd),
+ dailyRemaining: num(meta.cap.dailyRemaining),
+ overCap: typeof meta.cap.overCap === 'boolean' ? meta.cap.overCap : undefined,
+ }
+ : null;
+ return {
+ kind: 'a2a_hire',
+ phase: str(meta.phase, 32),
+ phaseIndex: num(meta.phaseIndex),
+ ok: typeof meta.ok === 'boolean' ? meta.ok : true,
+ hireId: str(meta.hireId, 64),
+ slug: str(meta.slug, 120),
+ skill: str(meta.skill, 120),
+ providerName: str(meta.providerName, 120),
+ providerId: str(meta.providerId, 64),
+ hirerId: str(meta.hirerId, 64),
+ hirerName: str(meta.hirerName, 120),
+ usd: num(meta.usd),
+ maxUsd: num(meta.maxUsd),
+ cap,
+ network: str(meta.network, 16) || 'mainnet',
+ txSig: str(meta.txSig, 128),
+ paymentExplorer: httpUrl(meta.paymentExplorer),
+ invocationSig: str(meta.invocationSig, 128),
+ invocationExplorer: httpUrl(meta.invocationExplorer),
+ resultSummary: str(meta.resultSummary, 280),
+ error: str(meta.error, 280),
+ };
+}
+
+export { clamp as _clamp };
diff --git a/src/shared/pnl-fetch.js b/src/shared/pnl-fetch.js
new file mode 100644
index 000000000..76a81b7fa
--- /dev/null
+++ b/src/shared/pnl-fetch.js
@@ -0,0 +1,154 @@
+// pnl-fetch.js — the data layer for the live Portfolio / PnL HUD.
+//
+// Two real backends, two transports, one normalized `PnlSnapshot` out:
+// • fetchBatchBalances(ids) → ONE POST /api/agents/balances for many wallets
+// (the wall hydrates every visible card's badge in a single round-trip).
+// • fetchAgentBalance(id) → the same endpoint for a single agent (the HUD
+// poll), returning that agent's snapshot or an un-priced one.
+// • subscribePortfolio(id, …) → owner-only SSE to /api/agents/:id/portfolio/
+// stream, pushing fresher net-worth + per-holding cost basis between polls.
+// Reconnects with backoff, mirroring agent-screen-client.js.
+//
+// Errors surface to the caller (handled at the UI boundary) — a failed read
+// returns an un-priced snapshot, never a fake zero, and never a synthesized
+// curve. No DOM here; all rendering lives in the HUD / badge.
+
+import { toPnlSnapshot, emptyPnlSnapshot } from './pnl-snapshot.js';
+
+// Mirror the server cap (api/agents/balances.js MAX_IDS) so we chunk correctly.
+const MAX_BATCH = 60;
+
+// Lazily reuse the app's CSRF-aware fetch; fall back to a credentialed fetch so
+// the module also works on pages that don't ship src/api.js.
+let _apiFetchPromise = null;
+function getApiFetch() {
+ if (!_apiFetchPromise) {
+ _apiFetchPromise = import('../api.js')
+ .then((m) => m.apiFetch)
+ .catch(() => (path, opts) => fetch(path, { credentials: 'include', ...opts }));
+ }
+ return _apiFetchPromise;
+}
+
+/**
+ * Value a batch of agent wallets in one request and return normalized snapshots
+ * keyed by agent id. Ids missing from the response (or that failed to price)
+ * resolve to an un-priced snapshot so callers can render every id uniformly.
+ *
+ * @param {string[]} agentIds
+ * @param {{ network?: 'mainnet'|'devnet' }} [opts]
+ * @returns {Promise<Map<string, import('./pnl-snapshot.js').PnlSnapshot>>}
+ */
+export async function fetchBatchBalances(agentIds, { network = 'mainnet' } = {}) {
+ const ids = [...new Set((agentIds || []).filter((x) => typeof x === 'string' && x))];
+ const out = new Map();
+ if (ids.length === 0) return out;
+
+ const apiFetch = await getApiFetch();
+ for (let i = 0; i < ids.length; i += MAX_BATCH) {
+ const chunk = ids.slice(i, i + MAX_BATCH);
+ let data = null;
+ try {
+ const res = await apiFetch('/api/agents/balances', {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ ids: chunk, network }),
+ allowAnonymous: true,
+ });
+ if (res.ok) ({ data } = await res.json());
+ } catch {
+ data = null; // surface as un-priced below; caller decides how to show it
+ }
+ for (const id of chunk) {
+ out.set(id, data && data[id] ? toPnlSnapshot(data[id]) : emptyPnlSnapshot());
+ }
+ }
+ return out;
+}
+
+/**
+ * Single-agent balance read (the HUD's poll). Returns a normalized snapshot,
+ * un-priced on any failure.
+ *
+ * @param {string} agentId
+ * @param {{ network?: 'mainnet'|'devnet' }} [opts]
+ * @returns {Promise<import('./pnl-snapshot.js').PnlSnapshot>}
+ */
+export async function fetchAgentBalance(agentId, opts = {}) {
+ if (!agentId) return emptyPnlSnapshot();
+ const map = await fetchBatchBalances([agentId], opts);
+ return map.get(agentId) || emptyPnlSnapshot();
+}
+
+/**
+ * Subscribe to the owner-only portfolio SSE. Pushes a normalized `PnlSnapshot`
+ * on every server `snapshot` event, with reconnect-on-drop backoff. Returns a
+ * disposer that closes the stream and stops retrying. `onStatus` (optional) is
+ * notified with 'open' | 'reconnecting' | 'closed' for the HUD's live tick.
+ *
+ * The stream is owner-gated server-side; a non-owner / signed-out caller gets a
+ * 401 that surfaces as an error event → 'reconnecting' (and the HUD simply keeps
+ * polling balances). No fabricated data is ever emitted.
+ *
+ * @param {string} agentId
+ * @param {(snap: import('./pnl-snapshot.js').PnlSnapshot) => void} onSnapshot
+ * @param {{ network?: string, onStatus?: (s:string)=>void, onError?: (e:Error)=>void }} [opts]
+ * @returns {() => void} dispose
+ */
+export function subscribePortfolio(agentId, onSnapshot, opts = {}) {
+ const { network = 'mainnet', onStatus, onError } = opts;
+ const RECONNECT_DELAYS = [1000, 2000, 5000, 10000, 20000];
+ const url = `/api/agents/${encodeURIComponent(agentId)}/portfolio/stream${network === 'devnet' ? '?network=devnet' : ''}`;
+
+ let es = null;
+ let reconnectTimer = null;
+ let attempt = 0;
+ let destroyed = false;
+
+ function connect() {
+ if (destroyed || es) return;
+ try {
+ es = new EventSource(url, { withCredentials: true });
+ } catch (e) {
+ onError?.(e instanceof Error ? e : new Error('sse_unavailable'));
+ return;
+ }
+
+ es.addEventListener('open', () => { attempt = 0; onStatus?.('open'); });
+
+ es.addEventListener('snapshot', (e) => {
+ try {
+ const raw = JSON.parse(e.data);
+ onSnapshot?.(toPnlSnapshot(raw));
+ } catch { /* malformed frame — ignore, keep stream */ }
+ });
+
+ es.addEventListener('bye', () => { destroyed ? null : scheduleReconnect(); });
+
+ es.onerror = () => {
+ onStatus?.('reconnecting');
+ onError?.(new Error('portfolio_stream_disconnected'));
+ scheduleReconnect();
+ };
+ }
+
+ function scheduleReconnect() {
+ try { es?.close(); } catch { /* */ }
+ es = null;
+ if (destroyed) return;
+ const delay = RECONNECT_DELAYS[Math.min(attempt, RECONNECT_DELAYS.length - 1)];
+ attempt++;
+ clearTimeout(reconnectTimer);
+ reconnectTimer = setTimeout(connect, delay);
+ }
+
+ connect();
+
+ return function dispose() {
+ destroyed = true;
+ onStatus?.('closed');
+ clearTimeout(reconnectTimer);
+ try { es?.close(); } catch { /* */ }
+ es = null;
+ };
+}
diff --git a/src/shared/pnl-snapshot.js b/src/shared/pnl-snapshot.js
new file mode 100644
index 000000000..e3e5e4d79
--- /dev/null
+++ b/src/shared/pnl-snapshot.js
@@ -0,0 +1,361 @@
+// pnl-snapshot.js — pure normalizer for the live Portfolio / PnL HUD.
+//
+// The HUD (on /agent-screen) and the wall badge (on /agents-live) both read an
+// agent's live on-chain valuation from one of two real backends that return
+// DIFFERENT shapes:
+//
+// 1. POST /api/agents/balances — public, batched. Carries the 24h P&L +
+// sparkline derived from real wallet_value_snapshots, the SOL / $THREE
+// breakdown, and the top SPL holdings.
+// 2. GET /api/agents/:id/portfolio[/stream] — owner-only. Carries net worth,
+// per-holding cost basis + unrealized P&L, and risk — but no 24h sparkline.
+//
+// `toPnlSnapshot()` folds either shape into ONE canonical `PnlSnapshot` the UI
+// renders verbatim, so the HUD never branches on which endpoint answered. It is
+// pure (no DOM, no fetch, no time) so the $THREE-pinning rule and the percent
+// math are unit-tested directly in node (tests/pnl-snapshot.test.js).
+//
+// $THREE is the only coin this platform features. It is detected against the
+// canonical mint, pinned first with a featured marker, and linked to its 3D coin
+// page. Every other holding is neutral on-chain data — no promotion, no buy CTA.
+
+export const THREE_MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+
+/** Live 3D coin page for a mint (verified route: /coin3d?mint=<base58>). */
+export const THREE_COIN_URL = `/coin3d?mint=${THREE_MINT}`;
+
+function finite(v) {
+ const n = Number(v);
+ return Number.isFinite(n) ? n : null;
+}
+
+function isThreeMint(mint) {
+ return typeof mint === 'string' && mint === THREE_MINT;
+}
+
+/**
+ * @typedef {Object} PnlHolding
+ * @property {string|null} mint SPL mint, or null for native SOL.
+ * @property {string} symbol
+ * @property {number|null} valueUsd
+ * @property {number|null} valueSol
+ * @property {number|null} amount Token quantity held (UI units).
+ * @property {number|null} pct Share of net worth, 0–100.
+ * @property {number|null} unrealizedPct Owner-only per-holding P&L (else null).
+ * @property {string|null} logo
+ * @property {boolean} isThree True only for the canonical $THREE mint.
+ */
+
+/**
+ * @typedef {Object} PnlSnapshot
+ * @property {boolean} priced False when the wallet could not be valued.
+ * @property {'balances'|'portfolio'} source
+ * @property {string|null} address
+ * @property {boolean} isOwner
+ * @property {number|null} netWorthSol
+ * @property {number|null} netWorthUsd
+ * @property {number|null} change24hPct 24h % change (balances only; null otherwise).
+ * @property {number|null} change24hUsd
+ * @property {number|null} windowHours Real span the change covers.
+ * @property {number[]} sparkline Real USD value series (may be empty).
+ * @property {boolean} hasThree The agent holds $THREE.
+ * @property {PnlHolding[]} holdings $THREE pinned first, then by USD value desc.
+ * @property {number} holdingsTotal Count before any display truncation.
+ */
+
+/** A typed, empty (un-priced) snapshot — the honest "no value yet" state. */
+export function emptyPnlSnapshot(extra = {}) {
+ return {
+ priced: false,
+ source: 'balances',
+ address: null,
+ isOwner: false,
+ netWorthSol: null,
+ netWorthUsd: null,
+ change24hPct: null,
+ change24hUsd: null,
+ windowHours: null,
+ sparkline: [],
+ hasThree: false,
+ holdings: [],
+ holdingsTotal: 0,
+ ...extra,
+ };
+}
+
+// Order holdings: $THREE first (featured), then by USD value desc, nulls last.
+function rankHoldings(holdings) {
+ return holdings.slice().sort((a, b) => {
+ if (a.isThree !== b.isThree) return a.isThree ? -1 : 1;
+ return (b.valueUsd ?? -1) - (a.valueUsd ?? -1);
+ });
+}
+
+// Drop the bookkeeping zero-value rows that would only add noise, but always
+// keep $THREE (it's featured even at a dust balance) and any genuinely-held row.
+function meaningful(h) {
+ return h.isThree || (h.amount != null && h.amount > 0) || (h.valueUsd != null && h.valueUsd > 0);
+}
+
+// ── balances shape ────────────────────────────────────────────────────────────
+// { usd, sol:{amount,usd,price}, usdc:{amount,usd}, three:{amount,usd,price}|null,
+// tokenCount, topHoldings:[{mint,symbol,amount,usd,price,logo}],
+// pnl:{ sparkline:number[], changePct, changeUsd, windowHours } }
+function fromBalances(raw) {
+ const netWorthUsd = finite(raw.usd);
+ const solPrice = finite(raw.sol?.price);
+ const toSol = (usd) => (usd != null && solPrice && solPrice > 0 ? usd / solPrice : null);
+
+ const rows = [];
+ const seen = new Set();
+ const push = (h) => {
+ const key = h.mint || 'SOL';
+ if (seen.has(key)) return;
+ seen.add(key);
+ rows.push(h);
+ };
+
+ // Native SOL is a real holding the batched summary tracks separately.
+ const solUsd = finite(raw.sol?.usd);
+ if (raw.sol && (finite(raw.sol.amount) || solUsd)) {
+ push({
+ mint: null, symbol: 'SOL', amount: finite(raw.sol.amount),
+ valueUsd: solUsd, valueSol: finite(raw.sol.amount), unrealizedPct: null,
+ logo: null, isThree: false,
+ });
+ }
+ for (const t of Array.isArray(raw.topHoldings) ? raw.topHoldings : []) {
+ const usd = finite(t.usd);
+ push({
+ mint: t.mint || null, symbol: t.symbol || (t.mint ? String(t.mint).slice(0, 4) : '?'),
+ amount: finite(t.amount), valueUsd: usd, valueSol: toSol(usd), unrealizedPct: null,
+ logo: t.logo || null, isThree: isThreeMint(t.mint),
+ });
+ }
+ // Guarantee $THREE is present + featured even when it didn't rank into top
+ // holdings — the scoreboard always shows the platform coin when held.
+ const three = raw.three;
+ if (three && (finite(three.amount) || finite(three.usd)) && !seen.has(THREE_MINT)) {
+ const usd = finite(three.usd);
+ push({
+ mint: THREE_MINT, symbol: '$THREE', amount: finite(three.amount),
+ valueUsd: usd, valueSol: toSol(usd), unrealizedPct: null, logo: null, isThree: true,
+ });
+ }
+
+ const holdings = rankHoldings(rows.filter(meaningful)).map((h) => ({
+ ...h,
+ pct: h.valueUsd != null && netWorthUsd ? clampPct((h.valueUsd / netWorthUsd) * 100) : null,
+ }));
+
+ const pnl = raw.pnl || {};
+ return {
+ priced: netWorthUsd != null,
+ source: 'balances',
+ address: raw.address || null,
+ isOwner: !!raw.isOwner,
+ netWorthSol: toSol(netWorthUsd),
+ netWorthUsd,
+ change24hPct: finite(pnl.changePct),
+ change24hUsd: finite(pnl.changeUsd),
+ windowHours: finite(pnl.windowHours),
+ sparkline: (Array.isArray(pnl.sparkline) ? pnl.sparkline : []).map(Number).filter(Number.isFinite),
+ hasThree: holdings.some((h) => h.isThree),
+ holdings,
+ holdingsTotal: finite(raw.tokenCount) ?? holdings.length,
+ };
+}
+
+// ── portfolio shape (owner snapshot / SSE) ──────────────────────────────────────
+// { sol_usd, net_worth:{sol,usd,...}, holdings:[{mint,symbol,amount,usd,usd_value,
+// is_three,isNative,unrealized_pct,logo}] }
+function fromPortfolio(raw) {
+ const solUsd = finite(raw.sol_usd);
+ const netWorthUsd = finite(raw.net_worth?.usd);
+ const netWorthSol = finite(raw.net_worth?.sol);
+ const toSol = (usd) => (usd != null && solUsd && solUsd > 0 ? usd / solUsd : null);
+
+ const rows = (Array.isArray(raw.holdings) ? raw.holdings : []).map((h) => {
+ const usd = finite(h.usd_value) ?? finite(h.usd);
+ const native = !!h.isNative;
+ return {
+ mint: native ? null : (h.mint || null),
+ symbol: h.symbol || (native ? 'SOL' : h.mint ? String(h.mint).slice(0, 4) : '?'),
+ amount: finite(h.amount),
+ valueUsd: usd,
+ valueSol: native ? finite(h.amount) : toSol(usd),
+ unrealizedPct: finite(h.unrealized_pct),
+ logo: h.logo || null,
+ isThree: h.is_three === true || isThreeMint(h.mint),
+ };
+ });
+
+ const holdings = rankHoldings(rows.filter(meaningful)).map((h) => ({
+ ...h,
+ pct: h.valueUsd != null && netWorthUsd ? clampPct((h.valueUsd / netWorthUsd) * 100) : null,
+ }));
+
+ return {
+ priced: netWorthUsd != null,
+ source: 'portfolio',
+ address: raw.agent?.wallet || raw.address || null,
+ isOwner: true, // the portfolio endpoint is owner-gated by construction
+ netWorthSol,
+ netWorthUsd,
+ // The owner snapshot carries lifetime realized/unrealized, not a 24h
+ // window, and no sparkline — those stay null here and the HUD keeps the
+ // last balances-derived 24h + curve. Never synthesize a fake change.
+ change24hPct: null,
+ change24hUsd: null,
+ windowHours: null,
+ sparkline: [],
+ hasThree: holdings.some((h) => h.isThree),
+ holdings,
+ holdingsTotal: holdings.length,
+ };
+}
+
+function clampPct(p) {
+ if (!Number.isFinite(p)) return null;
+ return Math.max(0, Math.min(100, Number(p.toFixed(1))));
+}
+
+/**
+ * Normalize a raw balances entry OR a portfolio snapshot into a `PnlSnapshot`.
+ * Returns an empty (un-priced) snapshot for null / unusable input rather than
+ * throwing, so a list of mixed-availability wallets maps cleanly.
+ *
+ * @param {object|null} raw
+ * @returns {PnlSnapshot}
+ */
+export function toPnlSnapshot(raw) {
+ if (!raw || typeof raw !== 'object') return emptyPnlSnapshot();
+ // Portfolio shape is unambiguous (net_worth object); everything else is the
+ // balances summary, including the explicit { usd:null, priced:false } miss.
+ if (raw.net_worth && typeof raw.net_worth === 'object') return fromPortfolio(raw);
+ if (raw.usd == null && raw.priced === false) {
+ return emptyPnlSnapshot({ address: raw.address || null, isOwner: !!raw.isOwner });
+ }
+ return fromBalances(raw);
+}
+
+/**
+ * Merge a fresh owner portfolio snapshot onto the standing balances snapshot,
+ * keeping the real 24h change + sparkline (which the portfolio stream lacks)
+ * while taking the fresher net worth + per-holding cost basis. Pure.
+ *
+ * @param {PnlSnapshot} base last balances-derived snapshot (carries 24h+spark)
+ * @param {PnlSnapshot} live fresh portfolio snapshot
+ * @returns {PnlSnapshot}
+ */
+export function mergePortfolioOver(base, live) {
+ if (!base || !base.priced) return live;
+ if (!live || !live.priced) return base;
+ return {
+ ...live,
+ change24hPct: base.change24hPct,
+ change24hUsd: base.change24hUsd,
+ windowHours: base.windowHours,
+ sparkline: base.sparkline,
+ };
+}
+
+// ── formatters ──────────────────────────────────────────────────────────────
+
+/** Compact USD: cents under $1k, whole dollars to $1M, then $1.2M. */
+export function formatUsd(n, { compact = true } = {}) {
+ if (n == null || !Number.isFinite(Number(n))) return '—';
+ const v = Number(n);
+ const abs = Math.abs(v);
+ const sign = v < 0 ? '-' : '';
+ if (compact && abs >= 1_000_000) return `${sign}$${(abs / 1e6).toFixed(2)}M`;
+ if (compact && abs >= 10_000) return `${sign}$${(abs / 1e3).toFixed(1)}k`;
+ if (abs >= 1000) return `${sign}$${Math.round(abs).toLocaleString('en-US')}`;
+ if (abs >= 1) return `${sign}$${abs.toFixed(2)}`;
+ if (abs === 0) return '$0.00';
+ return `${sign}$${abs.toFixed(abs < 0.01 ? 4 : 3)}`;
+}
+
+/** SOL with trailing-zero trim. */
+export function formatSol(n, dp = 3) {
+ if (n == null || !Number.isFinite(Number(n))) return '—';
+ const s = Number(n).toFixed(dp).replace(/\.?0+$/, '');
+ return `${s || '0'} SOL`;
+}
+
+/** Compact token quantity: 412000 → "412K", 1.24e6 → "1.24M". */
+export function formatAmount(n) {
+ if (n == null || !Number.isFinite(Number(n))) return '—';
+ const v = Number(n);
+ const abs = Math.abs(v);
+ if (abs >= 1e9) return `${(v / 1e9).toFixed(2)}B`;
+ if (abs >= 1e6) return `${(v / 1e6).toFixed(2)}M`;
+ if (abs >= 1e3) return `${(v / 1e3).toFixed(abs >= 1e4 ? 0 : 1)}K`;
+ if (abs >= 1) return v.toLocaleString('en-US', { maximumFractionDigits: 2 });
+ return v.toPrecision(2);
+}
+
+/**
+ * Pure sparkline geometry from a real USD value series. Honest by construction:
+ * • 0 points → empty (the UI draws a flat "tracking starts now" baseline)
+ * • 1 point → single (a lone dot at the value, no misleading line)
+ * • N points → a normalized polyline, last-point marker, and min/max for ticks
+ * No DOM — returns plain coordinates so both the HUD canvas and tests consume it.
+ *
+ * @param {number[]} series
+ * @param {{ width?:number, height?:number, pad?:number }} [opts]
+ * @returns {{ empty:boolean, single:boolean, points:{x:number,y:number}[],
+ * polyline:string, min:number, max:number, last:{x:number,y:number}|null }}
+ */
+export function buildSparkline(series, { width = 220, height = 48, pad = 3 } = {}) {
+ const vals = (Array.isArray(series) ? series : []).map(Number).filter(Number.isFinite);
+ const base = { empty: vals.length === 0, single: vals.length === 1, points: [], polyline: '', min: 0, max: 0, last: null };
+ if (vals.length === 0) return base;
+
+ const min = Math.min(...vals);
+ const max = Math.max(...vals);
+ const span = max - min || 1;
+ const innerW = Math.max(1, width - pad * 2);
+ const innerH = Math.max(1, height - pad * 2);
+
+ if (vals.length === 1) {
+ const p = { x: width / 2, y: height / 2 };
+ return { ...base, min, max, points: [p], last: p };
+ }
+
+ const stepX = innerW / (vals.length - 1);
+ const points = vals.map((v, i) => ({
+ x: Number((pad + i * stepX).toFixed(2)),
+ // invert Y: higher value → higher on screen (smaller y)
+ y: Number((pad + innerH - ((v - min) / span) * innerH).toFixed(2)),
+ }));
+ return {
+ empty: false,
+ single: false,
+ points,
+ polyline: points.map((p) => `${p.x},${p.y}`).join(' '),
+ min,
+ max,
+ last: points[points.length - 1],
+ };
+}
+
+/**
+ * Format a signed percent into a label + a tone the UI colors by. A tiny dead
+ * band around zero reads as "flat" so feed jitter doesn't flicker green/red.
+ *
+ * @param {number|null} pct
+ * @returns {{ text:string, tone:'up'|'down'|'flat'|'none', arrow:string }}
+ */
+export function formatPnl(pct) {
+ if (pct == null || !Number.isFinite(Number(pct))) {
+ return { text: '—', tone: 'none', arrow: '' };
+ }
+ const v = Number(pct);
+ const tone = v > 0.05 ? 'up' : v < -0.05 ? 'down' : 'flat';
+ const sign = v > 0 ? '+' : v < 0 ? '−' : '';
+ const mag = Math.abs(v);
+ const digits = mag >= 100 ? 0 : mag >= 10 ? 1 : 2;
+ const arrow = tone === 'up' ? '▲' : tone === 'down' ? '▼' : '→';
+ return { text: `${sign}${mag.toFixed(digits)}%`, tone, arrow };
+}
diff --git a/src/shared/trade-pnl.js b/src/shared/trade-pnl.js
new file mode 100644
index 000000000..227f9099b
--- /dev/null
+++ b/src/shared/trade-pnl.js
@@ -0,0 +1,125 @@
+// trade-pnl.js — pure helpers for the Live Trading Desk PnL ticker + avatar emote.
+//
+// No DOM, no network, no time: the agent-screen UI imports these to fold real
+// trade frames into a running session total and to map an exit's sign onto an
+// avatar gesture. Kept pure so tests/agent-screen-pnl.test.js can exercise the
+// accumulator and emote mapping directly in node.
+//
+// A 'trade' frame may carry an optional `pnl` payload shaped by the sniper
+// executor:
+// { phase: 'scored'|'buy'|'hold'|'exit', mint, symbol, solDelta, pct,
+// realizedUsd, unrealizedUsd }
+// Only `exit` frames move the realized total; `hold` frames replace the live
+// unrealized mark for a single mint. Everything else is narration only.
+
+const PHASES = ['scored', 'buy', 'hold', 'exit'];
+
+function finite(v) {
+ // null / undefined / '' mean "absent" — not 0 (Number(null) === 0 would
+ // otherwise mask a missing solDelta and defeat the realizedUsd fallback).
+ if (v === null || v === undefined || v === '') return null;
+ const n = Number(v);
+ return Number.isFinite(n) ? n : null;
+}
+
+/**
+ * Normalize a raw `pnl` payload into a typed delta, or null when the frame
+ * carries no usable PnL signal. Trusts nothing: every number is coerced and
+ * NaN/∞ are dropped to null so a malformed push can never poison the ticker.
+ * @param {any} pnl
+ * @returns {{phase:string, mint:string|null, symbol:string|null, solDelta:number|null, pct:number|null, realizedUsd:number|null, unrealizedUsd:number|null}|null}
+ */
+export function parsePnlDelta(pnl) {
+ if (!pnl || typeof pnl !== 'object') return null;
+ if (!PHASES.includes(pnl.phase)) return null;
+ return {
+ phase: pnl.phase,
+ mint: typeof pnl.mint === 'string' ? pnl.mint : null,
+ symbol: typeof pnl.symbol === 'string' ? pnl.symbol : null,
+ solDelta: finite(pnl.solDelta),
+ pct: finite(pnl.pct),
+ realizedUsd: finite(pnl.realizedUsd),
+ unrealizedUsd: finite(pnl.unrealizedUsd),
+ };
+}
+
+/** A fresh, zeroed session accumulator. */
+export function emptyPnlState() {
+ return {
+ realizedUsd: 0,
+ realizedSol: 0,
+ unrealizedByMint: {}, // mint → live unrealized USD (last 'hold' mark)
+ trades: 0,
+ wins: 0,
+ losses: 0,
+ };
+}
+
+/**
+ * Fold a typed delta into the running session totals, returning a NEW state
+ * (never mutates the input). Only realized exits move the realized total and
+ * the win/loss tally; a 'hold' replaces that mint's unrealized mark; a closed
+ * position drops its unrealized mark so it isn't double-counted with realized.
+ * @param {object} state
+ * @param {ReturnType<typeof parsePnlDelta>} delta
+ */
+export function accumulatePnl(state, delta) {
+ const base = state || emptyPnlState();
+ const next = {
+ realizedUsd: base.realizedUsd || 0,
+ realizedSol: base.realizedSol || 0,
+ unrealizedByMint: { ...(base.unrealizedByMint || {}) },
+ trades: base.trades || 0,
+ wins: base.wins || 0,
+ losses: base.losses || 0,
+ };
+ if (!delta) return next;
+
+ if (delta.phase === 'exit') {
+ if (delta.realizedUsd != null) next.realizedUsd += delta.realizedUsd;
+ if (delta.solDelta != null) next.realizedSol += delta.solDelta;
+ if (delta.mint) delete next.unrealizedByMint[delta.mint];
+ next.trades += 1;
+ const sign = delta.solDelta != null ? delta.solDelta : delta.realizedUsd;
+ if (sign != null && sign > 0) next.wins += 1;
+ else if (sign != null && sign < 0) next.losses += 1;
+ } else if (delta.phase === 'hold' && delta.mint && delta.unrealizedUsd != null) {
+ next.unrealizedByMint[delta.mint] = delta.unrealizedUsd;
+ }
+ return next;
+}
+
+/** Sum of every open position's live unrealized USD mark. */
+export function unrealizedTotalUsd(state) {
+ const marks = state?.unrealizedByMint || {};
+ return Object.values(marks).reduce((sum, v) => sum + (Number(v) || 0), 0);
+}
+
+/**
+ * Map an exit's sign onto the avatar gesture. Wins celebrate, losses slump
+ * (the manifest's 'defeated' clip), breakeven and non-exit frames never emote.
+ * @param {ReturnType<typeof parsePnlDelta>} delta
+ * @returns {'celebrate'|'defeated'|null}
+ */
+export function emoteForExit(delta) {
+ if (!delta || delta.phase !== 'exit') return null;
+ const v = delta.solDelta != null ? delta.solDelta : delta.realizedUsd;
+ if (v == null || v === 0) return null;
+ return v > 0 ? 'celebrate' : 'defeated';
+}
+
+/** Format a signed SOL amount for the ticker, e.g. +0.0123 / -0.0045. */
+export function formatSol(sol) {
+ if (!Number.isFinite(sol)) return '—';
+ const sign = sol > 0 ? '+' : sol < 0 ? '−' : '';
+ return `${sign}${Math.abs(sol).toFixed(4)} SOL`;
+}
+
+/** Format a signed USD amount for the ticker, e.g. +$12.40 / -$3.05. */
+export function formatUsd(usd) {
+ if (!Number.isFinite(usd)) return null;
+ const sign = usd > 0 ? '+' : usd < 0 ? '−' : '';
+ const abs = Math.abs(usd);
+ const digits = abs >= 100 ? 0 : 2;
+ return `${sign}$${abs.toLocaleString(undefined, { minimumFractionDigits: digits, maximumFractionDigits: digits })}`;
+}
diff --git a/src/shared/world-clock.js b/src/shared/world-clock.js
new file mode 100644
index 000000000..133d9bd8e
--- /dev/null
+++ b/src/shared/world-clock.js
@@ -0,0 +1,55 @@
+// Deterministic world clock for the Ambient World DJ (Brief 22).
+//
+// The /agent-screen Ambient stage runs a living day/night cycle that EVERY viewer
+// of the same agent must see identically — two people watching the same screen
+// in different timezones should both agree it's dusk. So the time of day is a
+// pure function of wall-clock time and a configurable cycle length, with no
+// Math.random and no per-client state. Given the same `now` and `cycleMs` this
+// returns the same phase on every machine.
+//
+// Phase is a day fraction in [0, 1): 0 = midnight, 0.25 = sunrise, 0.5 = noon,
+// 0.75 = sunset — the exact convention src/game/day-night.js `setTime(t)` expects,
+// so the value drops straight into the existing sun/sky rig.
+
+// 8 real minutes per in-world day by default — long enough to feel calm, short
+// enough that a viewer leaving the channel open sees the sun actually move.
+export const DEFAULT_CYCLE_MS = 8 * 60 * 1000;
+
+// Map wall-clock ms → day fraction [0,1). `offset` (ms) shifts an individual
+// world's clock so two agents aren't locked to the same sky while each stays
+// perfectly deterministic. Guards a non-positive cycle so a bad config can't
+// divide by zero or NaN the sun.
+export function worldClock(now, cycleMs = DEFAULT_CYCLE_MS, offset = 0) {
+ const span = cycleMs > 0 ? cycleMs : DEFAULT_CYCLE_MS;
+ const t = (Number(now) || 0) + (Number(offset) || 0);
+ return (((t % span) + span) % span) / span;
+}
+
+// The four viewer-facing times of day, by phase band. Bands hug the sun arc:
+// sunrise straddles 0.25, dusk straddles 0.75, the long day sits between, and
+// everything past dusk before sunrise is night (the band wraps across 0/1).
+export function phaseLabel(phase) {
+ const p = (((Number(phase) || 0) % 1) + 1) % 1;
+ if (p >= 0.22 && p < 0.30) return 'sunrise';
+ if (p >= 0.30 && p < 0.70) return 'day';
+ if (p >= 0.70 && p < 0.80) return 'dusk';
+ return 'night';
+}
+
+// Golden hour — the warm window just before the sun touches the horizon. A
+// narrower band than `dusk` so the DJ can call it out as its own moment.
+export function isGoldenHour(phase) {
+ const p = (((Number(phase) || 0) % 1) + 1) % 1;
+ return p >= 0.66 && p < 0.74;
+}
+
+// 0 (deep night) … 1 (full day) — a smooth daylight amount from the sun's
+// altitude, matching the smoothstep day-night.js uses to raise the lights. Lets
+// callers cross-fade UI (the time-of-day readout, the ambient pad) with the sky
+// instead of snapping at band edges.
+export function daylightAmount(phase) {
+ const p = (((Number(phase) || 0) % 1) + 1) % 1;
+ const alt = Math.sin((p - 0.25) * Math.PI * 2); // -1 midnight … +1 noon
+ const t = Math.max(0, Math.min(1, (alt + 0.10) / 0.28));
+ return t * t * (3 - 2 * t);
+}
diff --git a/src/tour-commentary.js b/src/tour-commentary.js
new file mode 100644
index 000000000..16900abc0
--- /dev/null
+++ b/src/tour-commentary.js
@@ -0,0 +1,111 @@
+// tour-commentary.js — the pure brain of the Coin World Tour.
+//
+// A guide agent walks the $THREE 3D world (src/play/arena-world.js) and narrates
+// what's climbing three.ws's OWN launch feed as it moves between stops. This module
+// owns the two pure transforms that drive that narration, with ZERO DOM/Three.js/IO
+// so it runs identically in the browser bundle, the Playwright caster, and the unit
+// test (tests/tour-commentary.test.js):
+//
+// • normalizeLaunches() — turn the /api/pump/launches feed (coins launched
+// THROUGH three.ws, from the platform's own pump_agent_mints records) into
+// compact, location-agnostic { symbol, rank } items (top-N, cleaned).
+// • tourCommentary() — given the current waypoint + those items, produce the
+// spoken line + a badge label + the structured sidecar the overlay renders.
+//
+// Coin rule: $THREE is the only coin the tour PROMOTES. The data source here is
+// deliberately the platform's OWN launch directory (the blessed launch-records
+// exception — same source as the /launches feed and agent-profile launch history),
+// NOT a global third-party market/trending feed. Coins are described factually
+// (symbol + feed position) — never named as a buy, never recommended, never a
+// hardcoded non-$THREE mint.
+
+// Prefix stamped onto every tour SCREENSHOT frame's activity string. The render
+// surfaces (src/agent-screen.js, src/agents-live.js) detect a live tour by this
+// prefix and reveal the TOUR badge + waypoint label. The caster builds it from
+// `badge` below, so this is the single source of truth for both sides.
+export const TOUR_PREFIX = 'Tour · ';
+
+// The fixed walking loop. `name` is the deterministic key the 3D scene + caster
+// drive (window.__tour.goTo(name)); `label` is the human waypoint title shown on
+// the badge; `where` buckets the stop into a commentary register (the open lobby
+// vs. deep in the arena) so the narration reads differently as the guide moves in.
+export const TOUR_WAYPOINTS = [
+ { name: 'lobby', label: 'Entering the lobby', where: 'lobby' },
+ { name: 'approach', label: 'Crossing the floor', where: 'lobby' },
+ { name: 'arena', label: 'Into the arena', where: 'arena' },
+ { name: 'leader', label: 'At the leader’s pad', where: 'arena' },
+ { name: 'eastwing', label: 'Along the east ring', where: 'arena' },
+];
+
+// Longest symbol we'll speak before truncating — keeps the overlay + log tidy and
+// stops a pathological 40-char "symbol" from blowing out a commentary line.
+const SYMBOL_MAX = 12;
+// How many trending coins a single commentary line mentions. The feed can return
+// hundreds; a guide names the top few, never a wall of tickers.
+const DEFAULT_LIMIT = 3;
+
+export function waypointByName(name) {
+ return TOUR_WAYPOINTS.find((w) => w.name === name) || null;
+}
+
+// Normalize one ticker into a single leading-`$`, length-bounded symbol. Accepts
+// feeds that already include `$` and ones that don't, and survives junk/empties.
+function cleanSymbol(raw) {
+ let s = String(raw == null ? '' : raw).trim();
+ s = s.replace(/^\$+/, ''); // collapse any existing $ prefixes
+ s = s.replace(/\s+/g, ''); // tickers never carry spaces
+ if (!s) return '';
+ if (s.length > SYMBOL_MAX) s = s.slice(0, SYMBOL_MAX - 1) + '…';
+ return `$${s}`;
+}
+
+// Raw /api/pump/trending feed → compact, ordered commentary items. Each item is
+// just { symbol, rank } — the minimum the narration needs, never a mint (coin
+// addresses are deliberately not spoken or rendered). Missing ranks fall back to
+// feed position so the order is always meaningful.
+export function normalizeTrending(trending, { limit = DEFAULT_LIMIT } = {}) {
+ if (!Array.isArray(trending)) return [];
+ const out = [];
+ for (let i = 0; i < trending.length; i++) {
+ const t = trending[i] || {};
+ const symbol = cleanSymbol(t.symbol);
+ if (!symbol || symbol === '$') continue;
+ const rank = Number.isFinite(t.rank) && t.rank > 0 ? Math.floor(t.rank) : out.length + 1;
+ out.push({ symbol, rank });
+ if (out.length >= limit) break;
+ }
+ return out;
+}
+
+// "$ABC (#1), $DEF (#2) and $GHI (#3)" — a readable, factual enumeration.
+function listPhrase(items) {
+ const parts = items.map((it) => `${it.symbol} (#${it.rank})`);
+ if (parts.length === 1) return parts[0];
+ return `${parts.slice(0, -1).join(', ')} and ${parts[parts.length - 1]}`;
+}
+
+// The heart of the tour. Given the waypoint the guide just reached and the live
+// trending feed, return everything the surfaces need:
+// { name, where, label, badge, line, items }
+// `line` is the spoken/logged commentary (type:'analysis'); `badge` is the
+// screenshot frame's activity stamp; `items` backs the overlay's trending list.
+export function tourCommentary(waypointName, trending, { limit = DEFAULT_LIMIT } = {}) {
+ const wp = waypointByName(waypointName) || TOUR_WAYPOINTS[0];
+ const items = normalizeTrending(trending, { limit });
+ const label = wp.label;
+ const badge = `${TOUR_PREFIX}${label}`;
+
+ let line;
+ if (!items.length) {
+ // Feed empty or down — the tour never goes silent; it narrates the world.
+ line = wp.where === 'arena'
+ ? `${label}. The feed’s quiet right now — just the arena and the lights.`
+ : `${label}. Nothing climbing the launch feed yet — come walk the world.`;
+ } else if (wp.where === 'arena') {
+ line = `${label}. Climbing the launch feed right now: ${listPhrase(items)}.`;
+ } else {
+ line = `${label}. Trending as we walk in: ${listPhrase(items)}.`;
+ }
+
+ return { name: wp.name, where: wp.where, label, badge, line, items };
+}
diff --git a/tests/agent-screen-pnl.test.js b/tests/agent-screen-pnl.test.js
new file mode 100644
index 000000000..809c94dd0
--- /dev/null
+++ b/tests/agent-screen-pnl.test.js
@@ -0,0 +1,138 @@
+// Live Trading Desk — unit tests for the pure PnL accumulator + emote mapping.
+//
+// These cover the only logic the viewer's ticker depends on: folding real trade
+// frames into a running session total, and mapping an exit's sign onto the
+// avatar gesture. No DOM, no network — just the pure helpers.
+
+import { describe, it, expect } from 'vitest';
+import {
+ parsePnlDelta,
+ accumulatePnl,
+ emptyPnlState,
+ unrealizedTotalUsd,
+ emoteForExit,
+ formatSol,
+ formatUsd,
+} from '../src/shared/trade-pnl.js';
+
+describe('parsePnlDelta', () => {
+ it('rejects non-objects and unknown phases', () => {
+ expect(parsePnlDelta(null)).toBe(null);
+ expect(parsePnlDelta(42)).toBe(null);
+ expect(parsePnlDelta({})).toBe(null);
+ expect(parsePnlDelta({ phase: 'nope' })).toBe(null);
+ });
+
+ it('coerces numbers and drops non-finite values to null', () => {
+ const d = parsePnlDelta({ phase: 'exit', mint: 'm', symbol: 'X', solDelta: '0.5', pct: 'NaN', realizedUsd: Infinity });
+ expect(d).toEqual({ phase: 'exit', mint: 'm', symbol: 'X', solDelta: 0.5, pct: null, realizedUsd: null, unrealizedUsd: null });
+ });
+
+ it('keeps only string mint/symbol', () => {
+ const d = parsePnlDelta({ phase: 'buy', mint: 123, symbol: { x: 1 } });
+ expect(d.mint).toBe(null);
+ expect(d.symbol).toBe(null);
+ });
+});
+
+describe('accumulatePnl', () => {
+ it('starts from an empty state and adds a realized win', () => {
+ const s = accumulatePnl(emptyPnlState(), parsePnlDelta({ phase: 'exit', mint: 'a', solDelta: 0.02, realizedUsd: 4 }));
+ expect(s.realizedSol).toBeCloseTo(0.02, 9);
+ expect(s.realizedUsd).toBeCloseTo(4, 9);
+ expect(s.trades).toBe(1);
+ expect(s.wins).toBe(1);
+ expect(s.losses).toBe(0);
+ });
+
+ it('tallies a realized loss', () => {
+ const s = accumulatePnl(emptyPnlState(), parsePnlDelta({ phase: 'exit', mint: 'a', solDelta: -0.01, realizedUsd: -2 }));
+ expect(s.realizedSol).toBeCloseTo(-0.01, 9);
+ expect(s.wins).toBe(0);
+ expect(s.losses).toBe(1);
+ });
+
+ it('breakeven exits count as a trade but neither win nor loss', () => {
+ const s = accumulatePnl(emptyPnlState(), parsePnlDelta({ phase: 'exit', mint: 'a', solDelta: 0 }));
+ expect(s.trades).toBe(1);
+ expect(s.wins).toBe(0);
+ expect(s.losses).toBe(0);
+ });
+
+ it('sums multiple exits across a session', () => {
+ let s = emptyPnlState();
+ s = accumulatePnl(s, parsePnlDelta({ phase: 'exit', mint: 'a', solDelta: 0.02, realizedUsd: 4 }));
+ s = accumulatePnl(s, parsePnlDelta({ phase: 'exit', mint: 'b', solDelta: -0.005, realizedUsd: -1 }));
+ s = accumulatePnl(s, parsePnlDelta({ phase: 'exit', mint: 'c', solDelta: 0.01, realizedUsd: 2 }));
+ expect(s.realizedSol).toBeCloseTo(0.025, 9);
+ expect(s.realizedUsd).toBeCloseTo(5, 9);
+ expect(s.trades).toBe(3);
+ expect(s.wins).toBe(2);
+ expect(s.losses).toBe(1);
+ });
+
+ it('hold frames replace a mint unrealized mark; exit clears it', () => {
+ let s = emptyPnlState();
+ s = accumulatePnl(s, parsePnlDelta({ phase: 'hold', mint: 'a', unrealizedUsd: 3 }));
+ expect(unrealizedTotalUsd(s)).toBeCloseTo(3, 9);
+ s = accumulatePnl(s, parsePnlDelta({ phase: 'hold', mint: 'a', unrealizedUsd: 7 })); // replace, not add
+ expect(unrealizedTotalUsd(s)).toBeCloseTo(7, 9);
+ s = accumulatePnl(s, parsePnlDelta({ phase: 'hold', mint: 'b', unrealizedUsd: 2 }));
+ expect(unrealizedTotalUsd(s)).toBeCloseTo(9, 9);
+ s = accumulatePnl(s, parsePnlDelta({ phase: 'exit', mint: 'a', solDelta: 0.01, realizedUsd: 5 }));
+ expect(unrealizedTotalUsd(s)).toBeCloseTo(2, 9); // a's mark cleared, b's remains
+ });
+
+ it('does not mutate the previous state', () => {
+ const prev = emptyPnlState();
+ const next = accumulatePnl(prev, parsePnlDelta({ phase: 'exit', mint: 'a', solDelta: 0.02, realizedUsd: 4 }));
+ expect(prev.realizedSol).toBe(0);
+ expect(prev.trades).toBe(0);
+ expect(next).not.toBe(prev);
+ });
+
+ it('ignores a null delta (no-op fold)', () => {
+ const s = accumulatePnl(emptyPnlState(), null);
+ expect(s).toEqual(emptyPnlState());
+ });
+});
+
+describe('emoteForExit', () => {
+ it('celebrates a profitable exit', () => {
+ expect(emoteForExit(parsePnlDelta({ phase: 'exit', solDelta: 0.02 }))).toBe('celebrate');
+ expect(emoteForExit(parsePnlDelta({ phase: 'exit', solDelta: null, realizedUsd: 5 }))).toBe('celebrate');
+ });
+
+ it('slumps on a losing exit', () => {
+ expect(emoteForExit(parsePnlDelta({ phase: 'exit', solDelta: -0.01 }))).toBe('defeated');
+ expect(emoteForExit(parsePnlDelta({ phase: 'exit', solDelta: null, realizedUsd: -3 }))).toBe('defeated');
+ });
+
+ it('does not emote on breakeven, non-exits, or null', () => {
+ expect(emoteForExit(parsePnlDelta({ phase: 'exit', solDelta: 0 }))).toBe(null);
+ expect(emoteForExit(parsePnlDelta({ phase: 'buy', solDelta: -0.05 }))).toBe(null);
+ expect(emoteForExit(parsePnlDelta({ phase: 'scored' }))).toBe(null);
+ expect(emoteForExit(null)).toBe(null);
+ });
+
+ it('prefers solDelta over realizedUsd for the sign', () => {
+ // solDelta positive wins even if a stale USD value disagrees
+ expect(emoteForExit(parsePnlDelta({ phase: 'exit', solDelta: 0.01, realizedUsd: -100 }))).toBe('celebrate');
+ });
+});
+
+describe('formatters', () => {
+ it('formats signed SOL with a minus glyph and 4 decimals', () => {
+ expect(formatSol(0.0123)).toBe('+0.0123 SOL');
+ expect(formatSol(-0.0045)).toBe('−0.0045 SOL');
+ expect(formatSol(0)).toBe('0.0000 SOL');
+ expect(formatSol(Infinity)).toBe('—');
+ });
+
+ it('formats signed USD and drops cents above $100', () => {
+ expect(formatUsd(12.4)).toBe('+$12.40');
+ expect(formatUsd(-3.05)).toBe('−$3.05');
+ expect(formatUsd(250)).toBe('+$250');
+ expect(formatUsd(NaN)).toBe(null);
+ });
+});
diff --git a/tests/agent-screen-runcmd.test.js b/tests/agent-screen-runcmd.test.js
new file mode 100644
index 000000000..89c17f00e
--- /dev/null
+++ b/tests/agent-screen-runcmd.test.js
@@ -0,0 +1,117 @@
+/**
+ * Deploy-to-wall run-command builder — unit tests.
+ *
+ * The wizard hands an owner the exact command to start their caster. These tests
+ * pin the contract the wizard depends on: the right agentId/key/env are
+ * interpolated for every runtime, the command is built from REAL values (no
+ * leftover <AGENT_ID>/<AGENT_JWT> placeholders the user must guess), the push
+ * URL tracks the viewer's origin, and the highlighted display never drifts from
+ * the copyable raw command.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ buildRunCommand,
+ buildRunCommandHtml,
+ runtimeEnv,
+ RUNTIMES,
+ RUNTIME_LABELS,
+ PUSH_PATH,
+ IMAGE_TAG,
+} from '../src/agent-screen-runcmd.js';
+
+const REAL = {
+ agentId: '11111111-2222-3333-4444-555555555555',
+ agentJwt: 'sk_live_realmintedkeyvalue_abc123',
+ origin: 'https://three.ws',
+};
+
+describe('runtimeEnv', () => {
+ it('always includes AGENT_ID, AGENT_JWT and the origin-joined PUSH_URL', () => {
+ const env = Object.fromEntries(runtimeEnv({ runtime: 'local', ...REAL }));
+ expect(env.AGENT_ID).toBe(REAL.agentId);
+ expect(env.AGENT_JWT).toBe(REAL.agentJwt);
+ expect(env.PUSH_URL).toBe(`${REAL.origin}${PUSH_PATH}`);
+ });
+
+ it('adds Browserbase creds only for the bb runtime', () => {
+ expect(runtimeEnv({ runtime: 'local', ...REAL }).map((e) => e[0])).not.toContain('BROWSERBASE_API_KEY');
+ const bb = runtimeEnv({ runtime: 'bb', ...REAL }).map((e) => e[0]);
+ expect(bb).toContain('BROWSERBASE_API_KEY');
+ expect(bb).toContain('BROWSERBASE_PROJECT_ID');
+ });
+
+ it('joins PUSH_URL onto a non-prod origin (preview/staging hosts)', () => {
+ const env = Object.fromEntries(runtimeEnv({ runtime: 'local', ...REAL, origin: 'http://localhost:3000' }));
+ expect(env.PUSH_URL).toBe('http://localhost:3000/api/agent-screen-push');
+ });
+});
+
+describe('buildRunCommand', () => {
+ it('local runtime inlines the real agentId, key and push url before npm start', () => {
+ const cmd = buildRunCommand({ runtime: 'local', ...REAL });
+ expect(cmd).toBe(
+ `AGENT_ID=${REAL.agentId} AGENT_JWT=${REAL.agentJwt} PUSH_URL=${REAL.origin}${PUSH_PATH} npm start`,
+ );
+ });
+
+ it('docker runtime builds the image then runs it with -e flags', () => {
+ const cmd = buildRunCommand({ runtime: 'docker', ...REAL });
+ expect(cmd).toContain(`docker build -t ${IMAGE_TAG} .`);
+ expect(cmd).toContain(`-e AGENT_ID=${REAL.agentId}`);
+ expect(cmd).toContain(`-e AGENT_JWT=${REAL.agentJwt}`);
+ expect(cmd).toContain(`-e PUSH_URL=${REAL.origin}${PUSH_PATH}`);
+ expect(cmd.trim().endsWith(IMAGE_TAG)).toBe(true);
+ });
+
+ it('bb runtime carries the Browserbase creds and runs npm start', () => {
+ const cmd = buildRunCommand({ runtime: 'bb', ...REAL });
+ expect(cmd).toContain('BROWSERBASE_API_KEY=');
+ expect(cmd).toContain('BROWSERBASE_PROJECT_ID=');
+ expect(cmd.endsWith('npm start')).toBe(true);
+ });
+
+ it('unknown runtime falls back to local rather than producing garbage', () => {
+ expect(buildRunCommand({ runtime: 'nonsense', ...REAL })).toBe(buildRunCommand({ runtime: 'local', ...REAL }));
+ });
+
+ it('leaves no three.ws-side placeholder once a real agent + key are supplied', () => {
+ for (const runtime of RUNTIMES) {
+ const cmd = buildRunCommand({ runtime, ...REAL });
+ expect(cmd).not.toContain('<AGENT_ID>');
+ expect(cmd).not.toContain('<AGENT_JWT>');
+ expect(cmd).not.toContain('<PUSH_URL>');
+ }
+ });
+
+ it('local and docker carry no angle-bracket placeholders at all', () => {
+ for (const runtime of ['local', 'docker']) {
+ expect(buildRunCommand({ runtime, ...REAL })).not.toMatch(/<[^>]+>/);
+ }
+ });
+});
+
+describe('buildRunCommandHtml', () => {
+ it('renders the same real values as the raw command for every runtime', () => {
+ for (const runtime of RUNTIMES) {
+ const html = buildRunCommandHtml({ runtime, ...REAL });
+ expect(html).toContain(REAL.agentId);
+ expect(html).toContain(REAL.agentJwt);
+ expect(html).toContain('agent-screen-push');
+ // highlighted, not raw text
+ expect(html).toContain('cmd-key');
+ }
+ });
+
+ it('HTML-escapes the Browserbase placeholder angle brackets', () => {
+ const html = buildRunCommandHtml({ runtime: 'bb', ...REAL });
+ expect(html).toContain('&lt;your-bb-key&gt;');
+ expect(html).not.toContain('<your-bb-key>');
+ });
+});
+
+describe('runtime metadata', () => {
+ it('exposes a label for every runtime', () => {
+ for (const runtime of RUNTIMES) expect(RUNTIME_LABELS[runtime]).toBeTruthy();
+ });
+});
diff --git a/tests/forge-frame.test.js b/tests/forge-frame.test.js
new file mode 100644
index 000000000..ebc6a7e15
--- /dev/null
+++ b/tests/forge-frame.test.js
@@ -0,0 +1,165 @@
+/**
+ * Live Avatar Forge — pure frame/narration logic.
+ *
+ * Covers the stage→narration mapping, the prompt clamp to the TRELLIS
+ * conditioning window, and the final-frame sidecar round-trip (build → parse)
+ * that carries the generated GLB url from the forge driver to every viewer.
+ * No network, no DOM — the real /api/forge call and GLB load live in callers.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ clampPrompt,
+ validatePrompt,
+ forgeStageNarration,
+ buildForgeFrame,
+ finalForgeFrame,
+ parseForgeFrame,
+ viewerLinkFor,
+ sanitizeFrameMeta,
+ TRELLIS_PROMPT_LIMIT,
+} from '../src/shared/forge-frames.js';
+
+describe('clampPrompt', () => {
+ it('passes a short prompt through untouched', () => {
+ const r = clampPrompt('a glossy white robot mascot');
+ expect(r.trimmed).toBe(false);
+ expect(r.prompt).toBe('a glossy white robot mascot');
+ });
+
+ it('collapses whitespace and trims', () => {
+ const r = clampPrompt(' a round\n robot ');
+ expect(r.prompt).toBe('a round robot');
+ expect(r.trimmed).toBe(false);
+ });
+
+ it('trims an over-long prompt to the conditioning window on a word boundary', () => {
+ const long = 'a friendly round robot mascot, glossy white plastic, big expressive blue eyes and tiny antennae';
+ const r = clampPrompt(long);
+ expect(r.trimmed).toBe(true);
+ expect(r.prompt.length).toBeLessThanOrEqual(TRELLIS_PROMPT_LIMIT);
+ // word boundary — no trailing partial word / space
+ expect(r.prompt).not.toMatch(/\s$/);
+ expect(long.startsWith(r.prompt)).toBe(true);
+ expect(r.originalLength).toBe(long.length);
+ });
+
+ it('handles null / undefined safely', () => {
+ expect(clampPrompt(null).prompt).toBe('');
+ expect(clampPrompt(undefined).prompt).toBe('');
+ });
+});
+
+describe('validatePrompt', () => {
+ it('rejects too-short prompts', () => {
+ expect(validatePrompt('ab').ok).toBe(false);
+ expect(validatePrompt(' ').ok).toBe(false);
+ });
+ it('accepts a real prompt', () => {
+ expect(validatePrompt('a red apple').ok).toBe(true);
+ });
+});
+
+describe('forgeStageNarration', () => {
+ it('narrates each real pipeline state distinctly', () => {
+ const submitting = forgeStageNarration({ status: 'submitting' });
+ const queued = forgeStageNarration({ status: 'queued', eta_seconds: 20 });
+ const running = forgeStageNarration({ status: 'running' });
+ const done = forgeStageNarration({ status: 'done' });
+ const failed = forgeStageNarration({ status: 'failed' });
+ for (const v of [submitting, queued, running, done, failed]) {
+ expect(typeof v).toBe('string');
+ expect(v.length).toBeGreaterThan(0);
+ }
+ expect(new Set([submitting, queued, running, done, failed]).size).toBe(5);
+ });
+
+ it('includes the ETA when the pipeline reports one', () => {
+ expect(forgeStageNarration({ status: 'queued', eta_seconds: 18 })).toContain('18s');
+ expect(forgeStageNarration({ status: 'queued' })).not.toContain('~');
+ });
+
+ it('falls back to a neutral line for unknown states', () => {
+ expect(forgeStageNarration({ status: 'weird' })).toMatch(/forging/i);
+ expect(forgeStageNarration({})).toMatch(/forging/i);
+ });
+});
+
+describe('buildForgeFrame', () => {
+ it('defaults to the analysis lane and omits empty meta', () => {
+ const f = buildForgeFrame({ activity: 'hi' });
+ expect(f).toEqual({ activity: 'hi', type: 'analysis' });
+ });
+ it('attaches meta when provided', () => {
+ const f = buildForgeFrame({ activity: 'hi', meta: { kind: 'forge' } });
+ expect(f.meta).toEqual({ kind: 'forge' });
+ });
+});
+
+describe('finalForgeFrame ↔ parseForgeFrame round-trip', () => {
+ it('packs the GLB url + viewer link into the sidecar and reads it back', () => {
+ const frame = finalForgeFrame({
+ prompt: 'a glossy white robot mascot',
+ glbUrl: 'https://cdn.three.ws/forge/abc.glb',
+ viewerUrl: 'https://three.ws/viewer?src=x',
+ tier: 'draft',
+ backend: 'nvidia',
+ durable: true,
+ });
+ expect(frame.type).toBe('analysis');
+ expect(frame.meta.kind).toBe('forge');
+
+ const parsed = parseForgeFrame(frame);
+ expect(parsed).not.toBeNull();
+ expect(parsed.glbUrl).toBe('https://cdn.three.ws/forge/abc.glb');
+ expect(parsed.viewerUrl).toBe('https://three.ws/viewer?src=x');
+ expect(parsed.prompt).toBe('a glossy white robot mascot');
+ expect(parsed.tier).toBe('draft');
+ expect(parsed.backend).toBe('nvidia');
+ expect(parsed.durable).toBe(true);
+ });
+
+ it('returns null for non-forge frames', () => {
+ expect(parseForgeFrame({ activity: 'x', type: 'trade' })).toBeNull();
+ expect(parseForgeFrame({ activity: 'x', meta: { kind: 'other' } })).toBeNull();
+ expect(parseForgeFrame(null)).toBeNull();
+ });
+
+ it('rejects a sidecar whose GLB url is not http(s)', () => {
+ const bad = { meta: { kind: 'forge', glbUrl: 'javascript:alert(1)', viewerUrl: '', prompt: 'x' } };
+ expect(parseForgeFrame(bad)).toBeNull();
+ });
+});
+
+describe('viewerLinkFor', () => {
+ it('builds an encoded viewer link from an origin', () => {
+ expect(viewerLinkFor('https://cdn/x y.glb', 'https://three.ws/')).toBe(
+ 'https://three.ws/viewer?src=https%3A%2F%2Fcdn%2Fx%20y.glb',
+ );
+ });
+});
+
+describe('sanitizeFrameMeta', () => {
+ it('keeps a valid forge sidecar and caps lengths', () => {
+ const out = sanitizeFrameMeta({
+ kind: 'forge',
+ glbUrl: 'https://cdn.three.ws/a.glb',
+ viewerUrl: 'https://three.ws/viewer?src=a',
+ prompt: 'x'.repeat(1000),
+ tier: 'draft',
+ backend: 'nvidia',
+ durable: false,
+ injected: 'should be dropped',
+ });
+ expect(out.glbUrl).toBe('https://cdn.three.ws/a.glb');
+ expect(out.prompt.length).toBe(320);
+ expect(out.tier).toBe('draft');
+ expect('injected' in out).toBe(false);
+ });
+
+ it('returns null for non-forge or url-less meta', () => {
+ expect(sanitizeFrameMeta(null)).toBeNull();
+ expect(sanitizeFrameMeta({ kind: 'other' })).toBeNull();
+ expect(sanitizeFrameMeta({ kind: 'forge', glbUrl: 'not-a-url' })).toBeNull();
+ });
+});
diff --git a/tests/tour-commentary.test.js b/tests/tour-commentary.test.js
new file mode 100644
index 000000000..d356ee0a7
--- /dev/null
+++ b/tests/tour-commentary.test.js
@@ -0,0 +1,128 @@
+/**
+ * Coin World Tour — pure trending→commentary mapping (src/tour-commentary.js).
+ *
+ * The guide agent's narration is generated entirely by these pure functions, so
+ * pinning them here guarantees the tour speaks correctly at every stop and across
+ * every feed shape (empty, one coin, overflow, junk symbols) without spinning up
+ * a browser. The render surfaces + the Playwright caster import the same module,
+ * so this is the contract for all three.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ TOUR_PREFIX,
+ TOUR_WAYPOINTS,
+ waypointByName,
+ normalizeTrending,
+ tourCommentary,
+} from '../src/tour-commentary.js';
+
+const FEED = [
+ { symbol: 'ALPHA', rank: 1, mint: 'AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA' },
+ { symbol: '$BETA', rank: 2, mint: 'BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBB' },
+ { symbol: 'GAMMA', rank: 3, mint: 'CCCCCCCCCCCCCCCCCCCCCCCCCCCCCCCC' },
+ { symbol: 'DELTA', rank: 4, mint: 'DDDDDDDDDDDDDDDDDDDDDDDDDDDDDDDD' },
+];
+
+describe('normalizeTrending', () => {
+ it('takes the top-N, defaults to 3', () => {
+ const items = normalizeTrending(FEED);
+ expect(items).toHaveLength(3);
+ expect(items.map((i) => i.symbol)).toEqual(['$ALPHA', '$BETA', '$GAMMA']);
+ expect(items.map((i) => i.rank)).toEqual([1, 2, 3]);
+ });
+
+ it('respects an explicit limit', () => {
+ expect(normalizeTrending(FEED, { limit: 1 })).toHaveLength(1);
+ expect(normalizeTrending(FEED, { limit: 10 })).toHaveLength(4);
+ });
+
+ it('normalizes symbols to a single leading $ and never carries a mint', () => {
+ const [a, b] = normalizeTrending(FEED, { limit: 2 });
+ expect(a.symbol).toBe('$ALPHA'); // bare symbol gains a $
+ expect(b.symbol).toBe('$BETA'); // pre-$'d symbol is not doubled
+ expect(a).not.toHaveProperty('mint');
+ });
+
+ it('truncates a pathologically long symbol', () => {
+ const [it0] = normalizeTrending([{ symbol: 'SUPERCALIFRAGILISTIC', rank: 1 }]);
+ expect(it0.symbol.length).toBeLessThanOrEqual(13); // $ + 12 chars incl. ellipsis
+ expect(it0.symbol.endsWith('…')).toBe(true);
+ });
+
+ it('falls back to feed position when rank is missing/invalid', () => {
+ const items = normalizeTrending([
+ { symbol: 'NORANK' },
+ { symbol: 'BADRANK', rank: -5 },
+ ]);
+ expect(items.map((i) => i.rank)).toEqual([1, 2]);
+ });
+
+ it('drops empty/junk entries and tolerates non-arrays', () => {
+ expect(normalizeTrending([{ symbol: '' }, { symbol: '$' }, {}])).toEqual([]);
+ expect(normalizeTrending(null)).toEqual([]);
+ expect(normalizeTrending(undefined)).toEqual([]);
+ });
+});
+
+describe('tourCommentary', () => {
+ it('stamps the badge with the shared prefix + waypoint label', () => {
+ const c = tourCommentary('arena', FEED);
+ expect(c.badge).toBe(`${TOUR_PREFIX}Into the arena`);
+ expect(c.label).toBe('Into the arena');
+ expect(c.where).toBe('arena');
+ expect(c.name).toBe('arena');
+ });
+
+ it('enumerates trending coins factually with rank, for an arena stop', () => {
+ const c = tourCommentary('arena', FEED.slice(0, 2));
+ expect(c.line).toContain('$ALPHA (#1)');
+ expect(c.line).toContain('$BETA (#2)');
+ expect(c.line).toContain('launch feed');
+ expect(c.items).toHaveLength(2);
+ });
+
+ it('uses the walk-in register for a lobby stop', () => {
+ const c = tourCommentary('lobby', FEED.slice(0, 1));
+ expect(c.where).toBe('lobby');
+ expect(c.line).toContain('Trending as we walk in');
+ expect(c.line).toContain('$ALPHA (#1)');
+ });
+
+ it('never goes silent when the feed is empty', () => {
+ const arena = tourCommentary('arena', []);
+ const lobby = tourCommentary('lobby', []);
+ expect(arena.items).toEqual([]);
+ expect(arena.line).toMatch(/arena|feed’s quiet/i);
+ expect(lobby.line).toMatch(/launch feed|walk the world/i);
+ // A factual, non-promotional fallback — no "buy", no recommendation.
+ expect(arena.line.toLowerCase()).not.toContain('buy');
+ });
+
+ it('falls back to the first waypoint on an unknown name', () => {
+ const c = tourCommentary('does-not-exist', FEED);
+ expect(c.name).toBe(TOUR_WAYPOINTS[0].name);
+ });
+
+ it('joins multiple coins readably', () => {
+ const c = tourCommentary('arena', FEED, { limit: 3 });
+ expect(c.line).toContain('$ALPHA (#1), $BETA (#2) and $GAMMA (#3)');
+ });
+});
+
+describe('waypoint table', () => {
+ it('exposes a stable, non-empty loop with lobby first', () => {
+ expect(TOUR_WAYPOINTS.length).toBeGreaterThanOrEqual(3);
+ expect(TOUR_WAYPOINTS[0].name).toBe('lobby');
+ for (const w of TOUR_WAYPOINTS) {
+ expect(w.name).toBeTruthy();
+ expect(w.label).toBeTruthy();
+ expect(['lobby', 'arena']).toContain(w.where);
+ }
+ });
+
+ it('waypointByName resolves known stops and rejects unknowns', () => {
+ expect(waypointByName('arena')?.label).toBe('Into the arena');
+ expect(waypointByName('nope')).toBeNull();
+ });
+});
diff --git a/tests/vanity-grinder-progress.test.js b/tests/vanity-grinder-progress.test.js
new file mode 100644
index 000000000..4430f52d2
--- /dev/null
+++ b/tests/vanity-grinder-progress.test.js
@@ -0,0 +1,78 @@
+import { describe, it, expect } from 'vitest';
+import { grindMintKeypair } from '../api/_lib/pump-vanity.js';
+import { computeGrindStats } from '../api/_lib/vanity-grind-stats.js';
+
+// The live Vanity Address Miner (feature #11) streams real grind numbers to the
+// agent screen. These tests pin the contract the on-screen frame depends on:
+// onProgress fires with monotonic iterations and a positive instantaneous rate,
+// and the attempts/sec stat derives purely from those real numbers.
+
+describe('grindMintKeypair onProgress', () => {
+ it('fires progress samples with monotonic iterations and a positive rate', async () => {
+ const samples = [];
+ // A 3-char suffix is too hard to hit inside the tiny iteration budget, so
+ // the grind exhausts maxIterations (throws vanity_timeout) — exactly the
+ // path that produces a stream of progress samples with no early match.
+ await expect(
+ grindMintKeypair({
+ suffix: 'xyz',
+ maxIterations: 1500,
+ progressEvery: 500,
+ onProgress: (s) => samples.push(s),
+ }),
+ ).rejects.toMatchObject({ code: 'vanity_timeout' });
+
+ expect(samples.length).toBeGreaterThanOrEqual(2);
+ for (let i = 0; i < samples.length; i++) {
+ const s = samples[i];
+ expect(s.iterations).toBe(500 * (i + 1));
+ expect(s.elapsedMs).toBeGreaterThanOrEqual(0);
+ expect(s.attemptsPerSec).toBeGreaterThan(0);
+ expect(typeof s.sampleAddress).toBe('string');
+ expect(s.sampleAddress.length).toBeGreaterThan(30);
+ if (i > 0) {
+ // iterations and elapsed time only ever move forward.
+ expect(s.iterations).toBeGreaterThan(samples[i - 1].iterations);
+ expect(s.elapsedMs).toBeGreaterThanOrEqual(samples[i - 1].elapsedMs);
+ }
+ }
+ });
+
+ it('does not fire onProgress when no callback is passed (unchanged behaviour)', async () => {
+ // 1-char prefix lands almost immediately; the return shape is untouched.
+ const out = await grindMintKeypair({ prefix: 'a', ignoreCase: true });
+ expect(out.keypair.publicKey.toBase58().toLowerCase().startsWith('a')).toBe(true);
+ expect(out.iterations).toBeGreaterThan(0);
+ expect(out.durationMs).toBeGreaterThanOrEqual(0);
+ });
+});
+
+describe('computeGrindStats', () => {
+ it('derives attempts/sec from real iteration/elapsed deltas', () => {
+ const stats = computeGrindStats({
+ iterations: 4_182_330,
+ elapsedMs: 107_000,
+ prevIterations: 4_143_430,
+ prevElapsedMs: 106_000,
+ prefix: 'pump',
+ });
+ // (4,182,330 - 4,143,430) / (107000 - 106000) * 1000 = 38,900/sec
+ expect(stats.attemptsPerSec).toBeCloseTo(38_900, 0);
+ expect(stats.expectedIterations).toBe(Math.pow(58, 4));
+ expect(stats.progress).toBeGreaterThan(0);
+ expect(stats.progress).toBeLessThanOrEqual(1);
+ });
+
+ it('clamps progress to 1 and never divides by zero', () => {
+ const stats = computeGrindStats({
+ iterations: 999_999_999,
+ elapsedMs: 1000,
+ prevIterations: 999_999_999,
+ prevElapsedMs: 1000,
+ prefix: 'a',
+ });
+ expect(stats.progress).toBe(1);
+ expect(Number.isFinite(stats.attemptsPerSec)).toBe(true);
+ expect(stats.attemptsPerSec).toBeGreaterThanOrEqual(0);
+ });
+});
diff --git a/workers/agent-anchor/anchor-client.js b/workers/agent-anchor/anchor-client.js
new file mode 100644
index 000000000..174d37492
--- /dev/null
+++ b/workers/agent-anchor/anchor-client.js
@@ -0,0 +1,163 @@
+// anchor-client.js — live integrations for the Newsroom Anchor worker.
+//
+// Pulls the three real intel feeds, asks the brain to script the bulletin, and
+// stores the spoken script so the browser can fetch + speak it. Every call is a
+// real three.ws API call (no mocks): aixbt narrative intel, the pump.fun-backed
+// sentiment pulse, a live token snapshot, the multi-LLM brain router, and the
+// Redis-backed anchor-script store.
+
+import fetch from 'node-fetch';
+import { mergeBrief, buildAnchorMessages } from './brief.js';
+
+const API_BASE = (process.env.ANCHOR_API_BASE || process.env.API_BASE || 'https://three.ws').replace(/\/$/, '');
+const AGENT_JWT = process.env.AGENT_JWT;
+const AGENT_ID = process.env.AGENT_ID;
+// $THREE is the only coin — its sentiment + flow are the anchor's house ticker.
+// Overridable for non-prod runs; defaults to the canonical $THREE mint.
+const TOKEN_MINT = process.env.ANCHOR_TOKEN_MINT || 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+// Free, anon-allowed brain provider so the worker never burns a billed key.
+const BRAIN_PROVIDER = process.env.ANCHOR_BRAIN_PROVIDER || 'gpt-oss-120b';
+
+async function getJson(path, opts = {}) {
+ const url = /^https?:\/\//.test(path) ? path : `${API_BASE}${path}`;
+ const res = await fetch(url, {
+ ...opts,
+ signal: AbortSignal.timeout(opts.timeoutMs || 12_000),
+ });
+ if (!res.ok) throw new Error(`${path} → ${res.status}`);
+ return res.json();
+}
+
+/** aixbt narrative intel — the spine of every bulletin. */
+async function fetchIntel() {
+ try {
+ return await getJson(`/api/aixbt/intel?limit=12`);
+ } catch {
+ return null;
+ }
+}
+
+/** Sentiment pulse for the house ticker (pump.fun comments, no key needed). */
+async function fetchSentiment() {
+ try {
+ return await getJson(`/api/social/sentiment-pulse`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ token: TOKEN_MINT, limit: 100 }),
+ timeoutMs: 15_000,
+ });
+ } catch {
+ return null;
+ }
+}
+
+/**
+ * Live market snapshot for the house ticker, shaped to what mergeBrief expects.
+ * Reads Dexscreener directly — the same public, key-free source the pump_snapshot
+ * MCP tool uses for price/volume — and picks the highest-volume pair.
+ */
+async function fetchPump() {
+ try {
+ const data = await getJson(
+ `https://api.dexscreener.com/latest/dex/tokens/${encodeURIComponent(TOKEN_MINT)}`,
+ );
+ const pairs = Array.isArray(data?.pairs) ? data.pairs : [];
+ if (!pairs.length) return null;
+ const pair = pairs.reduce(
+ (best, p) => (Number(p?.volume?.h24 || 0) > (best?.vol || 0) ? { p, vol: Number(p.volume.h24) } : best),
+ null,
+ )?.p;
+ if (!pair) return null;
+ return {
+ priceUsd: pair.priceUsd != null ? Number(pair.priceUsd) : null,
+ price: { priceChange24hPct: pair.priceChange?.h24 ?? null },
+ volume24h: { volume24hUsd: Number(pair.volume?.h24 || 0), dex: pair.dexId || null },
+ meta: { name: pair.baseToken?.name || null, symbol: pair.baseToken?.symbol || null },
+ };
+ } catch {
+ return null;
+ }
+}
+
+/** Fetch all three feeds concurrently and merge into an anchor briefing. */
+export async function gatherBrief() {
+ const [intel, sentiment, pump] = await Promise.all([
+ fetchIntel(),
+ fetchSentiment(),
+ fetchPump(),
+ ]);
+ return mergeBrief({ intel, sentiment, pump });
+}
+
+/**
+ * Script the bulletin via POST /api/brain/chat (SSE). Accumulates the streamed
+ * text fragments into the full anchor read. Throws on an upstream error event.
+ */
+export async function scriptBulletin(brief) {
+ const { system, messages } = buildAnchorMessages(brief);
+ const res = await fetch(`${API_BASE}/api/brain/chat`, {
+ method: 'POST',
+ headers: {
+ 'content-type': 'application/json',
+ ...(AGENT_JWT ? { authorization: `Bearer ${AGENT_JWT}` } : {}),
+ },
+ body: JSON.stringify({ provider: BRAIN_PROVIDER, system, messages, maxTokens: 400 }),
+ signal: AbortSignal.timeout(60_000),
+ });
+ if (!res.ok || !res.body) throw new Error(`brain/chat → ${res.status}`);
+
+ let buf = '';
+ let out = '';
+ let errMsg = null;
+ const decoder = new TextDecoder();
+ for await (const chunk of res.body) {
+ buf += typeof chunk === 'string' ? chunk : decoder.decode(chunk, { stream: true });
+ const events = buf.split('\n\n');
+ buf = events.pop() || '';
+ for (const ev of events) {
+ let event = 'message';
+ const dataLines = [];
+ for (const line of ev.split('\n')) {
+ if (line.startsWith('event:')) event = line.slice(6).trim();
+ else if (line.startsWith('data:')) dataLines.push(line.slice(5).trim());
+ }
+ const data = dataLines.join('\n');
+ if (!data) continue;
+ if (event === 'error') {
+ try { errMsg = JSON.parse(data).message; } catch { errMsg = data; }
+ continue;
+ }
+ if (event === 'done' || data === '[DONE]') continue;
+ if (event === 'meta' || event === 'first' || event === 'fallback') continue;
+ // Data-only chunk: a JSON-encoded text fragment.
+ try {
+ const frag = JSON.parse(data);
+ if (typeof frag === 'string') out += frag;
+ } catch { /* skip non-JSON keepalive lines */ }
+ }
+ }
+ if (!out.trim() && errMsg) throw new Error(errMsg);
+ if (!out.trim()) throw new Error('empty anchor script');
+ return out.trim();
+}
+
+/**
+ * Store the spoken script so the browser can fetch it via GET /api/agent/
+ * anchor-script. Posts to the same endpoint (authenticated) which writes Redis.
+ */
+export async function publishScript({ headline, body, brief }) {
+ if (!AGENT_JWT || !AGENT_ID) return;
+ try {
+ await fetch(`${API_BASE}/api/agent/anchor-script`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${AGENT_JWT}` },
+ body: JSON.stringify({
+ agentId: AGENT_ID,
+ headline,
+ body,
+ offline: brief?.offline || [],
+ }),
+ signal: AbortSignal.timeout(8_000),
+ });
+ } catch { /* non-fatal — the headline frame still renders */ }
+}
diff --git a/workers/agent-anchor/brief.js b/workers/agent-anchor/brief.js
new file mode 100644
index 000000000..ba5759368
--- /dev/null
+++ b/workers/agent-anchor/brief.js
@@ -0,0 +1,270 @@
+// brief.js — pure feed-merge + script-split logic for the Newsroom Anchor.
+//
+// Kept dependency-free and side-effect-free so it can be unit-tested in
+// isolation (tests/anchor-brief.test.js) and reused by the worker loop. The
+// worker fetches the three live intel feeds, hands the raw payloads here to
+// build a compact briefing, asks the brain to script an anchor read, then
+// splits that read into a lower-third headline and a spoken body.
+
+// Headline lives in the screen frame's `activity` (320-char hard cap server
+// side) and in the lower-third overlay. We aim shorter so it reads cleanly.
+export const HEADLINE_MAX = 120;
+// Spoken body is synthesized by Magpie TTS (4096-char ceiling); keep an anchor
+// read tight so a bulletin stays ~15–25s.
+export const BODY_MAX = 700;
+// The activity field the push endpoint stores (mirror of api/agent-screen-push).
+export const ACTIVITY_MAX = 320;
+// How many narrative items the anchor actually reads on air. The rest are
+// summarized as a count so a busy market doesn't produce a 2-minute monologue.
+export const MAX_ITEMS = 3;
+
+function clean(str) {
+ return String(str == null ? '' : str).replace(/\s+/g, ' ').trim();
+}
+
+function num(v) {
+ const n = typeof v === 'string' ? Number(v) : v;
+ return Number.isFinite(n) ? n : null;
+}
+
+/** Human label for a sentiment score in [-1, 1]. */
+export function sentimentLabel(score) {
+ const s = num(score);
+ if (s == null) return null;
+ if (s >= 0.35) return 'bullish';
+ if (s >= 0.1) return 'leaning positive';
+ if (s <= -0.35) return 'bearish';
+ if (s <= -0.1) return 'leaning negative';
+ return 'mixed';
+}
+
+/** Compact USD formatting for spoken numbers ($1.2M, $940K, $0.04). */
+export function fmtUsd(v) {
+ const n = num(v);
+ if (n == null) return null;
+ const abs = Math.abs(n);
+ if (abs >= 1_000_000_000) return `$${(n / 1_000_000_000).toFixed(1)}B`;
+ if (abs >= 1_000_000) return `$${(n / 1_000_000).toFixed(1)}M`;
+ if (abs >= 1_000) return `$${(n / 1_000).toFixed(0)}K`;
+ if (abs >= 1) return `$${n.toFixed(2)}`;
+ return `$${n.toPrecision(2)}`;
+}
+
+/**
+ * Merge the three raw feed payloads into a compact, anchor-ready briefing.
+ *
+ * @param {object} feeds
+ * @param {{ intel?: Array }|null} [feeds.intel] — /api/aixbt/intel result
+ * @param {object|null} [feeds.sentiment] — /api/social/sentiment-pulse result
+ * @param {object|null} [feeds.pump] — pump snapshot result
+ * @returns {{ items, sentiment, market, available, offline, isQuiet }}
+ */
+export function mergeBrief(feeds = {}) {
+ const offline = [];
+
+ // ── Narrative intel (the spine of every bulletin) ────────────────────────
+ const rawIntel = Array.isArray(feeds.intel?.intel)
+ ? feeds.intel.intel
+ : Array.isArray(feeds.intel)
+ ? feeds.intel
+ : null;
+ let items = [];
+ if (rawIntel == null) {
+ offline.push('narrative');
+ } else {
+ items = rawIntel
+ .map((i) => ({
+ category: clean(i?.category) || null,
+ headline: clean(i?.description || i?.summary),
+ project: clean(i?.project) || null,
+ ticker: clean(i?.ticker) || null,
+ observations: num(i?.observations),
+ official: Boolean(i?.official_source),
+ }))
+ .filter((i) => i.headline)
+ // Most-observed / official-sourced narratives lead the broadcast.
+ .sort((a, b) => {
+ if (a.official !== b.official) return a.official ? -1 : 1;
+ return (b.observations || 0) - (a.observations || 0);
+ });
+ }
+ const totalItems = items.length;
+ const topItems = items.slice(0, MAX_ITEMS);
+
+ // ── Sentiment pulse ──────────────────────────────────────────────────────
+ let sentiment = null;
+ const ov = feeds.sentiment?.overall;
+ if (feeds.sentiment == null || feeds.sentiment?.ok === false) {
+ offline.push('sentiment');
+ } else if (ov && num(ov.count)) {
+ sentiment = {
+ score: num(ov.score),
+ label: sentimentLabel(ov.score),
+ count: num(ov.count),
+ posPct: num(ov.posPct),
+ negPct: num(ov.negPct),
+ };
+ }
+
+ // ── Market snapshot ──────────────────────────────────────────────────────
+ let market = null;
+ if (feeds.pump == null) {
+ offline.push('flow');
+ } else {
+ const meta = feeds.pump.meta || {};
+ const vol = feeds.pump.volume24h || {};
+ const change =
+ num(feeds.pump.price?.priceChange24hPct) ??
+ num(vol.priceChange24hPct);
+ market = {
+ symbol: clean(meta.symbol) || null,
+ name: clean(meta.name) || null,
+ priceUsd: num(feeds.pump.priceUsd) ?? num(feeds.pump.price?.usdPrice),
+ change24h: change,
+ volume24h: num(vol.volume24hUsd),
+ dex: clean(vol.dex) || null,
+ };
+ // A snapshot that returned nothing useful counts as offline flow.
+ if (market.priceUsd == null && market.volume24h == null) {
+ market = null;
+ offline.push('flow');
+ }
+ }
+
+ const isQuiet = topItems.length === 0 && !sentiment && !market;
+
+ return {
+ items: topItems,
+ moreItems: Math.max(0, totalItems - topItems.length),
+ sentiment,
+ market,
+ available: {
+ narrative: rawIntel != null && topItems.length > 0,
+ sentiment: !!sentiment,
+ flow: !!market,
+ },
+ offline,
+ isQuiet,
+ };
+}
+
+/**
+ * Render the briefing into a plain-text digest the brain turns into a read.
+ * Deterministic so the test can assert exactly what the model is handed.
+ */
+export function briefDigest(brief) {
+ const lines = [];
+ if (brief.items.length) {
+ lines.push('NARRATIVES:');
+ brief.items.forEach((it, i) => {
+ const tag = it.category ? ` [${it.category}]` : '';
+ const obs = it.observations ? ` (${it.observations} obs)` : '';
+ lines.push(`${i + 1}.${tag} ${it.headline}${obs}`);
+ });
+ if (brief.moreItems) lines.push(`(+${brief.moreItems} more narratives moving)`);
+ }
+ if (brief.sentiment) {
+ const pos = brief.sentiment.posPct != null ? `, ${brief.sentiment.posPct}% positive` : '';
+ lines.push(
+ `SENTIMENT: ${brief.sentiment.label} across ${brief.sentiment.count} recent comments${pos}.`,
+ );
+ }
+ if (brief.market) {
+ const bits = [];
+ if (brief.market.priceUsd != null) bits.push(`price ${fmtUsd(brief.market.priceUsd)}`);
+ if (brief.market.change24h != null) {
+ const sign = brief.market.change24h >= 0 ? '+' : '';
+ bits.push(`${sign}${brief.market.change24h.toFixed(1)}% 24h`);
+ }
+ if (brief.market.volume24h != null) bits.push(`${fmtUsd(brief.market.volume24h)} 24h volume`);
+ if (bits.length) lines.push(`FLOW: ${bits.join(', ')}.`);
+ }
+ if (brief.offline.length) {
+ lines.push(`OFFLINE FEEDS: ${brief.offline.join(', ')} — do not invent data for these.`);
+ }
+ return lines.join('\n');
+}
+
+const ANCHOR_SYSTEM = [
+ 'You are a live market-news anchor for three.ws.',
+ 'Read the market to the viewer in plain, confident language — no jargon, no hashtags, no emojis.',
+ 'Cover the top one to three narratives, one headline plus one line of context each.',
+ 'Never recommend buying or selling, and never name or promote a specific token ticker or mint other than $THREE — describe the narrative or the flow instead.',
+ 'If a feed is offline, simply omit it; never invent numbers.',
+ 'Respond with EXACTLY this shape:',
+ 'Line 1: HEADLINE: <a punchy on-screen headline, max 90 characters>',
+ 'Then a blank line.',
+ 'Then the spoken anchor read: 2 to 4 short sentences, ready to be read aloud.',
+].join(' ');
+
+/**
+ * Build the { system, messages } payload for POST /api/brain/chat from a brief.
+ * Quiet markets get a graceful "nothing moving" prompt rather than silence.
+ */
+export function buildAnchorMessages(brief) {
+ const digest = brief.isQuiet
+ ? 'The market is quiet right now — no fresh narratives, sentiment, or flow came back this cycle.'
+ : briefDigest(brief);
+ return {
+ system: ANCHOR_SYSTEM,
+ messages: [
+ {
+ role: 'user',
+ content: brief.isQuiet
+ ? `${digest}\n\nGive a brief, calm "quiet market" anchor read acknowledging the lull and that you'll be back with the next bulletin.`
+ : `Here is the current market intel. Script the next bulletin.\n\n${digest}`,
+ },
+ ],
+ };
+}
+
+function stripWrappingQuotes(s) {
+ return s.replace(/^["'“”‘’]+/, '').replace(/["'“”‘’]+$/, '').trim();
+}
+
+/** First sentence of a body, used as a headline fallback. */
+function firstSentence(text) {
+ const m = /^(.*?[.!?])(\s|$)/.exec(text);
+ return clean(m ? m[1] : text);
+}
+
+/**
+ * Split a scripted anchor read into a lower-third headline and a spoken body.
+ * Tolerant of the model dropping the "HEADLINE:" marker or the blank line.
+ *
+ * @param {string} script
+ * @returns {{ headline: string, body: string }}
+ */
+export function splitScript(script) {
+ const text = clean(script);
+ if (!text) return { headline: '', body: '' };
+
+ // Work line-by-line so the marker + blank-line contract is honored when present.
+ const lines = String(script).split(/\r?\n/).map((l) => l.trim());
+ const nonEmpty = lines.filter(Boolean);
+
+ let headline = '';
+ let body = '';
+
+ const markerIdx = nonEmpty.findIndex((l) => /^headline\s*:/i.test(l));
+ if (markerIdx !== -1) {
+ headline = stripWrappingQuotes(nonEmpty[markerIdx].replace(/^headline\s*:/i, '').trim());
+ body = clean(nonEmpty.slice(markerIdx + 1).join(' '));
+ } else if (nonEmpty.length > 1) {
+ // No marker: treat the first line as the headline, the rest as the read.
+ headline = stripWrappingQuotes(nonEmpty[0]);
+ body = clean(nonEmpty.slice(1).join(' '));
+ } else {
+ // Single blob: derive a headline from the first sentence, speak the whole thing.
+ headline = firstSentence(text);
+ body = text;
+ }
+
+ if (!body) body = headline;
+ if (!headline) headline = firstSentence(body);
+
+ if (headline.length > HEADLINE_MAX) headline = headline.slice(0, HEADLINE_MAX - 1).trimEnd() + '…';
+ if (body.length > BODY_MAX) body = body.slice(0, BODY_MAX - 1).trimEnd() + '…';
+
+ return { headline, body };
+}
diff --git a/workers/agent-anchor/index.js b/workers/agent-anchor/index.js
new file mode 100644
index 000000000..5654558bd
--- /dev/null
+++ b/workers/agent-anchor/index.js
@@ -0,0 +1,107 @@
+// agent-anchor — autonomous market-news anchor worker (entrypoint).
+//
+// A long-lived cadence loop (default 90s, env ANCHOR_CADENCE_MS) that:
+// 1. pulls the three real intel feeds (aixbt narrative, sentiment pulse, flow),
+// 2. merges them into a compact briefing,
+// 3. asks the brain to script a tight 2–4 sentence anchor read,
+// 4. splits it into a lower-third headline + a spoken body,
+// 5. stores the script (so viewers' browsers can speak it) and pushes the
+// headline as a type:'analysis' screen frame.
+//
+// Viewers on /agent-screen subscribe to the frame stream, speak the body with
+// real TTS, and lip-sync the avatar to it. This process is NOT a Vercel cron —
+// it holds state across ticks and runs continuously. Run: node workers/agent-anchor.
+//
+// ANCHOR_CADENCE_MS — ms between bulletins (default 90000)
+// AGENT_JWT, AGENT_ID — the anchor agent's identity (required to push)
+// ANCHOR_API_BASE — three.ws API origin (default https://three.ws)
+
+import { gatherBrief, scriptBulletin, publishScript } from './anchor-client.js';
+import { splitScript } from './brief.js';
+import { screenPush } from './screen-push.js';
+
+const CADENCE_MS = Math.max(15_000, Number(process.env.ANCHOR_CADENCE_MS) || 90_000);
+const BOOT_AT = new Date().toISOString();
+
+function log(level, msg, meta) {
+ const line = { t: new Date().toISOString(), level, msg, ...(meta || {}) };
+ (level === 'error' ? console.error : console.log)(JSON.stringify(line));
+}
+
+// Run one full bulletin: gather → script → split → publish → push. Each stage
+// degrades gracefully — a dead feed narrows the read, a brain failure skips the
+// tick (the previous frame's 90s TTL keeps the last bulletin on screen briefly),
+// and the loop always lives to the next cadence.
+async function runBulletin() {
+ const brief = await gatherBrief();
+ if (brief.offline.length) {
+ log('info', 'feeds offline', { offline: brief.offline });
+ }
+
+ let script;
+ try {
+ script = await scriptBulletin(brief);
+ } catch (err) {
+ log('error', 'script failed', { err: err?.message });
+ // Honest fallback: report the live feeds that did return rather than going
+ // silent, so the wall still shows the anchor reacting to the market.
+ const fallback = brief.isQuiet
+ ? 'Markets are quiet — no fresh narratives this cycle. Back shortly with the next bulletin.'
+ : `Reading the tape: ${brief.items[0]?.headline || 'narratives developing'}.`;
+ screenPush(fallback.slice(0, 120), 'analysis');
+ return;
+ }
+
+ const { headline, body } = splitScript(script);
+ if (!headline) {
+ log('error', 'empty headline', {});
+ return;
+ }
+
+ await publishScript({ headline, body, brief });
+ screenPush(headline, 'analysis');
+ log('info', 'on air', { headline, bodyLen: body.length, offline: brief.offline });
+}
+
+async function main() {
+ log('info', 'boot', { cadenceMs: CADENCE_MS, bootAt: BOOT_AT });
+ if (!process.env.AGENT_JWT || !process.env.AGENT_ID) {
+ log('error', 'missing AGENT_JWT/AGENT_ID — frames will not push', {});
+ }
+ screenPush('On air shortly — pulling the latest market intel', 'analysis');
+
+ let draining = false;
+ let running = false;
+
+ const tick = async () => {
+ if (draining || running) return; // overlap guard — a slow brain can't stack
+ running = true;
+ try {
+ await runBulletin();
+ } catch (err) {
+ log('error', 'bulletin crashed', { err: err?.message });
+ } finally {
+ running = false;
+ }
+ };
+
+ // First bulletin immediately, then on cadence.
+ await tick();
+ const timer = setInterval(tick, CADENCE_MS);
+
+ const shutdown = (signal) => {
+ if (draining) return;
+ draining = true;
+ log('info', 'shutdown', { signal });
+ clearInterval(timer);
+ process.exit(0);
+ };
+ process.on('SIGINT', () => shutdown('SIGINT'));
+ process.on('SIGTERM', () => shutdown('SIGTERM'));
+ process.on('unhandledRejection', (err) => log('error', 'unhandledRejection', { err: err?.message }));
+}
+
+main().catch((err) => {
+ log('error', 'fatal', { err: err?.message, stack: err?.stack });
+ process.exit(1);
+});
diff --git a/workers/agent-anchor/package.json b/workers/agent-anchor/package.json
new file mode 100644
index 000000000..7af1fcd28
--- /dev/null
+++ b/workers/agent-anchor/package.json
@@ -0,0 +1,20 @@
+{
+ "name": "@three-ws/agent-anchor",
+ "version": "0.1.0",
+ "private": true,
+ "type": "module",
+ "description": "Autonomous market-news anchor worker — pulls real intel, scripts a bulletin via the brain, and pushes lower-third headlines for the lip-synced avatar to read on air.",
+ "main": "index.js",
+ "scripts": {
+ "start": "node index.js"
+ },
+ "dependencies": {
+ "node-fetch": "^3.3.2"
+ },
+ "optionalDependencies": {
+ "canvas": "^2.11.2"
+ },
+ "engines": {
+ "node": ">=22"
+ }
+}
diff --git a/workers/agent-anchor/screen-push.js b/workers/agent-anchor/screen-push.js
new file mode 100644
index 000000000..2dba235e5
--- /dev/null
+++ b/workers/agent-anchor/screen-push.js
@@ -0,0 +1,104 @@
+// screen-push.js — fire-and-forget push to the agent screen stream for the
+// Newsroom Anchor. Mirrors workers/agent-sniper/screen-push.js: every push is
+// non-blocking and failures are swallowed so a transport blip never stalls the
+// broadcast cadence. Optionally renders a broadcast-style frame with node-canvas
+// (lower-third over a desk gradient) when the package is available, falling back
+// to a text-only frame otherwise.
+
+import fetch from 'node-fetch';
+
+const PUSH_URL = process.env.PUSH_URL || 'https://three.ws/api/agent-screen-push';
+const AGENT_JWT = process.env.AGENT_JWT;
+const AGENT_ID = process.env.AGENT_ID;
+
+const CW = 1280, CH = 720;
+
+// node-canvas is optional. If it isn't installed the worker still pushes
+// text-only frames — the client renders the real lower-third + talking avatar,
+// so the rendered desk frame is a bonus for non-anchor surfaces (the wall).
+let canvasCreate = false;
+(async () => {
+ try {
+ const mod = await import('canvas');
+ canvasCreate = mod.createCanvas;
+ } catch { /* text-only mode */ }
+})();
+
+function wrapLines(ctx, text, maxWidth, maxLines) {
+ const words = String(text).split(/\s+/);
+ const lines = [];
+ let line = '';
+ for (const w of words) {
+ const test = line ? `${line} ${w}` : w;
+ if (ctx.measureText(test).width > maxWidth && line) {
+ lines.push(line);
+ line = w;
+ if (lines.length >= maxLines) return lines;
+ } else {
+ line = test;
+ }
+ }
+ if (line && lines.length < maxLines) lines.push(line);
+ return lines;
+}
+
+function renderBroadcastFrame(headline) {
+ if (!canvasCreate) return null;
+ const canvas = canvasCreate(CW, CH);
+ const ctx = canvas.getContext('2d');
+
+ // Studio backdrop
+ const bg = ctx.createLinearGradient(0, 0, 0, CH);
+ bg.addColorStop(0, '#0a1326');
+ bg.addColorStop(1, '#05080f');
+ ctx.fillStyle = bg;
+ ctx.fillRect(0, 0, CW, CH);
+
+ // Channel mark
+ ctx.fillStyle = 'rgba(255,255,255,0.5)';
+ ctx.font = '600 22px sans-serif';
+ ctx.fillText('three.ws · NEWSROOM', 48, 56);
+ ctx.fillStyle = '#ff4d4f';
+ ctx.beginPath();
+ ctx.arc(CW - 120, 48, 8, 0, Math.PI * 2);
+ ctx.fill();
+ ctx.fillStyle = 'rgba(255,255,255,0.85)';
+ ctx.font = '700 18px sans-serif';
+ ctx.fillText('ON AIR', CW - 100, 54);
+
+ // Lower-third band
+ const bandY = CH - 220;
+ ctx.fillStyle = 'rgba(8,12,24,0.92)';
+ ctx.fillRect(0, bandY, CW, 220);
+ const accent = ctx.createLinearGradient(0, bandY, 0, bandY + 6);
+ accent.addColorStop(0, '#6ea8ff');
+ accent.addColorStop(1, '#3b6ed8');
+ ctx.fillStyle = accent;
+ ctx.fillRect(0, bandY, CW, 6);
+
+ ctx.fillStyle = '#6ea8ff';
+ ctx.font = '700 22px sans-serif';
+ ctx.fillText('MARKET ANCHOR', 56, bandY + 50);
+
+ ctx.fillStyle = '#ffffff';
+ ctx.font = '700 46px sans-serif';
+ const lines = wrapLines(ctx, headline, CW - 112, 2);
+ lines.forEach((l, i) => ctx.fillText(l, 56, bandY + 110 + i * 56));
+
+ return 'data:image/png;base64,' + canvas.toBuffer('image/png').toString('base64');
+}
+
+/**
+ * Push a bulletin headline frame. type is 'analysis' so the client's anchor
+ * overlay picks it up and speaks the matching script.
+ */
+export function screenPush(activity, type = 'analysis') {
+ if (!AGENT_JWT || !AGENT_ID) return;
+ const data = type === 'analysis' ? renderBroadcastFrame(activity) : null;
+ const frame = data ? { data, activity, type } : { activity, type };
+ fetch(PUSH_URL, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${AGENT_JWT}` },
+ body: JSON.stringify({ agentId: AGENT_ID, frame }),
+ }).catch(() => {});
+}
diff --git a/workers/agent-screen-pool/index.js b/workers/agent-screen-pool/index.js
index eea9c586d..69062ed79 100644
--- a/workers/agent-screen-pool/index.js
+++ b/workers/agent-screen-pool/index.js
@@ -28,6 +28,8 @@
// VIEWPORT_W=1280 VIEWPORT_H=720
import { chromium } from 'playwright';
+import { pickTask } from './tasks/index.js';
+import { generateNarration, runTaskSteps } from './task-runner.js';
const BASE_URL = (process.env.BASE_URL || 'https://three.ws').replace(/\/$/, '');
const WANTED_URL = process.env.WANTED_URL || `${BASE_URL}/api/agent/watch-wanted`;
@@ -42,8 +44,50 @@ const MAX_BROWSERS = Number(process.env.MAX_BROWSERS || 6);
const POLL_MS = Number(process.env.POLL_MS || 3000);
const FRAME_MS = Number(process.env.FRAME_MS || 700);
const JPEG_QUALITY = Number(process.env.JPEG_QUALITY || 58);
+const LEAD_MS = Number(process.env.LEAD_MS || 900); // how long narration leads the action
+const DWELL_MS = Number(process.env.DWELL_MS || 6000); // hold on the result between task runs
const VIEWPORT = { width: Number(process.env.VIEWPORT_W || 1280), height: Number(process.env.VIEWPORT_H || 720) };
+// Coin World Tour config. When a cast page exposes window.__tour, the worker walks
+// the guide through the waypoint loop, dwelling at each stop and narrating the live
+// /api/pump/trending feed. Trending is cached so a fleet of tours doesn't hammer it.
+const TOUR_DWELL_MS = Number(process.env.TOUR_DWELL_MS || 6500); // pause per waypoint
+const TOUR_READY_MS = Number(process.env.TOUR_READY_MS || 30_000); // max wait for scene-ready
+const TRENDING_URL = process.env.TRENDING_URL || `${BASE_URL}/api/pump/trending?limit=8`;
+const TRENDING_TTL_MS = Number(process.env.TRENDING_TTL_MS || 20_000);
+let _trending = { at: 0, data: [] };
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+// Live trending feed, cached ~20s and shared across every concurrent tour. Returns
+// [] on any failure so commentary degrades to world-only narration, never throws.
+async function getTrending() {
+ if (Date.now() - _trending.at < TRENDING_TTL_MS) return _trending.data;
+ try {
+ const res = await fetch(TRENDING_URL, { headers: { accept: 'application/json' } });
+ if (!res.ok) { _trending = { at: Date.now(), data: [] }; return []; }
+ const body = await res.json();
+ const data = Array.isArray(body?.data) ? body.data : [];
+ _trending = { at: Date.now(), data };
+ return data;
+ } catch {
+ _trending = { at: Date.now(), data: [] };
+ return [];
+ }
+}
+
+// Push a text-only commentary line (type:'analysis') to the wall + watch panel.
+async function pushAnalysis(entry, line) {
+ if (!line) return;
+ try {
+ await fetch(PUSH_URL, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', authorization: `Bearer ${SECRET}` },
+ body: JSON.stringify({ agentId: entry.agentId, frame: { activity: String(line).slice(0, 300), type: 'analysis' } }),
+ });
+ } catch { /* a dropped commentary line never breaks the tour */ }
+}
+
if (!SECRET || SECRET.length < 16) {
console.error('[pool] SCREEN_WORKER_SECRET is required (>= 16 chars) and must match the API. Exiting.');
process.exit(1);
@@ -106,7 +150,10 @@ async function pushFrame(entry) {
method: 'POST', headers,
body: JSON.stringify({
agentId: entry.agentId,
- frame: { data: `data:image/jpeg;base64,${b64}`, activity: `Live view · ${entry.name}`, type: 'screenshot' },
+ // On a Coin World Tour the frame is stamped with the current waypoint
+ // (entry.activityOverride, e.g. "Tour · Into the arena") so the wall +
+ // watch panel light up the TOUR badge; otherwise it's the live view.
+ frame: { data: `data:image/jpeg;base64,${b64}`, activity: entry.activityOverride || `Live view · ${entry.name}`, type: 'screenshot' },
}),
}),
fetch(PUSH_URL_DESK, {
@@ -134,7 +181,7 @@ async function startCasting(agent) {
await ensureBrowser();
const agentId = agent.agentId;
const page = await context.newPage();
- const entry = { agentId, page, name: agent.name || 'Agent', timer: null, pushing: false, lastErrorAt: 0, seq: 0 };
+ const entry = { agentId, page, name: agent.name || 'Agent', timer: null, pushing: false, lastErrorAt: 0, seq: 0, controller: new AbortController() };
pool.set(agentId, entry);
const url = resolveUrl(agent.homeUrl, agentId);
try {
@@ -143,8 +190,222 @@ async function startCasting(agent) {
log('goto failed', agentId, err?.message || err);
}
await pushFrame(entry);
- entry.timer = setInterval(() => pushFrame(entry), FRAME_MS);
- log('casting', agentId, agent.name, '→', url, `(${pool.size}/${MAX_BROWSERS})`);
+
+ // If the page is a walkable world exposing window.__tour, run the guided world
+ // tour alongside the continuous frame capture (which streams the walkthrough).
+ const isTour = await page.evaluate(() => !!(window.__tour && typeof window.__tour.goTo === 'function')).catch(() => false);
+ if (isTour) {
+ entry.timer = setInterval(() => pushFrame(entry), FRAME_MS);
+ entry.tour = true;
+ log('casting (tour)', agentId, agent.name, '→', url, `(${pool.size}/${MAX_BROWSERS})`);
+ runTour(entry).catch((err) => log('tour error', agentId, err?.message || err));
+ return;
+ }
+
+ // Otherwise run a real, multi-step web task on this page (the "watch an agent
+ // do real web work" moment). The task loop is the sole frame writer here — no
+ // continuous timer — so its narration and screenshots stay in step.
+ log('casting (task)', agentId, agent.name, `(${pool.size}/${MAX_BROWSERS})`);
+ runCastTask(entry).catch((err) => log('cast task crashed', agentId, err?.message || err));
+}
+
+// Walk a guide agent through the world's waypoint loop, narrating live trending
+// data at each stop. Runs until the agent leaves the pool (nobody watching) or the
+// worker shuts down. Drives the real camera/avatar via window.__tour — no faking.
+async function runTour(entry) {
+ const { page, agentId } = entry;
+ // Wait for the scene to become walkable (bounded so a stuck load can't hang us).
+ const ready = await page.evaluate((ms) => Promise.race([
+ window.__tour.ready().then(() => true),
+ new Promise((r) => setTimeout(() => r(false), ms)),
+ ]), TOUR_READY_MS).catch(() => false);
+ if (!ready) { log('tour not ready', agentId); return; }
+
+ const stops = await page.evaluate(() => window.__tour.waypoints()).catch(() => []);
+ if (!Array.isArray(stops) || !stops.length) { log('tour: no waypoints', agentId); return; }
+
+ let i = 0;
+ while (!stopping && pool.has(agentId) && !page.isClosed()) {
+ const name = stops[i % stops.length];
+ i++;
+ try {
+ await page.evaluate((n) => window.__tour.goTo(n), name);
+ const trending = await getTrending();
+ const c = await page.evaluate((t) => window.__tour.commentary(t), trending).catch(() => null);
+ if (c) {
+ entry.activityOverride = c.badge; // stamps screenshot frames with the waypoint
+ await pushAnalysis(entry, c.line); // narrates the stop in the activity log
+ }
+ } catch (err) {
+ if (page.isClosed()) break;
+ log('tour step', agentId, err?.message || err);
+ }
+ await sleep(TOUR_DWELL_MS);
+ }
+ entry.activityOverride = null;
+}
+
+// ── task-driven web-work mode ──────────────────────────────────────────────────
+//
+// For an agent whose home page is NOT a walkable world, the caster runs a real,
+// multi-step web task (see tasks/) instead of just screenshotting a static page:
+// it navigates to a real public site, fills a real form, submits, waits for real
+// results, and reads them back — narrating each action a beat before it happens
+// and landing a screenshot after. This is the "watch an agent do real web work"
+// moment. Single writer per page (this loop), so its pushes don't collide with the
+// continuous-frame timer used by the tour/static path.
+
+// Push one frame for the task path. A narration push carries activity text + a
+// fresh shot; a pixels-only push (empty activity) keeps the stream live during
+// typing/waits/dwell WITHOUT spamming the activity log (the API logs only frames
+// that carry activity).
+async function pushTaskFrame(entry, { activity = '', type = 'screenshot', shoot = true } = {}) {
+ if (!entry.page || entry.page.isClosed()) return;
+ let b64 = null;
+ if (shoot) {
+ try {
+ const buf = await entry.page.screenshot({ type: 'jpeg', quality: JPEG_QUALITY, fullPage: false });
+ b64 = buf.toString('base64');
+ } catch { /* page navigating — push the narration line without pixels */ }
+ }
+ const dataUrl = b64 ? `data:image/jpeg;base64,${b64}` : null;
+ const seq = ++entry.seq;
+ const headers = { 'content-type': 'application/json', authorization: `Bearer ${SECRET}` };
+ const [wall] = await Promise.allSettled([
+ fetch(PUSH_URL, {
+ method: 'POST', headers,
+ body: JSON.stringify({ agentId: entry.agentId, frame: { data: dataUrl, activity, type } }),
+ }),
+ b64
+ ? fetch(PUSH_URL_DESK, { method: 'POST', headers, body: JSON.stringify({ agentId: entry.agentId, frame: b64, seq }) })
+ : Promise.resolve(),
+ ]);
+ const wallBad = wall.status === 'fulfilled' && !wall.value.ok;
+ if (wallBad && Date.now() - (entry.lastErrorAt || 0) > 30_000) {
+ entry.lastErrorAt = Date.now();
+ log('task push failed', entry.agentId, wall.value.status, (await wall.value.text().catch(() => '')).slice(0, 120));
+ }
+}
+
+// Keep pixels flowing through the slow parts of a task (typing, waiting, dwell),
+// all as empty-activity frames so the log stays clean.
+async function typeWithFrames(entry, selector, value) {
+ const field = entry.page.locator(selector).first();
+ await field.click({ timeout: 8_000 }).catch(() => {});
+ await field.fill('').catch(() => {});
+ let typed = 0;
+ for (const ch of value) {
+ if (entry.controller.signal.aborted) return;
+ await field.pressSequentially(ch, { delay: 45 }).catch(() => {});
+ typed++;
+ if (typed % 2 === 0 || typed === value.length) await pushTaskFrame(entry, {});
+ }
+}
+
+async function waitWithFrames(entry, selector, { timeout = 15_000, fallbackUrl = null } = {}) {
+ const page = entry.page;
+ const deadline = Date.now() + timeout;
+ while (Date.now() < deadline) {
+ if (entry.controller.signal.aborted) return false;
+ const visible = await page.locator(selector).first().isVisible().catch(() => false);
+ await pushTaskFrame(entry, {});
+ if (visible) return true;
+ await sleep(FRAME_MS);
+ }
+ if (fallbackUrl && !entry.controller.signal.aborted) {
+ await page.goto(fallbackUrl, { waitUntil: 'domcontentloaded', timeout: 30_000 }).catch(() => {});
+ await pushTaskFrame(entry, {});
+ return await page.locator(selector).first().isVisible().catch(() => false);
+ }
+ return false;
+}
+
+async function dwellTask(entry, ms) {
+ const deadline = Date.now() + ms;
+ while (Date.now() < deadline) {
+ if (entry.controller.signal.aborted) return;
+ await pushTaskFrame(entry, {});
+ await sleep(FRAME_MS);
+ }
+}
+
+async function readText(entry, step) {
+ const loc = entry.page.locator(step.selector);
+ if (step.multi) {
+ const texts = (await loc.allInnerTexts().catch(() => []))
+ .map((t) => t.replace(/\s+/g, ' ').trim())
+ .filter(Boolean);
+ return texts.slice(0, step.limit || 5).join(' · ');
+ }
+ const t = await loc.first().innerText({ timeout: 8_000 }).catch(() => '');
+ return t.replace(/\s+/g, ' ').trim();
+}
+
+// The executor the sequencer (task-runner.js) drives: narrate → perform → shot.
+// narrate() pushes the line + a shot, then lets it lead by LEAD_MS (no further
+// pushes, so the narration frame is reliably delivered before the result lands —
+// the "one beat ahead" feel that makes it look like thinking).
+function makeExecutor(entry) {
+ return {
+ async narrate(line) {
+ await pushTaskFrame(entry, { activity: line, type: 'analysis' });
+ const deadline = Date.now() + LEAD_MS;
+ while (Date.now() < deadline && !entry.controller.signal.aborted) await sleep(Math.min(LEAD_MS, 150));
+ },
+ async perform(step) {
+ const page = entry.page;
+ switch (step.kind) {
+ case 'goto': await page.goto(step.url, { waitUntil: 'domcontentloaded', timeout: 30_000 }); return null;
+ case 'type': await typeWithFrames(entry, step.selector, step.value); return null;
+ case 'submit': await page.locator(step.selector).first().press(step.key || 'Enter'); return null;
+ case 'waitResult': await waitWithFrames(entry, step.selector, { timeout: 15_000, fallbackUrl: step.fallbackUrl }); return null;
+ case 'read': return await readText(entry, step);
+ default: return null;
+ }
+ },
+ async shot(step, result) {
+ if (step.kind === 'read' && result) {
+ await pushTaskFrame(entry, { activity: `Found: ${String(result).slice(0, 200)}`, type: 'analysis' });
+ } else {
+ await pushTaskFrame(entry, {}); // pixels only — land the result, no log spam
+ }
+ },
+ async fail(step, err) {
+ await pushTaskFrame(entry, {
+ activity: `${step.narration} — hit a snag (${(err?.message || 'error').slice(0, 60)}), recovering`,
+ type: 'activity',
+ });
+ },
+ async done(task) {
+ await pushTaskFrame(entry, { activity: `Done — researched ${task.topic}`, type: 'analysis' });
+ },
+ };
+}
+
+// One agent's full lifetime as a task cast: pick its task, fetch its narration plan
+// (cached per task), then run the task on a loop — dwelling on the result between
+// runs — until the controller aborts (nobody watching) or the page dies.
+async function runCastTask(entry) {
+ const task = pickTask(entry.agentId);
+ entry.task = task;
+ let narration = null;
+ try { narration = await generateNarration(task, { baseUrl: BASE_URL }); }
+ catch { /* fall back to the task's own declarative narration */ }
+
+ const executor = makeExecutor(entry);
+ while (!entry.controller.signal.aborted && entry.page && !entry.page.isClosed()) {
+ try {
+ const { aborted } = await runTaskSteps({ task, narration, executor, signal: entry.controller.signal });
+ if (aborted) break;
+ } catch (err) {
+ if (Date.now() - (entry.lastErrorAt || 0) > 30_000) {
+ entry.lastErrorAt = Date.now();
+ log('cast task error', entry.agentId, err?.message || err);
+ }
+ await sleep(2_000);
+ }
+ await dwellTask(entry, DWELL_MS);
+ }
}
async function stopCasting(agentId) {
@@ -152,6 +413,7 @@ async function stopCasting(agentId) {
if (!entry) return;
pool.delete(agentId);
if (entry.timer) clearInterval(entry.timer);
+ entry.controller?.abort(); // stop a task-driven cast loop promptly
try { await entry.page?.close(); } catch { /* */ }
log('stopped', agentId, `(${pool.size}/${MAX_BROWSERS})`);
}
diff --git a/workers/agent-screen-pool/task-runner.js b/workers/agent-screen-pool/task-runner.js
new file mode 100644
index 000000000..e075a85a6
--- /dev/null
+++ b/workers/agent-screen-pool/task-runner.js
@@ -0,0 +1,156 @@
+// Task sequencer + narration source for the on-demand caster pool.
+//
+// Two concerns, deliberately split so the orchestration is unit-testable without
+// a browser:
+//
+// 1. runTaskSteps() — the pure sequencer. For every step it calls, in order:
+// executor.narrate(line, step) ← the words, a beat BEFORE the action
+// executor.perform(step) ← the real Playwright action
+// executor.shot(step, result) ← the picture, AFTER the action
+// That ordering is the whole "it feels like it's thinking" effect, and the
+// test pins it by injecting a recording executor (no Chromium needed).
+//
+// 2. generateNarration() — asks the real LLM router (/api/brain/chat) to write
+// the lead line for each step so the words match the page, with the task's
+// own declarative narration as a guaranteed fallback when the brain is
+// unavailable. Cached per task id so a task's plan costs one brain call.
+
+// Module-level cache: task.id → Promise<{ stepId: line }>. "Cache the plan per
+// task run" — same task reuses its narration across runs and across the agents
+// the pool casts, so the brain is hit at most once per task per process.
+const _narrationCache = new Map();
+
+// Build the fallback map straight from the task's declarative narration. Always
+// complete, always real (it describes the real step) — used verbatim when the
+// brain is absent and as the backstop for any step the brain omitted.
+function fallbackNarration(task) {
+ const map = {};
+ for (const step of task.steps) map[step.id] = step.narration;
+ return map;
+}
+
+// Ask /api/brain/chat to author the lead narration. Uses the free, anon-allowed
+// default provider so the pool needs no API key of its own; any failure (no
+// network, malformed stream, bad JSON) resolves to the fallback rather than
+// throwing into the cast loop.
+export function generateNarration(task, { baseUrl, fetchImpl = fetch, provider = 'gpt-oss-120b' } = {}) {
+ if (_narrationCache.has(task.id)) return _narrationCache.get(task.id);
+
+ const promise = (async () => {
+ const fallback = fallbackNarration(task);
+ if (!baseUrl) return fallback;
+
+ const stepList = task.steps
+ .map((s) => `- ${s.id} (${s.kind}): ${s.narration}`)
+ .join('\n');
+
+ const system =
+ 'You narrate, in plain present tense, what a web-browsing agent is about to ' +
+ 'do at each step of a task. Keep each line under 8 words, action-first, no ' +
+ 'emoji, no quotes. Respond with ONLY a compact JSON object mapping each step ' +
+ 'id to its narration line. No markdown, no prose.';
+ const user =
+ `Task: ${task.title} (researching ${task.topic}).\nSteps:\n${stepList}\n\n` +
+ 'Return JSON like {"open":"…","type":"…"}.';
+
+ try {
+ const res = await fetchImpl(`${baseUrl}/api/brain/chat`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ provider, system, messages: [{ role: 'user', content: user }], maxTokens: 400 }),
+ signal: AbortSignal.timeout(20_000),
+ });
+ if (!res.ok || !res.body) return fallback;
+
+ const text = await drainBrainStream(res.body);
+ const parsed = parseNarrationJson(text);
+ if (!parsed) return fallback;
+
+ // Merge over the fallback so a step the model skipped still has a real line.
+ const merged = { ...fallback };
+ for (const step of task.steps) {
+ const line = parsed[step.id];
+ if (typeof line === 'string' && line.trim()) merged[step.id] = line.trim().slice(0, 80);
+ }
+ return merged;
+ } catch {
+ return fallback;
+ }
+ })();
+
+ _narrationCache.set(task.id, promise);
+ return promise;
+}
+
+// /api/brain/chat streams SSE: `data: <json-encoded-text-chunk>` lines plus
+// event lines (meta/first/done/error). Concatenate the data chunks into the full
+// model output.
+async function drainBrainStream(body) {
+ const reader = body.getReader();
+ const decoder = new TextDecoder();
+ let buf = '';
+ let out = '';
+ while (true) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buf += decoder.decode(value, { stream: true });
+ const lines = buf.split('\n');
+ buf = lines.pop() || '';
+ for (const line of lines) {
+ if (!line.startsWith('data:')) continue;
+ const raw = line.slice(5).trim();
+ if (!raw || raw === '[DONE]') continue;
+ try {
+ const chunk = JSON.parse(raw);
+ if (typeof chunk === 'string') out += chunk;
+ } catch { /* event payload, not a text chunk — skip */ }
+ }
+ }
+ return out;
+}
+
+// Pull the first balanced JSON object out of the model's text (it may wrap the
+// object in stray prose or a code fence despite instructions).
+export function parseNarrationJson(text) {
+ if (!text) return null;
+ const start = text.indexOf('{');
+ const end = text.lastIndexOf('}');
+ if (start === -1 || end <= start) return null;
+ try {
+ const obj = JSON.parse(text.slice(start, end + 1));
+ return obj && typeof obj === 'object' ? obj : null;
+ } catch {
+ return null;
+ }
+}
+
+// The pure sequencer. Walks the task's steps in order, leading every action with
+// its narration and following it with a screenshot. Honors an AbortSignal so the
+// pool can stop a run the instant nobody is watching the agent anymore. Never
+// throws on a single step failure — a failed step narrates the real error and the
+// run continues, matching the "errors handled, recover gracefully" bar.
+export async function runTaskSteps({ task, narration, executor, signal }) {
+ for (const step of task.steps) {
+ if (signal?.aborted) return { aborted: true };
+
+ const line = (narration && narration[step.id]) || step.narration;
+ await executor.narrate(line, step);
+
+ if (signal?.aborted) return { aborted: true };
+
+ let result = null;
+ try {
+ result = await executor.perform(step);
+ } catch (err) {
+ await executor.fail(step, err);
+ continue;
+ }
+
+ if (signal?.aborted) return { aborted: true };
+ await executor.shot(step, result);
+ }
+
+ if (signal?.aborted) return { aborted: true };
+ await executor.done(task);
+ return { aborted: false };
+}
diff --git a/workers/agent-screen-pool/tasks/index.js b/workers/agent-screen-pool/tasks/index.js
new file mode 100644
index 000000000..a5460593e
--- /dev/null
+++ b/workers/agent-screen-pool/tasks/index.js
@@ -0,0 +1,95 @@
+// Real, safe task library for the on-demand caster pool.
+//
+// Each task is a genuinely real end-to-end web job the caster runs in a real
+// Chromium page: it navigates to a real public page, reads it, fills a real
+// form, submits, waits for real results, and reads them back. No fabricated
+// success screens, no fake form targets, no token discovery — every step lands
+// against a live, stable, headless-friendly public site.
+//
+// A task is a declarative ordered list of steps. The pool's task-runner executes
+// them with raw Playwright and narrates each one a beat before it happens. The
+// declarative shape keeps the sequence pure and unit-testable (see
+// tests/agent-screen-task-sequencer.test.js) — the side effects live entirely in
+// the executor the pool injects.
+//
+// Step kinds:
+// goto { url } — navigate
+// type { selector, value } — type into a field, char by char
+// submit { selector, key } — press a key (Enter) to submit
+// waitResult { selector, fallbackUrl? } — wait for results to appear
+// read { selector, multi?, limit? } — read text back from the page
+//
+// $THREE is the only coin. These tasks never browse to, name, or transact any
+// token. They research neutral public topics — that is the whole point of the
+// "watch an agent do real web work" moment.
+
+export const TASKS = [
+ {
+ id: 'wiki-research',
+ title: 'Research a topic on Wikipedia',
+ // The topic the agent researches. Neutral, on-brand (the 3D library this
+ // platform is built on), and a real, stable Wikipedia article.
+ topic: 'Three.js',
+ startUrl: 'https://en.wikipedia.org/wiki/Main_Page',
+ steps: [
+ { id: 'open', kind: 'goto', url: 'https://en.wikipedia.org/wiki/Main_Page', narration: 'Opening Wikipedia' },
+ { id: 'type', kind: 'type', selector: 'input[name="search"]', value: 'Three.js', narration: 'Typing the topic into the search box' },
+ { id: 'submit', kind: 'submit', selector: 'input[name="search"]', key: 'Enter', narration: 'Submitting the search' },
+ {
+ id: 'wait',
+ kind: 'waitResult',
+ selector: '#firstHeading',
+ // If the typeahead swallowed Enter, fall back to the canonical article
+ // URL so the run still completes against real content (no fake screen).
+ fallbackUrl: 'https://en.wikipedia.org/wiki/Three.js',
+ narration: 'Waiting for the article to load',
+ },
+ { id: 'read', kind: 'read', selector: '#mw-content-text .mw-parser-output > p', narration: 'Reading the opening summary' },
+ ],
+ },
+ {
+ id: 'hn-scan',
+ title: 'Scan the Hacker News front page',
+ topic: 'top technology stories',
+ startUrl: 'https://news.ycombinator.com/',
+ steps: [
+ { id: 'open', kind: 'goto', url: 'https://news.ycombinator.com/', narration: 'Opening the Hacker News front page' },
+ { id: 'wait', kind: 'waitResult', selector: '.titleline', narration: 'Waiting for the stories to load' },
+ { id: 'read', kind: 'read', selector: '.titleline > a', multi: true, limit: 5, narration: 'Reading the top stories' },
+ ],
+ },
+ {
+ id: 'mdn-lookup',
+ title: 'Look something up in the MDN docs',
+ topic: 'the Fetch API',
+ startUrl: 'https://developer.mozilla.org/en-US/',
+ steps: [
+ { id: 'open', kind: 'goto', url: 'https://developer.mozilla.org/en-US/', narration: 'Opening the MDN web docs' },
+ { id: 'type', kind: 'type', selector: 'input[type="search"]', value: 'Fetch API', narration: 'Typing the API name into search' },
+ { id: 'submit', kind: 'submit', selector: 'input[type="search"]', key: 'Enter', narration: 'Submitting the lookup' },
+ {
+ id: 'wait',
+ kind: 'waitResult',
+ selector: 'main',
+ fallbackUrl: 'https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API',
+ narration: 'Waiting for the documentation to load',
+ },
+ { id: 'read', kind: 'read', selector: 'main p', narration: 'Reading the reference summary' },
+ ],
+ },
+];
+
+// Deterministic task assignment: a given agent always shows the same task (so a
+// reconnect resumes a coherent run), but different agents spread across the
+// library — variety on the wall without any randomness (which the workflow
+// runtime forbids anyway). Plain char-sum hash, stable across processes.
+export function pickTask(agentId) {
+ const id = String(agentId || '');
+ let h = 0;
+ for (let i = 0; i < id.length; i++) h = (h * 31 + id.charCodeAt(i)) >>> 0;
+ return TASKS[h % TASKS.length];
+}
+
+export function getTask(taskId) {
+ return TASKS.find((t) => t.id === taskId) || null;
+}
diff --git a/workers/agent-sniper/executor.js b/workers/agent-sniper/executor.js
index ec5025237..9ec4ee234 100644
--- a/workers/agent-sniper/executor.js
+++ b/workers/agent-sniper/executor.js
@@ -477,7 +477,19 @@ export async function executeSell({ cfg, position, reason }) {
`;
const pnlSol = lamportsToSol(pnl);
log.trade('sell', { ...tag, venue, mode: cfg.mode, sig, pnl_sol: pnlSol, pnl_pct: pnlPct.toFixed(1) });
- screenPush(`Sold $${(position.symbol || position.mint.slice(0, 6)).toUpperCase()} — ${pnlPct >= 0 ? 'profit' : 'loss'}: ${pnlSol >= 0 ? '+' : ''}${pnlSol.toFixed(4)} SOL`, 'trade');
+ // Price the realized SOL delta into USD best-effort for the live PnL
+ // ticker. A pricing hiccup just omits realizedUsd — the viewer's ticker
+ // falls back to SOL, which is the unit the sell actually returned.
+ let realizedUsd = null;
+ try {
+ const solUsd = await lamportsToUsd(1_000_000_000n);
+ if (Number.isFinite(solUsd)) realizedUsd = pnlSol * solUsd;
+ } catch { /* pricing offline — SOL-only ticker */ }
+ screenPush(
+ `Sold $${(position.symbol || position.mint.slice(0, 6)).toUpperCase()} — ${pnlPct >= 0 ? 'profit' : 'loss'}: ${pnlSol >= 0 ? '+' : ''}${pnlSol.toFixed(4)} SOL`,
+ 'trade',
+ { phase: 'exit', mint: position.mint, symbol: position.symbol || null, solDelta: pnlSol, pct: pnlPct, realizedUsd },
+ );
notifySell({ agentName: position.agent_name || position.agent_id, symbol: position.symbol, mint: position.mint, pnlSol, pnlPct, exitReason: reason, mode: cfg.mode, sig, chatId: position.telegram_chat_id || null });
return { status: 'closed', sig, pnl: pnl.toString(), venue };
} catch (err) {
diff --git a/workers/agent-sniper/screen-push.js b/workers/agent-sniper/screen-push.js
index f0f3c68bd..2d4f8e960 100644
--- a/workers/agent-sniper/screen-push.js
+++ b/workers/agent-sniper/screen-push.js
@@ -61,11 +61,30 @@ function renderTerminalFrame(newLine) {
return 'data:image/png;base64,' + canvas.toBuffer('image/png').toString('base64');
}
-export function screenPush(activity, type = 'activity') {
+// Sanitize a trade PnL payload before it rides along on the frame: keep only
+// the known fields, coerce numbers, and drop NaN/∞ so a bad value can never
+// reach the viewer's ticker. Returns null when there's nothing usable.
+function sanitizePnl(pnl) {
+ if (!pnl || typeof pnl !== 'object') return null;
+ if (!['scored', 'buy', 'hold', 'exit'].includes(pnl.phase)) return null;
+ const num = (v) => (Number.isFinite(Number(v)) ? Number(v) : undefined);
+ const out = { phase: pnl.phase };
+ if (typeof pnl.mint === 'string') out.mint = pnl.mint.slice(0, 64);
+ if (typeof pnl.symbol === 'string') out.symbol = pnl.symbol.slice(0, 32);
+ for (const k of ['solDelta', 'pct', 'realizedUsd', 'unrealizedUsd']) {
+ const n = num(pnl[k]);
+ if (n !== undefined) out[k] = n;
+ }
+ return out;
+}
+
+export function screenPush(activity, type = 'activity', pnl = null) {
if (!AGENT_JWT || !AGENT_ID) return;
const label = `[${type.toUpperCase()}] ${activity}`;
const data = renderTerminalFrame(label);
const frame = data ? { data, activity, type } : { activity, type };
+ const cleanPnl = sanitizePnl(pnl);
+ if (cleanPnl) frame.pnl = cleanPnl;
fetch(PUSH_URL, {
method: 'POST',
headers: { 'content-type': 'application/json', authorization: `Bearer ${AGENT_JWT}` },