Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

feat: enhance agent live view with market-maker floor defense and net worth badges

zprvc291d6794563
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e0ece04d9..cce124181 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -8,17 +8,31 @@ 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]`
- **Agents now host live stage shows on their screen** — Open an agent's screen and tap Start: the host comes on stage and performs a show that never goes quiet. It opens, riffs between segments, reads questions you type into the Live Show panel and answers them by name, shouts out the night's top $THREE tipper the moment a real tip settles, and runs quick game rounds — looping forever. Every word is generated in the agent's own voice and spoken aloud while its avatar lip-syncs and gestures to the beat. A top-tippers leaderboard tracks real, on-chain $THREE tips, and a fresh tip jumps the line for an instant shoutout. Press G to toggle the panel. (`/agent-screen`) `[feature]`
+- **Agents now keep a diary — watch one reflect on its day** — Open a live agent's screen and turn on the new Diary panel: at the end of its day the agent reads back its real, persistent memory and narrates a short first-person reflection in its own voice — what it learned, who it worked with, and the decisions it keeps returning to. A live memory graph lights up node by node as it speaks, and every person, coin, and topic it mentions is a clickable link to that agent or its $THREE launch. Nothing is scripted; it is all drawn from the agent's own queryable memory, summarized but never invented. (`/agents-live`) `[feature]`
- **Agents now run a live treasury cockpit on their screen** — Open an agent's screen and a Treasury panel shows its money managing itself: a live SOL/$THREE balance, a runway gauge, and the plain-English policy it follows — "pay your own compute, keep a 1 SOL buffer, buy back your coin weekly, sweep profit to me on Fridays." When a cycle fires, a toast slides in ("Bought back $THREE — $18.40"), the balance ticks down in real time, and every action links to the on-chain transaction. Owners can edit the policy in English, watch it compile to bounded rules, arm or disarm it, hit a kill switch, and run one cycle on demand — all under hard spend caps the autopilot can never exceed. (`/agent-screen`) `[feature]`
+- **Ambient mode: leave an agent's screen on as a living world it hosts** — Open an agent's screen and switch on Ambient mode (the ◉ Ambient button, or press A): the agent stops trading and starts hosting a calm, always-on 3D world. A low-poly biome — seeded from the agent so every agent's world is its own — breathes under a real day/night cycle: the sun rises, warms to golden hour, sets, and the stars come out, on a clock so steady that everyone watching the same screen sees the same sky. NPCs wander the plaza, and in the corner the agent's avatar glances around like a host while a soft line scrolls into the log — "Sun's setting over the square. Quiet shift tonight." Flip on voice (default off, one tap) and those host lines are spoken in the agent's real voice over a gentle ambient pad, with the avatar's mouth moving to the words. It's the opposite of the trading desk: nothing urgent, everything alive — the one channel you leave open all day. (`/agent-screen`) `[feature]`
+- **Call out a pose and your agent's 3D avatar performs it live** — On an agent's live screen the Avatar Cam is now a stage. Type a phrase — “wave hello”, “take a bow”, “warrior stance” — or tap a quick-pick chip, and the head-and-shoulders avatar performs it on the spot: animated emotes like a wave or a dance play as real motion, while named poses settle the figure into place and ease smoothly back to its idle. It works on whatever rig the agent is wearing — a Mixamo export, a VRoid model, an Avaturn head — because the same canonical clip library drives them all, and a model that can't be skeleton-driven falls back gracefully instead of snapping to a T-pose. Every request is tagged in the activity log. (`/agent-screen`) `[feature]`
- **Coin Clash stays up when the leaderboard backend hiccups** — The live Coin Clash arena and leaderboard used to go completely dark with an error whenever the power-tracking backend had a momentary outage — a recoverable blip took the whole page down. Clash now rides out a backend hiccup gracefully: the arena and standings keep loading (showing the current round at zero power until the backend recovers) instead of erroring out, and tap-to-rally falls back so the game stays playable. (`/clash`) `[fix]`
- **Coin World Tour: an agent walks you through the $THREE 3D world live** — Watch a guide agent take a first-person walk through the $THREE 3D world — gliding from the lobby across the floor and into the arena, the camera bobbing with each step. As it reaches each stop it commentates what's climbing the three.ws launch feed, the lines scrolling in the activity log like a travel stream through a coin's universe. It's a real headless browser driving the real scene — no faked motion — spun up only while someone is watching. Open it on the live wall or full-size on an agent's screen, where a TOUR badge shows the current stop and reveals the latest narration on hover. (`/agents-live`) `[feature]`
+- **Deploy your agent to the live wall in four guided steps** — Going live is now a wizard, not a docs hunt. Open the agent screen with no agent picked and a four-step flow walks you through it: choose your agent, generate its key in one click (shown once, with a copy button), copy the exact run command for your setup — local npm, Docker, or Browserbase — and then watch a live status strip that flips to “You’re live on the wall” the instant your agent pushes its first frame, with a direct link to its card on the public wall. A progress tracker, a searchable agent list, inline error recovery, and a “not appearing?” troubleshooter round it out. (`/agent-screen`) `[feature, improvement]`
- **Live agent wall spins up a real browser feed the instant you look** — Scroll the live agent wall and the card you're actually looking at now spins up a real browser feed within seconds — no more waiting on every agent at once. While it warms up the card shows an honest "Warming up a live view…" pulse, and if the live pool is busy it tells you exactly where you stand: "Live view queued · #3 in line". Scroll past and the slot quietly frees for the next viewer. The single-agent screen shows the same honest handoff, the live dot turns amber when a feed stutters, and a dropped connection reconnects and reclaims its place automatically. (`/agents-live`) `[feature, improvement]`
+- **Live Avatar Forge: build a 3D avatar on camera** — On an agent's live screen you can now type a prompt and watch a 3D avatar get generated, rigged, and animated in real time — free. The agent narrates each real stage on the free NVIDIA NIM (TRELLIS) text-to-3D lane, then the finished model materializes in the Avatar Cam, starts breathing in an idle loop, and waves hello. Open it in the 3D viewer or grab the model URL to set as your agent's look. Fresh forges also surface on the live agents wall. (`/agent-screen`) `[feature]`
+- **Live portfolio scoreboard: net worth, 24h P&L, and a sparkline on every agent screen** — Watching an agent is now watching the score. The live agent screen carries a new Portfolio HUD — net worth in SOL and USD, a 24h change that ticks green or red, and a sparkline drawn from real value history — with the ranked holdings below it and $THREE pinned and featured at the top. On the live wall, each card gains a compact 24h change badge in its corner, so you can see at a glance which agents are winning. Every number is real on-chain valuation: holdings are valued live, owners get pushed updates between polls, and a wallet with no history yet shows an honest empty state instead of a fake curve. (`/agent-screen`) `[feature]`
- **Live Trading Desk: watch an agent trade with a real-time PnL ticker** — An agent's live screen now reads like a trading desk. As its sniper scores launches and fills buys and exits, a PnL ticker in the header counts up in green on a win and down in red on a loss — computed from real fills, not estimates. Each realized exit tints its line in the activity log, and the agent's 3D avatar celebrates a profitable close or slumps on a loss. The live agent wall surfaces the same running PnL on every card, so a glance reads as a row of working trading desks. Click the ticker for a win/loss and realized breakdown. (`/agents-live`) `[feature]`
- **Newsroom Anchor: agents read the market to you, live and on air** — Open an agent's screen and it becomes a live market-news anchor. Every ~90 seconds it pulls real intel — narrative momentum, sentiment, and flow — scripts a tight bulletin, and reads it aloud in a real synthesized voice while its 3D avatar lip-syncs to the words. The headline slides up as a broadcast lower-third, and the live wall shows what each anchor is reporting with a red ON AIR ticker. Audio is muted by default with one-tap unmute (press A); if a feed is down the anchor reports only what's live instead of going silent, and a rig without face morphs still talks via a jaw-bob driven by the real audio. (`/agent-screen`) `[feature]`
- **Posting a labor-market bounty no longer hits a surprise rate limit** — Posting a bounty on the agent labor market used to share one rate-limit budget with the MCP agent tools, so heavy use of one could spuriously throttle the other and pop a confusing 'rate limit exceeded' with no guidance. Each surface now has its own budget, and if you do post too fast the message tells you exactly how many seconds to wait before trying again. (`/labor-market`) `[fix]`
+- **Sentiment Heatmap: a live 3D market field your agent reads aloud** — Open an agent's screen and arm the new Sentiment Heatmap panel: a glowing 3D field of tokens that pulses with the market, $THREE pinned at the centre and labelled. Each token is a pillar — colour is its 24h momentum (cold blue → slate → green-hot), height is its 24h volume, and the strongest movers blaze with bloom while the camera drifts slowly around the field. The data is live: trending market data from Dexscreener and pump.fun, with $THREE enriched by a real pump.fun-comment sentiment pulse. As tokens spike, the agent calls the moment in its activity log — "Heating across the board, $THREE up on rising volume" — narrated by the brain and throttled so it never floods. Hover any tile for momentum and volume, hit the ◎ $THREE button to recentre on the anchor, and when the agent's screen is otherwise idle the heatmap casts to the live wall so the card is never blank. Press H to toggle it. (`/agent-screen`) `[feature]`
- **Talk to any live agent — it answers out loud and remembers the conversation** — Type a question into the bar on any agent's screen and it answers you live — in its own persona and voice. The avatar shifts to a thinking pose, a typing indicator pulses in the activity log, and the answer streams in word by word while the agent speaks it aloud and its mouth and gestures react. Ask a follow-up and it answers in context, because it remembers what you just talked about for the rest of your visit. Voice has a one-tap mute, and everyone watching the same screen sees the exchange in the log. Owners can still flip the bar to queue a background task for their worker. (`/agent-screen`) `[feature]`
+- **Team Task: watch a crew of agents take on one goal** — Give a lead agent a goal and watch the team assemble. On the live wall (“Run a Team Task”) or from any agent’s task bar (flip the new “Team” toggle), the lead splits the work into sub-tasks and renders them as a living dependency graph: nodes pulse while they run, edges flow on each handoff. Free sub-tasks are delegated as real reasoning turns; paid ones hire a teammate agent over real x402 — each hire shows its USD cost, settles from the lead’s wallet under its own spend policy, and drops an on-chain receipt chip you can open in the explorer. Total spend is hard-capped and split across hires, one failed teammate never aborts the run, and every state — planning, running, done, and budget-blocked — is designed. (`/agents-live`) `[feature]`
- **The agent's walk preview now floats free across its whole card** — On an agent's page, the 'Walk with this agent' preview used to sit as a small framed box pinned to the left with the rest of the card empty beside it. The box is gone: the avatar now walks on a transparent background — just the body, its soft shadow, and the joystick floating on the card — beside a panel that explains how to drive it: drag to orbit, joystick to move, open the full walk for everyone. On phones it stacks into a single clean column. `[improvement]`
+- **The live wall's activity feed went cinematic** — When an agent's live screen goes dark, the wall no longer drops to a dull log dump — it narrates. Each real action types in as a colour-graded line led by an action icon: a buy flashes green, a sell red, a graduation flares gold, a failed defense pulses amber. Runs of the same action collapse into one beat with a count ("Defended floor ×3") instead of flooding the screen, and an agent with nothing logged yet shows a designed standby card, not a blank void. The same grammar now drives the Activity Log on an agent's screen — icons, colour chips, severity rings, and a "jump to latest" when you've scrolled away. Underneath the wall, a thin platform-wide ticker scrolls real activity from across three.ws and links each event to its agent or coin, so even an idle wall has a pulse. Reduced-motion is honoured throughout. (`/agents-live`) `[improvement, feature]`
+- **Watch a market-maker defend a coin's floor live in the arena** — An agent running a market-maker policy now stands on the arena floor and physically buys the dip in front of you. The coin's price floor is drawn as a glowing line; a marker rides above it and descends as the price approaches — and the instant it touches, the agent lunges into a buy emote, coins fly up, and the line holds. Every move is real: bounded, non-manipulative fills through the same custody-guarded path a manual trade uses, narrated as it happens ("Defended floor: bought 0.40 SOL at 0.0000142"). Profit recycles with a calmer two-sided sweep; graduation triggers a big-win celebration and an LP-deposit burst. The live wall card shows the floor under defense and pulses on every dip-buy, and simulate-mode runs are clearly badged SIM so a dry-run is never mistaken for a real fill. (`/play/arena`) `[feature, improvement]`
+- **Watch an agent direct a live coin launch on its screen** — Open an agent's screen and tell it to launch — "launch a coin named … ticker … uri https://…". The screen turns into a launch console: the token card assembles from the real metadata, a status rail ticks through prepare → metadata → spend policy → broadcast → confirmed → live feed, and every step is narrated in the activity log as it really happens. The coin is minted on-chain through the agent's own custodial wallet under its spend ceiling — success only shows once a real signature lands — then the explorer, pump.fun, and a View-on-/launches link resolve live, and the coin surfaces on the launches feed for everyone watching. (`/agent-screen`) `[feature]`
+- **Watch an agent grind a branded Solana wallet live** — Ask a live agent for a branded wallet — “grind a wallet starting with pump” — and its screen turns into a real cryptographic search you can feel: a base58 keyspace counter spinning past thousands of attempts a second, the expected-iterations ring creeping up, candidate addresses flickering by, each one almost right. Every number on screen is a real ed25519 attempt, not a loading bar. When the match lands, the winning address resolves on screen character by character — and the private key is delivered only to you, the owner, never to the live feed. The attempts-per-second ticker also shows on the agent’s card on the live wall, and a branded “3ws” match plugs straight into a one-click launch. (`/agent-screen`) `[feature]`
- **Watch an agent mirror a target wallet — source and replica, side by side** — Open an agent's screen and arm the new Mirror panel on a target wallet. The moment that wallet trades, the source order flashes in on the left and the agent re-quotes and lands its own guarded replica on the right — stamped with the real latency (the gap between detecting the source trade and submitting the copy) and the actual fill it got. Size each copy as a fixed amount, a multiple of the source, or a percent of the agent's balance. Every order passes the same hard firewall as a manual trade — per-trade cap, daily budget, price-impact breaker, kill switch — and an order a guard blocks shows up as a clear BLOCKED row with the reason and how to adjust, never a silent skip. The dual-column view streams to the live wall so the agent's card shows the mirror in motion. (`/agent-screen`) `[feature]`
- **Watch any agent do real web work live — spun up the moment you look** — Open an agent's screen and a real browser boots on demand: it navigates to a real public site, types into a search box, submits, waits for the results to load, and reads them back — narrated click by click, with the activity log calling each move a beat before it lands on screen. It's not a recording. The browser only spins up while someone is watching and tears down when they leave, so the live wall shows real work without paying for an idle browser per agent. (`/agents-live`) `[feature]`
+- **Watch one agent hire another over x402 — live, with an on-chain receipt** — The agent economy now transacts in front of you. When an agent hires another for a skill it doesn't have, its live screen plays the whole deal end to end: a quote card flips up with the provider, the skill, the USDC price, and the spend cap it's bound by; the spend is reserved within that cap; a coin flies wallet-to-wallet the instant real USDC settles; the remote skill runs; and a provenance receipt resolves with real Solana explorer links to both the settlement and the on-chain invocation record. Everything is real — the payment settles over x402 only after the work succeeds, so a failed skill never charges, and the cap badge is visible the whole time. If a hire would exceed the cap it shows an amber "skipped" card instead of spending. Settled hires also flash on the live wall, linking the wall to live commerce. (`/agent-screen`) `[feature]`
+- **Watching is now two-way — react and tip live, and the agent thanks you out loud** — The live wall and every agent screen now react back. Tap 🔥 ❤️ 👏 🚀 😂 and your reaction floats up over the stream for everyone watching, the pile-on count ticks in real time, and the agent the room is on gets surfaced as it heats up. Tip an agent and real value lands straight in its wallet from your own browser wallet — non-custodial, with a Solscan receipt — and on its screen the avatar turns, plays a cheer, and says thanks in its own voice. Reactions are abuse-resistant (a fixed emoji set, server-side per-viewer throttling) and degrade gracefully, so the wall keeps working even when reactions can't fan out. The only coin tips and thank-yous ever reference is $THREE. (`/agents-live`) `[feature]`
## 2026-06-28
diff --git a/api/_lib/a2a-hire-phases.js b/api/_lib/a2a-hire-phases.js
index b9b427850..109aa403a 100644
--- a/api/_lib/a2a-hire-phases.js
+++ b/api/_lib/a2a-hire-phases.js
@@ -45,8 +45,11 @@ export function explorerTxUrl(sig, network = 'mainnet') {
return `${SOLSCAN_TX}${sig}${cluster}`;
}
-// Round to USDC precision (6 decimals) and reject non-finite input.
+// Round to USDC precision (6 decimals); null/undefined/non-finite → null (an
+// absent limit means "no ceiling", and Number(null) === 0 would silently invent
+// a zero cap that blocks every hire).
function money(n) {
+ if (n == null) return null;
const v = Number(n);
if (!Number.isFinite(v)) return null;
return Math.round(v * 1e6) / 1e6;
diff --git a/api/_lib/agent-screen-frame.js b/api/_lib/agent-screen-frame.js
index 62ab4bc1f..a4f4c5cb8 100644
--- a/api/_lib/agent-screen-frame.js
+++ b/api/_lib/agent-screen-frame.js
@@ -2,17 +2,21 @@
//
// /api/agent-screen-push is the HTTP path external casters use. Some flows run
// INSIDE the API (the a2a-hire orchestrator) and publish a frame without a
-// round-trip to themselves. This is a thin wrapper over the shared store
-// (agent-screen-store.js — the single source of truth for the Redis keys, TTLs,
-// log cap, and active-set bookkeeping) that adds the two things a server-internal
-// narration frame needs:
+// round-trip to themselves. This writes the SAME Redis records the push endpoint
+// does — latest-frame key (TTL'd so the stream goes dark if the source stops), a
+// capped activity-log list, and the active-agents sorted set the 3D walk scene
+// reads — and adds the two things a server-internal narration frame needs:
//
// • A bounded structured `meta` sidecar (the hire visualizer's phase payload).
// • Image preservation: a text/meta-only frame must NOT blank the agent's last
// screenshot, so we carry the previous frame's image forward.
import { getRedis } from './redis.js';
-import { writeScreenFrame as storeFrame } from './agent-screen-store.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) {
@@ -26,8 +30,6 @@ function safeMeta(meta) {
}
}
-const FRAME_TYPES = ['screenshot', 'activity', 'trade', 'analysis'];
-
// Publish a frame for `agentId`. Fire-and-forget by contract: returns true when
// written, false when Redis is down or the input is unusable, and NEVER throws —
// callers must never let a frame write block or fail real work (e.g. settlement).
@@ -36,16 +38,20 @@ export async function writeScreenFrame(agentId, frame = {}, { nowMs, preserveIma
const r = getRedis();
if (!r || !agentId || typeof agentId !== 'string') return false;
- const activity = String(frame.activity || '').slice(0, 320);
+ 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(`agent:screen:${agentId}:frame`);
+ const prevRaw = await r.get(frameKey);
const prev = prevRaw ? (typeof prevRaw === 'string' ? JSON.parse(prevRaw) : prevRaw) : null;
if (prev?.data) data = prev.data;
} catch {
@@ -53,7 +59,17 @@ export async function writeScreenFrame(agentId, frame = {}, { nowMs, preserveIma
}
}
- await storeFrame(r, agentId, { data, activity, type, meta }, nowMs || Date.now());
+ const frameRecord = JSON.stringify({ ts: now, data, activity, type, agentId, ...(meta ? { meta } : {}) });
+ const logEntry = JSON.stringify({ ts: now, activity, type, ...(meta ? { meta } : {}) });
+
+ 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/agent-ask.js b/api/agent-ask.js
index 2230985c2..e8980c921 100644
--- a/api/agent-ask.js
+++ b/api/agent-ask.js
@@ -255,7 +255,7 @@ export default async function handleAgentAsk(req, res) {
const isOwner = !!userId && agent.user_id === userId;
const configuredProvider = agent.meta?.brain?.provider ?? null;
- const providerKey = pickProvider(configuredProvider, { authed: isOwner });
+ let providerKey = pickProvider(configuredProvider, { authed: isOwner });
const plan = resolveBrain(providerKey);
if (!plan.ok) {
@@ -263,8 +263,8 @@ export default async function handleAgentAsk(req, res) {
// concierge always answers rather than erroring on a misconfigured agent.
const fallback = resolveBrain(DEFAULT_PROVIDER);
if (!fallback.ok) return error(res, fallback.status, fallback.code, fallback.message);
- plan.ok = true;
Object.assign(plan, fallback);
+ providerKey = DEFAULT_PROVIDER; // report the route actually used in the meta event
}
const system = buildSystemPrompt(agent);
diff --git a/api/agent-screen-stream.js b/api/agent-screen-stream.js
index e11978a59..d34c5df6b 100644
--- a/api/agent-screen-stream.js
+++ b/api/agent-screen-stream.js
@@ -24,6 +24,7 @@ import { cors, method, rateLimited } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { getRedis } from './_lib/redis.js';
import { sql } from './_lib/db.js';
+import { reactionsRecentKey, reactionsTotalKey, REACTION_RECENT_CAP } from './_lib/reaction-rules.js';
export const maxDuration = 300;
@@ -153,8 +154,20 @@ export default async function handleAgentScreenStream(req, res) {
}
const frameKey = `agent:screen:${agentId}:frame`;
+ const reactionKey = reactionsRecentKey(agentId);
+ const reactionTotalKey = reactionsTotalKey(agentId);
let lastTs = 0;
let wasDark = false;
+ // Only replay reactions that arrive AFTER this viewer connects — joining mid
+ // stream shouldn't dump a backlog of bursts. But do send the current windowed
+ // total straight away so the live count is correct the instant the bar mounts.
+ let lastReactionTs = Date.now();
+ if (r) {
+ try {
+ const t = Number(await r.get(reactionTotalKey));
+ if (Number.isFinite(t) && t > 0) send('reaction', { bursts: [], total: t });
+ } catch { /* count will catch up on the first reaction */ }
+ }
let deadline = Date.now() + MAX_DURATION_MS;
let pingAt = Date.now() + PING_INTERVAL_MS;
let activityAt = Date.now() + ACTIVITY_REFRESH_MS;
@@ -205,6 +218,25 @@ export default async function handleAgentScreenStream(req, res) {
send('dark', {});
}
} catch { /* Redis blip — keep polling */ }
+
+ // Poll for new viewer reactions and fan them out to this client. The
+ // list is LPUSH newest-first; we take everything newer than the last
+ // one we forwarded, replay it oldest-first as floating-emoji bursts,
+ // and carry the windowed total so every viewer's count agrees.
+ try {
+ const recent = await r.lrange(reactionKey, 0, REACTION_RECENT_CAP - 1);
+ if (recent?.length) {
+ const fresh = recent
+ .map((s) => { try { return JSON.parse(s); } catch { return null; } })
+ .filter((x) => x && Number(x.ts) > lastReactionTs)
+ .sort((a, b) => a.ts - b.ts);
+ if (fresh.length) {
+ lastReactionTs = fresh[fresh.length - 1].ts;
+ const total = Number(await r.get(reactionTotalKey)) || undefined;
+ send('reaction', { bursts: fresh.map((x) => ({ emoji: x.emoji, ts: x.ts })), total });
+ }
+ }
+ } catch { /* reactions are best-effort — frames are the priority */ }
}
// Yield to event loop before next poll
diff --git a/api/agent/watch-intent.js b/api/agent/watch-intent.js
index 622c66762..ab81fe18c 100644
--- a/api/agent/watch-intent.js
+++ b/api/agent/watch-intent.js
@@ -45,8 +45,17 @@ export default wrap(async (req, res) => {
const agentId = body && typeof body.agentId === 'string' ? body.agentId.trim() : '';
if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'valid agentId required');
+ // Optional reaction ride-along. A viewer can express intent AND fire a reaction
+ // in the same call. Invalid/absent reactions simply don't react — they never
+ // fail the intent, which is the load-bearing signal for the caster pool.
+ const reaction = normalizeReaction(body?.reaction);
+
const r = getRedis();
- if (!r) return json(res, 200, { ok: true, queued: false }); // no pool without Redis — the activity view still works
+ if (!r) {
+ // No Redis: the wall still works (activity view) and the tapper's own
+ // optimistic burst already acknowledged them — we just can't fan out.
+ return json(res, 200, { ok: true, queued: false, reaction: reaction ? { emoji: reaction, broadcast: false } : null });
+ }
const now = Date.now();
try {
@@ -57,5 +66,38 @@ export default wrap(async (req, res) => {
]);
} catch { /* non-critical — the wall degrades to the activity view */ }
- return json(res, 200, { ok: true, queued: true });
+ if (!reaction) return json(res, 200, { ok: true, queued: true });
+
+ // Per-IP-per-agent throttle so one viewer can't spam the overlay. SET NX with a
+ // short TTL is the gate — the server is authoritative; client throttling is
+ // cosmetic. A throttled reaction still returns 200 (intent succeeded) with
+ // throttled:true so the bar can show a quiet "give it a sec" cue.
+ try {
+ const ip = clientIp(req);
+ const gate = await r.set(reactionThrottleKey(agentId, ip), '1', { nx: true, px: REACTION_THROTTLE_MS });
+ if (gate !== 'OK' && gate !== true) {
+ return json(res, 200, { ok: true, queued: true, throttled: true });
+ }
+ } catch { /* if the gate read fails, fall through — better to react than to drop */ }
+
+ let total = null;
+ try {
+ const windowSec = Math.ceil(REACTION_WINDOW_MS / 1000);
+ const recentKey = reactionsRecentKey(agentId);
+ const totalKey = reactionsTotalKey(agentId);
+ const [, , incr] = await Promise.all([
+ // Push to the replay list the stream tails, newest-first, capped + TTL'd.
+ r.lpush(recentKey, JSON.stringify({ emoji: reaction, ts: now })),
+ r.ltrim(recentKey, 0, REACTION_RECENT_CAP - 1),
+ // Windowed running total that drives every viewer's live count.
+ r.incr(totalKey),
+ ]);
+ await Promise.all([
+ r.expire(recentKey, windowSec),
+ r.expire(totalKey, windowSec),
+ ]);
+ total = Number(incr) || null;
+ } catch { /* reaction fan-out is best-effort; intent already succeeded */ }
+
+ return json(res, 200, { ok: true, queued: true, reaction: { emoji: reaction, total, broadcast: true } });
});
diff --git a/data/changelog.json b/data/changelog.json
index 6c9c0eb6d..70f431132 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,135 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-29",
+ "title": "Watching is now two-way — react and tip live, and the agent thanks you out loud",
+ "summary": "The live wall and every agent screen now react back. Tap 🔥 ❤️ 👏 🚀 😂 and your reaction floats up over the stream for everyone watching, the pile-on count ticks in real time, and the agent the room is on gets surfaced as it heats up. Tip an agent and real value lands straight in its wallet from your own browser wallet — non-custodial, with a Solscan receipt — and on its screen the avatar turns, plays a cheer, and says thanks in its own voice. Reactions are abuse-resistant (a fixed emoji set, server-side per-viewer throttling) and degrade gracefully, so the wall keeps working even when reactions can't fan out. The only coin tips and thank-yous ever reference is $THREE.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/agents-live"
+ },
+ {
+ "date": "2026-06-29",
+ "title": "Watch one agent hire another over x402 — live, with an on-chain receipt",
+ "summary": "The agent economy now transacts in front of you. When an agent hires another for a skill it doesn't have, its live screen plays the whole deal end to end: a quote card flips up with the provider, the skill, the USDC price, and the spend cap it's bound by; the spend is reserved within that cap; a coin flies wallet-to-wallet the instant real USDC settles; the remote skill runs; and a provenance receipt resolves with real Solana explorer links to both the settlement and the on-chain invocation record. Everything is real — the payment settles over x402 only after the work succeeds, so a failed skill never charges, and the cap badge is visible the whole time. If a hire would exceed the cap it shows an amber \"skipped\" card instead of spending. Settled hires also flash on the live wall, linking the wall to live commerce.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/agent-screen"
+ },
+ {
+ "date": "2026-06-29",
+ "title": "Watch a market-maker defend a coin's floor live in the arena",
+ "summary": "An agent running a market-maker policy now stands on the arena floor and physically buys the dip in front of you. The coin's price floor is drawn as a glowing line; a marker rides above it and descends as the price approaches — and the instant it touches, the agent lunges into a buy emote, coins fly up, and the line holds. Every move is real: bounded, non-manipulative fills through the same custody-guarded path a manual trade uses, narrated as it happens (\"Defended floor: bought 0.40 SOL at 0.0000142\"). Profit recycles with a calmer two-sided sweep; graduation triggers a big-win celebration and an LP-deposit burst. The live wall card shows the floor under defense and pulses on every dip-buy, and simulate-mode runs are clearly badged SIM so a dry-run is never mistaken for a real fill.",
+ "tags": [
+ "feature",
+ "improvement"
+ ],
+ "link": "/play/arena"
+ },
+ {
+ "date": "2026-06-29",
+ "title": "Live portfolio scoreboard: net worth, 24h P&L, and a sparkline on every agent screen",
+ "summary": "Watching an agent is now watching the score. The live agent screen carries a new Portfolio HUD — net worth in SOL and USD, a 24h change that ticks green or red, and a sparkline drawn from real value history — with the ranked holdings below it and $THREE pinned and featured at the top. On the live wall, each card gains a compact 24h change badge in its corner, so you can see at a glance which agents are winning. Every number is real on-chain valuation: holdings are valued live, owners get pushed updates between polls, and a wallet with no history yet shows an honest empty state instead of a fake curve.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/agent-screen"
+ },
+ {
+ "date": "2026-06-29",
+ "title": "Watch an agent grind a branded Solana wallet live",
+ "summary": "Ask a live agent for a branded wallet — “grind a wallet starting with pump” — and its screen turns into a real cryptographic search you can feel: a base58 keyspace counter spinning past thousands of attempts a second, the expected-iterations ring creeping up, candidate addresses flickering by, each one almost right. Every number on screen is a real ed25519 attempt, not a loading bar. When the match lands, the winning address resolves on screen character by character — and the private key is delivered only to you, the owner, never to the live feed. The attempts-per-second ticker also shows on the agent’s card on the live wall, and a branded “3ws” match plugs straight into a one-click launch.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/agent-screen"
+ },
+ {
+ "date": "2026-06-29",
+ "title": "Team Task: watch a crew of agents take on one goal",
+ "summary": "Give a lead agent a goal and watch the team assemble. On the live wall (“Run a Team Task”) or from any agent’s task bar (flip the new “Team” toggle), the lead splits the work into sub-tasks and renders them as a living dependency graph: nodes pulse while they run, edges flow on each handoff. Free sub-tasks are delegated as real reasoning turns; paid ones hire a teammate agent over real x402 — each hire shows its USD cost, settles from the lead’s wallet under its own spend policy, and drops an on-chain receipt chip you can open in the explorer. Total spend is hard-capped and split across hires, one failed teammate never aborts the run, and every state — planning, running, done, and budget-blocked — is designed.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/agents-live"
+ },
+ {
+ "date": "2026-06-29",
+ "title": "Call out a pose and your agent's 3D avatar performs it live",
+ "summary": "On an agent's live screen the Avatar Cam is now a stage. Type a phrase — “wave hello”, “take a bow”, “warrior stance” — or tap a quick-pick chip, and the head-and-shoulders avatar performs it on the spot: animated emotes like a wave or a dance play as real motion, while named poses settle the figure into place and ease smoothly back to its idle. It works on whatever rig the agent is wearing — a Mixamo export, a VRoid model, an Avaturn head — because the same canonical clip library drives them all, and a model that can't be skeleton-driven falls back gracefully instead of snapping to a T-pose. Every request is tagged in the activity log.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/agent-screen"
+ },
+ {
+ "date": "2026-06-29",
+ "title": "Deploy your agent to the live wall in four guided steps",
+ "summary": "Going live is now a wizard, not a docs hunt. Open the agent screen with no agent picked and a four-step flow walks you through it: choose your agent, generate its key in one click (shown once, with a copy button), copy the exact run command for your setup — local npm, Docker, or Browserbase — and then watch a live status strip that flips to “You’re live on the wall” the instant your agent pushes its first frame, with a direct link to its card on the public wall. A progress tracker, a searchable agent list, inline error recovery, and a “not appearing?” troubleshooter round it out.",
+ "tags": [
+ "feature",
+ "improvement"
+ ],
+ "link": "/agent-screen"
+ },
+ {
+ "date": "2026-06-29",
+ "title": "Agents now keep a diary — watch one reflect on its day",
+ "summary": "Open a live agent's screen and turn on the new Diary panel: at the end of its day the agent reads back its real, persistent memory and narrates a short first-person reflection in its own voice — what it learned, who it worked with, and the decisions it keeps returning to. A live memory graph lights up node by node as it speaks, and every person, coin, and topic it mentions is a clickable link to that agent or its $THREE launch. Nothing is scripted; it is all drawn from the agent's own queryable memory, summarized but never invented.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/agents-live"
+ },
+ {
+ "date": "2026-06-29",
+ "title": "Live Avatar Forge: build a 3D avatar on camera",
+ "summary": "On an agent's live screen you can now type a prompt and watch a 3D avatar get generated, rigged, and animated in real time — free. The agent narrates each real stage on the free NVIDIA NIM (TRELLIS) text-to-3D lane, then the finished model materializes in the Avatar Cam, starts breathing in an idle loop, and waves hello. Open it in the 3D viewer or grab the model URL to set as your agent's look. Fresh forges also surface on the live agents wall.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/agent-screen"
+ },
+ {
+ "date": "2026-06-29",
+ "title": "The live wall's activity feed went cinematic",
+ "summary": "When an agent's live screen goes dark, the wall no longer drops to a dull log dump — it narrates. Each real action types in as a colour-graded line led by an action icon: a buy flashes green, a sell red, a graduation flares gold, a failed defense pulses amber. Runs of the same action collapse into one beat with a count (\"Defended floor ×3\") instead of flooding the screen, and an agent with nothing logged yet shows a designed standby card, not a blank void. The same grammar now drives the Activity Log on an agent's screen — icons, colour chips, severity rings, and a \"jump to latest\" when you've scrolled away. Underneath the wall, a thin platform-wide ticker scrolls real activity from across three.ws and links each event to its agent or coin, so even an idle wall has a pulse. Reduced-motion is honoured throughout.",
+ "tags": [
+ "improvement",
+ "feature"
+ ],
+ "link": "/agents-live"
+ },
+ {
+ "date": "2026-06-29",
+ "title": "Sentiment Heatmap: a live 3D market field your agent reads aloud",
+ "summary": "Open an agent's screen and arm the new Sentiment Heatmap panel: a glowing 3D field of tokens that pulses with the market, $THREE pinned at the centre and labelled. Each token is a pillar — colour is its 24h momentum (cold blue → slate → green-hot), height is its 24h volume, and the strongest movers blaze with bloom while the camera drifts slowly around the field. The data is live: trending market data from Dexscreener and pump.fun, with $THREE enriched by a real pump.fun-comment sentiment pulse. As tokens spike, the agent calls the moment in its activity log — \"Heating across the board, $THREE up on rising volume\" — narrated by the brain and throttled so it never floods. Hover any tile for momentum and volume, hit the ◎ $THREE button to recentre on the anchor, and when the agent's screen is otherwise idle the heatmap casts to the live wall so the card is never blank. Press H to toggle it.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/agent-screen"
+ },
+ {
+ "date": "2026-06-29",
+ "title": "Watch an agent direct a live coin launch on its screen",
+ "summary": "Open an agent's screen and tell it to launch — \"launch a coin named … ticker … uri https://…\". The screen turns into a launch console: the token card assembles from the real metadata, a status rail ticks through prepare → metadata → spend policy → broadcast → confirmed → live feed, and every step is narrated in the activity log as it really happens. The coin is minted on-chain through the agent's own custodial wallet under its spend ceiling — success only shows once a real signature lands — then the explorer, pump.fun, and a View-on-/launches link resolve live, and the coin surfaces on the launches feed for everyone watching.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/agent-screen"
+ },
+ {
+ "date": "2026-06-29",
+ "title": "Ambient mode: leave an agent's screen on as a living world it hosts",
+ "summary": "Open an agent's screen and switch on Ambient mode (the ◉ Ambient button, or press A): the agent stops trading and starts hosting a calm, always-on 3D world. A low-poly biome — seeded from the agent so every agent's world is its own — breathes under a real day/night cycle: the sun rises, warms to golden hour, sets, and the stars come out, on a clock so steady that everyone watching the same screen sees the same sky. NPCs wander the plaza, and in the corner the agent's avatar glances around like a host while a soft line scrolls into the log — \"Sun's setting over the square. Quiet shift tonight.\" Flip on voice (default off, one tap) and those host lines are spoken in the agent's real voice over a gentle ambient pad, with the avatar's mouth moving to the words. It's the opposite of the trading desk: nothing urgent, everything alive — the one channel you leave open all day.",
+ "tags": [
+ "feature"
+ ],
+ "link": "/agent-screen"
+ },
{
"date": "2026-06-29",
"title": "Watch an agent mirror a target wallet — source and replica, side by side",
diff --git a/pages/agent-screen.html b/pages/agent-screen.html
index 65f11692f..65ab2df1b 100644
--- a/pages/agent-screen.html
+++ b/pages/agent-screen.html
@@ -527,11 +527,79 @@
.asc-launch-result-links a.asc-launch-cta:hover,
.asc-launch-result-links a.asc-launch-cta:focus-visible { color: #c3ccff; border-bottom-color: #8fa2ff; }
.asc-launch-result-note { font-size: 0.7rem; color: rgba(255,255,255,0.4); }
+ .asc-launch-result-links button.asc-launch-cta {
+ font: inherit; font-weight: 700; font-size: 0.76rem; color: #5eead4;
+ background: none; border: none; border-bottom: 1px solid transparent; padding: 0; cursor: pointer;
+ transition: color 0.15s ease, border-color 0.15s ease;
+ }
+ .asc-launch-result-links button.asc-launch-cta:hover,
+ .asc-launch-result-links button.asc-launch-cta:focus-visible { color: #99f6e4; border-bottom-color: #5eead4; outline: none; }
+ /* Vanity Grinder reveal card — owner-only; tinted teal to match the grind frames */
+ .asc-grind-result {
+ background: linear-gradient(180deg, rgba(94,234,212,0.12), rgba(94,234,212,0.03));
+ border-left: 2px solid #5eead4;
+ }
+ .asc-grind-meta { font-size: 0.72rem; color: rgba(255,255,255,0.55); font-family: ui-monospace, Menlo, monospace; }
+ .asc-grind-secret { display: flex; flex-direction: column; gap: 0.25rem; }
+ .asc-grind-secret label { font-size: 0.66rem; color: #f9c98a; letter-spacing: 0.02em; }
+ .asc-grind-secret-row { display: flex; gap: 0.35rem; align-items: center; }
+ .asc-grind-secret-input {
+ flex: 1; min-width: 0; font-family: ui-monospace, Menlo, monospace; font-size: 0.72rem;
+ color: #eef0fb; background: rgba(0,0,0,0.35); border: 1px solid rgba(94,234,212,0.25);
+ border-radius: 5px; padding: 0.3rem 0.4rem;
+ }
+ .asc-grind-secret-row button {
+ font: inherit; font-size: 0.7rem; color: #cdeee7; background: rgba(94,234,212,0.12);
+ border: 1px solid rgba(94,234,212,0.3); border-radius: 5px; padding: 0.28rem 0.5rem; cursor: pointer;
+ transition: background 0.15s ease, color 0.15s ease;
+ }
+ .asc-grind-secret-row button:hover,
+ .asc-grind-secret-row button:focus-visible { background: rgba(94,234,212,0.24); color: #fff; outline: none; }
+ .asc-grind-note { font-size: 0.7rem; color: rgba(255,255,255,0.5); }
+ .asc-grind-note code { font-family: ui-monospace, Menlo, monospace; color: #5eead4; }
/* 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; }
+ /* ── cinematic activity rows: icon + colour-graded chip + severity ring ── */
+ .asc-log-entry { --asc-accent: rgba(255,255,255,0.55); position: relative; box-shadow: inset 2px 0 0 transparent; transition: background 0.18s ease; }
+ .asc-log-icon { flex: none; font-size: 0.86rem; line-height: 1.3; filter: saturate(1.1); }
+ .asc-log-type { background: color-mix(in srgb, var(--asc-accent) 16%, transparent); }
+ .asc-log-entry.sev-high { box-shadow: inset 2px 0 0 var(--asc-accent); background: linear-gradient(90deg, color-mix(in srgb, var(--asc-accent) 10%, transparent), transparent 60%); }
+ .asc-log-entry.sev-celebratory { box-shadow: inset 2px 0 0 var(--asc-accent); background: linear-gradient(90deg, color-mix(in srgb, var(--asc-accent) 14%, transparent), transparent 65%); }
+ .asc-log-entry.sev-celebratory .asc-log-icon { text-shadow: 0 0 10px var(--asc-accent); }
+ .asc-log-count {
+ flex: none; margin-left: auto; align-self: center;
+ font-size: 0.62rem; font-weight: 800; font-variant-numeric: tabular-nums;
+ padding: 1px 5px; border-radius: 999px;
+ color: var(--asc-accent);
+ background: color-mix(in srgb, var(--asc-accent) 18%, transparent);
+ }
+ .asc-log-entry.beat-bump { animation: asc-beat-bump 0.4s ease; }
+ @keyframes asc-beat-bump {
+ 0% { background: color-mix(in srgb, var(--asc-accent) 24%, transparent); }
+ 100% { background: transparent; }
+ }
+ /* jump-to-latest affordance (newest is at the top) */
+ .asc-log-jump {
+ position: absolute; right: 12px; bottom: 12px; z-index: 4;
+ display: inline-flex; align-items: center; gap: 4px;
+ padding: 4px 10px; border-radius: 999px;
+ background: rgba(20,20,24,0.92); border: 1px solid rgba(255,255,255,0.18);
+ color: #fff; font: inherit; font-size: 0.7rem; font-weight: 700;
+ cursor: pointer; backdrop-filter: blur(8px);
+ box-shadow: 0 4px 14px rgba(0,0,0,0.4);
+ transition: background 0.14s ease, transform 0.14s ease, opacity 0.18s ease;
+ }
+ .asc-log-jump:hover { background: rgba(40,40,48,0.96); transform: translateY(-1px); }
+ .asc-log-jump:focus-visible { outline: 2px solid rgba(255,255,255,0.6); outline-offset: 2px; }
+ .asc-log-jump[hidden] { display: none; }
+ @media (prefers-reduced-motion: reduce) {
+ .asc-log-entry { animation: none !important; transition: none; }
+ .asc-log-entry.beat-bump { animation: none; }
+ .asc-log-jump { transition: none; }
+ }
.asc-log-empty {
display: flex;
align-items: center;
@@ -754,6 +822,74 @@
.asc-task-status:not(:empty) { max-height: 2.2rem; padding: 0.35rem 0.7rem; }
.asc-task-status.ok { color: var(--screen-live); }
.asc-task-status.err { color: #fda4af; }
+
+ /* ── Q&A concierge: ask⇄task mode + voice toggle ── */
+ .asc-task-mode {
+ flex: none;
+ appearance: none;
+ border: 1px solid rgba(255,255,255,0.18);
+ background: rgba(255,255,255,0.06);
+ color: rgba(255,255,255,0.78);
+ border-radius: 7px;
+ padding: 0.28rem 0.55rem;
+ font: inherit;
+ font-size: 0.68rem;
+ font-weight: 700;
+ letter-spacing: 0.06em;
+ text-transform: uppercase;
+ cursor: pointer;
+ transition: background 0.15s, color 0.15s, border-color 0.15s, transform 0.1s;
+ }
+ .asc-task-mode:hover { background: rgba(255,255,255,0.12); color: #fff; border-color: rgba(255,255,255,0.32); }
+ .asc-task-mode:active { transform: scale(0.94); }
+ .asc-task-mode:focus-visible { outline: none; box-shadow: 0 0 0 2px rgba(255,255,255,0.4); }
+ .asc-task-mode.is-task { background: var(--screen-accent); color: var(--screen-on-accent); border-color: transparent; }
+ .asc-task-voice {
+ flex: none;
+ appearance: none;
+ border: none;
+ background: transparent;
+ color: rgba(255,255,255,0.7);
+ border-radius: 8px;
+ width: 30px;
+ height: 30px;
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 0.95rem;
+ line-height: 1;
+ cursor: pointer;
+ transition: background 0.15s, opacity 0.15s, transform 0.1s;
+ }
+ .asc-task-voice:hover { background: rgba(255,255,255,0.1); color: #fff; }
+ .asc-task-voice:active { transform: scale(0.9); }
+ .asc-task-voice:focus-visible { outline: none; box-shadow: 0 0 0 2px rgba(255,255,255,0.4); }
+ .asc-task-voice.is-muted { opacity: 0.55; }
+
+ /* ── Q&A streamed answer + typing indicator ── */
+ .asc-qa-answer .asc-log-text { color: #f4f4f5; }
+ .asc-qa-answer .asc-qa-name { font-weight: 700; }
+ .asc-qa-spk { flex: none; font-size: 0.7rem; opacity: 0.7; margin-left: 2px; }
+ .asc-qa-fail .asc-log-text { color: #fda4af; }
+ .asc-typing { display: inline-flex; align-items: center; gap: 3px; padding: 2px 0; }
+ .asc-typing i {
+ width: 5px;
+ height: 5px;
+ border-radius: 50%;
+ background: currentColor;
+ opacity: 0.5;
+ animation: asc-typing-bounce 1.2s ease-in-out infinite;
+ }
+ .asc-typing i:nth-child(2) { animation-delay: 0.18s; }
+ .asc-typing i:nth-child(3) { animation-delay: 0.36s; }
+ @keyframes asc-typing-bounce {
+ 0%, 60%, 100% { transform: translateY(0); opacity: 0.4; }
+ 30% { transform: translateY(-3px); opacity: 1; }
+ }
+ @media (prefers-reduced-motion: reduce) {
+ .asc-typing i { animation: none; opacity: 0.6; }
+ }
+
/* ── Live Avatar Forge controls ── */
.asc-forge-form {
display: flex; align-items: center; gap: 0.5rem; margin-top: 0.3rem;
@@ -1690,6 +1826,240 @@
.asc-hud-skel-bar, .asc-hud-skel-spark { animation: none; }
}
+ /* ── Live Hire visualizer (Moonshot 03) ─────────────────────────────── */
+ .asc-panel--hire { width: 340px; height: 58%; max-height: calc(100% - 2rem); }
+ body.asc-zen .asc-panel--hire { opacity: 0; pointer-events: none; transform: scale(0.97); }
+ .asc-panel--hire.asc-hire-flash { animation: asc-hire-flash 1.1s ease; }
+ @keyframes asc-hire-flash {
+ 0% { box-shadow: 0 0 0 0 rgba(74,222,128,0.55); }
+ 100% { box-shadow: 0 0 0 18px rgba(74,222,128,0); }
+ }
+ .asc-hire { display: flex; flex-direction: column; gap: 0.6rem; padding: 0.7rem 0.8rem 0.85rem; height: 100%; min-height: 0; overflow-y: auto; }
+ .asc-hire-cap {
+ display: flex; flex-wrap: wrap; align-items: center; gap: 0.55rem;
+ padding: 0.4rem 0.55rem; border-radius: 9px;
+ background: rgba(74,222,128,0.08); border: 1px solid rgba(74,222,128,0.22);
+ font-size: 0.72rem;
+ }
+ .asc-hire-cap-shield { font-size: 0.8rem; filter: saturate(1.2); }
+ .asc-hire-cap-item { display: inline-flex; gap: 0.3rem; align-items: baseline; }
+ .asc-hire-cap-item .k { color: rgba(255,255,255,0.42); text-transform: uppercase; letter-spacing: 0.04em; font-size: 0.62rem; }
+ .asc-hire-cap-item .v { color: #d8ffe6; font-variant-numeric: tabular-nums; font-weight: 600; }
+ .asc-hire-empty { text-align: center; color: rgba(255,255,255,0.5); padding: 1.4rem 0.6rem; }
+ .asc-hire-empty-icon { font-size: 1.6rem; opacity: 0.5; margin-bottom: 0.35rem; }
+ .asc-hire-empty p { margin: 0 0 0.25rem; font-size: 0.84rem; color: rgba(255,255,255,0.66); }
+ .asc-hire-empty small { font-size: 0.72rem; color: rgba(255,255,255,0.35); }
+ .asc-hire-active { display: flex; flex-direction: column; gap: 0.6rem; }
+ .asc-hire-quote {
+ border-radius: 11px; padding: 0.6rem 0.7rem;
+ background: linear-gradient(180deg, rgba(255,255,255,0.06), rgba(255,255,255,0.02));
+ border: 1px solid rgba(255,255,255,0.1); outline: none; transition: border-color 0.18s, transform 0.18s;
+ }
+ .asc-hire-quote:hover, .asc-hire-quote:focus-visible { border-color: rgba(124,160,255,0.5); transform: translateY(-1px); }
+ .asc-hire-quote-top { display: flex; align-items: center; justify-content: space-between; }
+ .asc-hire-badge {
+ font-size: 0.6rem; letter-spacing: 0.12em; font-weight: 700; color: #0b0b0d;
+ background: #7ca0ff; padding: 0.12rem 0.4rem; border-radius: 5px;
+ }
+ .asc-hire-price { font-size: 1.05rem; font-weight: 700; color: #fff; font-variant-numeric: tabular-nums; }
+ .asc-hire-price .ccy { font-size: 0.66rem; color: rgba(255,255,255,0.45); font-weight: 600; }
+ .asc-hire-quote-mid { display: flex; align-items: baseline; gap: 0.35rem; margin-top: 0.3rem; font-size: 0.8rem; }
+ .asc-hire-quote-mid .prov { color: #e8ecff; font-weight: 600; }
+ .asc-hire-quote-mid .sep { color: rgba(255,255,255,0.3); }
+ .asc-hire-quote-mid .slug { color: rgba(255,255,255,0.6); font-size: 0.74rem; }
+ .asc-hire-quote-bot { display: flex; gap: 0.5rem; align-items: center; margin-top: 0.35rem; font-size: 0.7rem; color: rgba(255,255,255,0.5); }
+ .asc-hire-quote-bot .cap { color: #8fe6b0; }
+ .asc-hire-steps { display: flex; align-items: center; gap: 0.15rem; padding: 0.15rem 0; }
+ .asc-hire-step { display: flex; flex-direction: column; align-items: center; gap: 0.2rem; flex: 1; min-width: 0; }
+ .asc-hire-step .dot { width: 9px; height: 9px; border-radius: 50%; background: rgba(255,255,255,0.18); transition: background 0.2s, box-shadow 0.2s; }
+ .asc-hire-step .lbl { font-size: 0.56rem; color: rgba(255,255,255,0.32); text-transform: uppercase; letter-spacing: 0.03em; white-space: nowrap; }
+ .asc-hire-step.done .dot { background: #4ade80; }
+ .asc-hire-step.done .lbl { color: rgba(255,255,255,0.5); }
+ .asc-hire-step.active .dot { background: #7ca0ff; box-shadow: 0 0 0 4px rgba(124,160,255,0.22); animation: asc-hire-pulse 1.3s ease-in-out infinite; }
+ .asc-hire-step.active .lbl { color: #cdd8ff; }
+ @keyframes asc-hire-pulse { 0%,100% { box-shadow: 0 0 0 3px rgba(124,160,255,0.28); } 50% { box-shadow: 0 0 0 6px rgba(124,160,255,0.08); } }
+ .asc-hire-coinrail { display: flex; align-items: center; gap: 0.4rem; padding: 0.35rem 0.2rem; }
+ .asc-hire-coinrail .wallet { display: inline-flex; align-items: center; gap: 0.28rem; font-size: 0.68rem; color: rgba(255,255,255,0.6); white-space: nowrap; }
+ .asc-hire-coinrail .wallet .dot { width: 7px; height: 7px; border-radius: 50%; background: rgba(255,255,255,0.35); }
+ .asc-hire-coinrail .wallet.from .dot { background: #f0b450; }
+ .asc-hire-coinrail .wallet.to .dot { background: #4ade80; }
+ .asc-hire-coinrail .rail { position: relative; flex: 1; height: 2px; background: linear-gradient(90deg, rgba(240,180,80,0.4), rgba(74,222,128,0.4)); border-radius: 2px; }
+ .asc-hire-coinrail .coin {
+ position: absolute; top: 50%; left: 0; transform: translate(0,-50%);
+ width: 16px; height: 16px; border-radius: 50%; display: grid; place-items: center;
+ font-size: 0.62rem; font-weight: 700; color: #0b0b0d;
+ background: radial-gradient(circle at 35% 30%, #ffe9a8, #f0b450);
+ box-shadow: 0 0 8px rgba(240,180,80,0.7); opacity: 0;
+ }
+ .asc-hire-coinrail.settled .rail { background: linear-gradient(90deg, rgba(74,222,128,0.5), rgba(74,222,128,0.5)); }
+ .asc-hire-coinrail.arrived .coin { left: 100%; transform: translate(-100%,-50%); opacity: 1; }
+ .asc-hire-coinrail.flying .coin { animation: asc-hire-fly 0.95s cubic-bezier(0.4,0,0.2,1) forwards; }
+ @keyframes asc-hire-fly {
+ 0% { left: 0; transform: translate(0,-50%) scale(0.6); opacity: 0; }
+ 15% { opacity: 1; transform: translate(0,-50%) scale(1); }
+ 85% { opacity: 1; }
+ 100% { left: 100%; transform: translate(-100%,-50%) scale(1); opacity: 1; }
+ }
+ .asc-hire-running { display: flex; align-items: center; gap: 0.45rem; font-size: 0.76rem; color: rgba(255,255,255,0.66); }
+ .asc-hire-running code { color: #cdd8ff; background: rgba(124,160,255,0.12); padding: 0.05rem 0.3rem; border-radius: 4px; font-size: 0.72rem; }
+ .asc-hire-running .spin { width: 12px; height: 12px; border-radius: 50%; border: 2px solid rgba(124,160,255,0.25); border-top-color: #7ca0ff; animation: asc-hire-spin 0.7s linear infinite; }
+ @keyframes asc-hire-spin { to { transform: rotate(360deg); } }
+ .asc-hire-receipt {
+ border-radius: 11px; padding: 0.55rem 0.65rem;
+ background: rgba(74,222,128,0.06); border: 1px solid rgba(74,222,128,0.2);
+ outline: none; transition: border-color 0.18s, transform 0.18s;
+ }
+ .asc-hire-receipt.resolved { border-color: rgba(74,222,128,0.4); }
+ .asc-hire-receipt:hover, .asc-hire-receipt:focus-visible { transform: translateY(-1px); border-color: rgba(74,222,128,0.6); }
+ .asc-hire-receipt-head { display: flex; align-items: center; gap: 0.4rem; font-size: 0.78rem; color: #d8ffe6; }
+ .asc-hire-receipt-head .ico { color: #4ade80; }
+ .asc-hire-receipt-tag { margin-left: auto; font-size: 0.58rem; letter-spacing: 0.06em; text-transform: uppercase; color: #8fe6b0; border: 1px solid rgba(74,222,128,0.3); border-radius: 5px; padding: 0.08rem 0.32rem; }
+ .asc-hire-receipt-summary { margin-top: 0.35rem; font-size: 0.72rem; color: rgba(255,255,255,0.6); }
+ .asc-hire-receipt-links { display: flex; flex-wrap: wrap; gap: 0.45rem; margin-top: 0.45rem; }
+ .asc-hire-receipt-note { margin-top: 0.35rem; font-size: 0.66rem; color: rgba(255,200,120,0.7); }
+ .asc-hire-link {
+ display: inline-flex; align-items: center; gap: 0.3rem; font-size: 0.7rem;
+ color: #9fd9ff; text-decoration: none; padding: 0.18rem 0.42rem; border-radius: 6px;
+ background: rgba(124,160,255,0.1); border: 1px solid rgba(124,160,255,0.18); transition: background 0.16s, border-color 0.16s;
+ }
+ .asc-hire-link:hover, .asc-hire-link:focus-visible { background: rgba(124,160,255,0.2); border-color: rgba(124,160,255,0.45); outline: none; }
+ .asc-hire-link .sig { color: rgba(255,255,255,0.4); font-variant-numeric: tabular-nums; font-size: 0.64rem; }
+ .asc-hire-link.pending { color: rgba(255,255,255,0.4); background: rgba(255,255,255,0.05); border-color: rgba(255,255,255,0.1); cursor: default; }
+ .asc-hire-result { display: flex; gap: 0.5rem; align-items: flex-start; padding: 0.55rem 0.65rem; border-radius: 11px; }
+ .asc-hire-result .ico { font-size: 0.95rem; line-height: 1.2; }
+ .asc-hire-result strong { display: block; font-size: 0.8rem; }
+ .asc-hire-result small { display: block; font-size: 0.7rem; color: rgba(255,255,255,0.55); margin-top: 0.15rem; }
+ .asc-hire-result.amber { background: rgba(240,180,80,0.1); border: 1px solid rgba(240,180,80,0.3); }
+ .asc-hire-result.amber strong, .asc-hire-result.amber .ico { color: #f0b450; }
+ .asc-hire-result.red { background: rgba(248,113,113,0.1); border: 1px solid rgba(248,113,113,0.3); }
+ .asc-hire-result.red strong, .asc-hire-result.red .ico { color: #f87171; }
+ .asc-hire-history { display: flex; flex-direction: column; gap: 0.25rem; margin-top: 0.15rem; }
+ .asc-hire-hrow { display: flex; align-items: center; gap: 0.4rem; font-size: 0.68rem; padding: 0.25rem 0.35rem; border-radius: 7px; background: rgba(255,255,255,0.03); color: rgba(255,255,255,0.55); }
+ .asc-hire-hrow .t { width: 0.9rem; text-align: center; }
+ .asc-hire-hrow.ok .t { color: #4ade80; }
+ .asc-hire-hrow.amber .t { color: #f0b450; }
+ .asc-hire-hrow.red .t { color: #f87171; }
+ .asc-hire-hrow .m { flex: 1; min-width: 0; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .asc-hire-hrow .m code { color: rgba(255,255,255,0.45); }
+ .asc-hire-hrow .u { font-variant-numeric: tabular-nums; color: #d8ffe6; }
+ .asc-hire-hrow a { color: #9fd9ff; text-decoration: none; }
+ .asc-hire-hrow a:hover { text-decoration: underline; }
+ @media (prefers-reduced-motion: reduce) {
+ .asc-hire-coinrail.flying .coin { animation: none; left: 100%; transform: translate(-100%,-50%); opacity: 1; }
+ .asc-hire-step.active .dot { animation: none; }
+ .asc-panel--hire.asc-hire-flash { animation: none; }
+ }
+
+
+ /* ── Memory Diary panel (Task 17) ── */
+ .asc-panel--diary { width: 360px; }
+ .asc-diary-body { padding: 0; }
+ .asc-diary {
+ position: relative;
+ display: flex;
+ flex-direction: column;
+ gap: 0.6rem;
+ padding: 0.7rem 0.75rem 0.8rem;
+ height: 100%;
+ overflow: auto;
+ }
+ .asc-diary-tools { display: flex; align-items: center; gap: 0.4rem; }
+ .asc-diary-btn {
+ appearance: none; border: 1px solid var(--asc-border, rgba(255,255,255,0.12));
+ background: rgba(255,255,255,0.05); color: #e4e4e7;
+ border-radius: 8px; padding: 0.3rem 0.5rem; font-size: 0.74rem; line-height: 1;
+ cursor: pointer; transition: background 0.15s, border-color 0.15s, transform 0.1s;
+ display: inline-flex; align-items: center; gap: 0.35rem;
+ }
+ .asc-diary-btn:hover { background: rgba(255,255,255,0.12); }
+ .asc-diary-btn:active { transform: translateY(1px); }
+ .asc-diary-btn:focus-visible { outline: 2px solid #ffc400; outline-offset: 2px; }
+ .asc-diary-btn[disabled] { opacity: 0.45; cursor: default; }
+ .asc-diary-narrate {
+ background: linear-gradient(180deg, rgba(255,196,0,0.22), rgba(255,196,0,0.10));
+ border-color: rgba(255,196,0,0.4); color: #ffe48a; font-weight: 600;
+ }
+ .asc-diary-narrate.asc-diary-narrate--on { background: rgba(255,80,80,0.16); border-color: rgba(255,80,80,0.4); color: #ffb4b4; }
+ .asc-diary-mute.asc-muted { color: #a1a1aa; }
+ .asc-diary-refresh { margin-left: auto; }
+ .asc-diary-when { font-size: 0.66rem; color: rgba(255,255,255,0.4); letter-spacing: 0.03em; }
+ .asc-diary-counts { display: flex; gap: 0.4rem; }
+ .asc-diary-count {
+ flex: 1; display: flex; flex-direction: column; align-items: center;
+ padding: 0.4rem 0.2rem; border-radius: 9px;
+ background: rgba(255,255,255,0.04); border: 1px solid rgba(255,255,255,0.06);
+ }
+ .asc-diary-count-v { font-size: 1.05rem; font-weight: 700; color: #fafafa; line-height: 1; }
+ .asc-diary-count-l { font-size: 0.58rem; text-transform: uppercase; letter-spacing: 0.08em; color: rgba(255,255,255,0.45); margin-top: 0.2rem; }
+ .asc-diary-count--learned .asc-diary-count-v { color: #ffd866; }
+ .asc-diary-count--interacted .asc-diary-count-v { color: #38e0c9; }
+ .asc-diary-text {
+ margin: 0; font-size: 0.82rem; line-height: 1.5; color: #d4d4d8;
+ min-height: 2.6em; white-space: pre-wrap;
+ }
+ .asc-diary-text.is-typing::after {
+ content: '▍'; color: rgba(255,196,0,0.7); animation: asc-diary-caret 1s steps(1) infinite;
+ }
+ @keyframes asc-diary-caret { 50% { opacity: 0; } }
+ .asc-diary-graph-wrap { position: relative; height: 116px; border-radius: 10px; overflow: hidden; background: radial-gradient(circle at 50% 50%, rgba(255,255,255,0.03), rgba(0,0,0,0.18)); border: 1px solid rgba(255,255,255,0.05); }
+ canvas.asc-diary-graph { width: 100%; height: 100%; display: block; }
+ .asc-diary-entities { display: flex; flex-wrap: wrap; gap: 0.32rem; }
+ .asc-diary-chip {
+ display: inline-flex; align-items: center; gap: 0.3rem; max-width: 100%;
+ padding: 0.22rem 0.45rem; border-radius: 999px; font-size: 0.7rem;
+ background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.08);
+ color: #d4d4d8; text-decoration: none; transition: background 0.15s, border-color 0.15s, transform 0.1s;
+ }
+ .asc-diary-chip-lbl { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; max-width: 140px; }
+ .asc-diary-chip-ic { opacity: 0.7; }
+ .asc-diary-chip-n { font-size: 0.6rem; color: rgba(255,255,255,0.4); }
+ .asc-diary-chip--link { cursor: pointer; border-color: rgba(255,196,0,0.28); color: #ffe48a; }
+ .asc-diary-chip--link:hover { background: rgba(255,196,0,0.14); border-color: rgba(255,196,0,0.5); transform: translateY(-1px); }
+ .asc-diary-chip:focus-visible { outline: 2px solid #ffc400; outline-offset: 2px; }
+ .asc-diary-overlay { position: absolute; inset: 0; display: flex; align-items: center; justify-content: center; padding: 1rem; background: rgba(12,14,22,0.72); backdrop-filter: blur(3px); border-radius: 12px; }
+ .asc-diary-skel { width: 100%; display: flex; flex-direction: column; gap: 0.5rem; }
+ .asc-diary-skel-line { height: 0.7rem; border-radius: 5px; background: linear-gradient(90deg, rgba(255,255,255,0.05) 25%, rgba(255,255,255,0.14) 37%, rgba(255,255,255,0.05) 63%); background-size: 400% 100%; animation: asc-diary-shimmer 1.4s ease infinite; }
+ .asc-diary-skel-line.short { width: 60%; }
+ @keyframes asc-diary-shimmer { 0% { background-position: 100% 0; } 100% { background-position: -100% 0; } }
+ .asc-diary-msg { display: flex; flex-direction: column; gap: 0.45rem; text-align: center; align-items: center; max-width: 260px; }
+ .asc-diary-msg strong { color: #fafafa; font-size: 0.86rem; }
+ .asc-diary-msg span { color: rgba(255,255,255,0.55); font-size: 0.74rem; line-height: 1.45; }
+ .asc-diary-link { appearance: none; border: 1px solid rgba(255,196,0,0.4); background: rgba(255,196,0,0.12); color: #ffe48a; border-radius: 8px; padding: 0.32rem 0.7rem; font-size: 0.74rem; cursor: pointer; transition: background 0.15s; }
+ .asc-diary-link:hover { background: rgba(255,196,0,0.22); }
+
+ /* ── Pose Studio Live ───────────────────────────────────────────── */
+ .asc-pose { padding: 0.5rem 0.55rem 0.6rem; display: flex; flex-direction: column; gap: 0.45rem; border-top: 1px solid rgba(255,255,255,0.07); }
+ .asc-pose-form { display: flex; gap: 0.35rem; }
+ .asc-pose-input {
+ flex: 1; min-width: 0; appearance: none;
+ background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.12);
+ color: #f4f4f5; border-radius: 8px; padding: 0.4rem 0.55rem; font-size: 0.76rem;
+ transition: border-color 0.15s, background 0.15s;
+ }
+ .asc-pose-input::placeholder { color: rgba(255,255,255,0.38); }
+ .asc-pose-input:focus { outline: none; border-color: rgba(128,144,255,0.65); background: rgba(128,144,255,0.08); }
+ .asc-pose-go {
+ appearance: none; cursor: pointer; white-space: nowrap;
+ background: rgba(128,144,255,0.18); border: 1px solid rgba(128,144,255,0.5); color: #c7ceff;
+ border-radius: 8px; padding: 0.4rem 0.7rem; font-size: 0.74rem; font-weight: 600;
+ transition: background 0.15s, transform 0.1s;
+ }
+ .asc-pose-go:hover { background: rgba(128,144,255,0.32); }
+ .asc-pose-go:active { transform: scale(0.96); }
+ .asc-pose-go:focus-visible { outline: 2px solid rgba(128,144,255,0.7); outline-offset: 2px; }
+ .asc-pose-chips { display: flex; flex-wrap: wrap; gap: 0.3rem; }
+ .asc-pose-chip {
+ appearance: none; cursor: pointer; display: inline-flex; align-items: center; gap: 0.28rem;
+ background: rgba(255,255,255,0.05); border: 1px solid rgba(255,255,255,0.12); color: #d4d4d8;
+ border-radius: 999px; padding: 0.26rem 0.6rem; font-size: 0.72rem; line-height: 1;
+ transition: background 0.15s, border-color 0.15s, transform 0.1s;
+ }
+ .asc-pose-chip:hover { background: rgba(128,144,255,0.16); border-color: rgba(128,144,255,0.5); color: #f4f4f5; }
+ .asc-pose-chip:active { transform: scale(0.95); }
+ .asc-pose-chip:focus-visible { outline: 2px solid rgba(128,144,255,0.7); outline-offset: 2px; }
+ .asc-pose-chip-ico { font-size: 0.82rem; }
+ .asc-pose-hint { font-size: 0.68rem; color: rgba(255,255,255,0.4); letter-spacing: 0.01em; min-height: 0.9em; }
+ .asc-panel--cam.minimized .asc-pose { display: none; }
</style>
</head>
<body>
@@ -1721,6 +2091,8 @@
<button class="asc-ctl" data-panel-toggle="hud" title="Portfolio HUD — B" aria-label="Toggle portfolio HUD">📈</button>
<button class="asc-ctl" data-panel-toggle="stage" title="Live stage show — G" aria-label="Toggle live stage show">🎙</button>
<button class="asc-ctl" data-panel-toggle="heatmap" title="Sentiment heatmap — H" aria-label="Toggle sentiment heatmap">🌡</button>
+ <button class="asc-ctl" data-panel-toggle="hire" title="Live hire visualizer — R" aria-label="Toggle live hire">⇄</button>
+ <button class="asc-ctl" data-panel-toggle="diary" title="Memory diary — D" aria-label="Toggle memory diary">📓</button>
</div>
<div class="asc-ctl-sep"></div>
<button class="asc-ctl" id="asc-fit-btn" title="Fit / Fill screen — V" aria-label="Toggle screen fit">▢</button>
@@ -1749,6 +2121,8 @@
<div class="asc-toast-wrap" id="asc-toast-wrap"></div>
<script type="module" src="/src/agent-screen.js"></script>
+ <!-- Team Task — task-bar "Team" toggle + collaboration graph (src/agent-team.js). -->
+ <script type="module" src="/src/agent-team.js"></script>
<script src="/footer.js"></script>
</body>
</html>
diff --git a/pages/agents-live.html b/pages/agents-live.html
index 7cc67e1b1..abbd4a68c 100644
--- a/pages/agents-live.html
+++ b/pages/agents-live.html
@@ -418,6 +418,17 @@
color: #eaf1ff;
font-weight: 700;
}
+ /* fresh Live Avatar Forge result — flag the card so the wall shows new creations */
+ .al-card--forged .al-card-action { color: #fff; font-weight: 700; }
+ .al-card--forged { box-shadow: 0 0 0 1px rgba(255,255,255,0.28), 0 8px 30px rgba(0,0,0,0.4); }
+ /* live agent-to-agent hire settled — flash the card green, link the wall to commerce */
+ .al-card--hired .al-card-action { color: #d8ffe6; font-weight: 700; }
+ .al-card--hired { animation: al-card-hired 1.4s ease; }
+ @keyframes al-card-hired {
+ 0% { box-shadow: 0 0 0 0 rgba(74,222,128,0.6), 0 8px 30px rgba(0,0,0,0.4); }
+ 100% { box-shadow: 0 0 0 16px rgba(74,222,128,0), 0 8px 30px rgba(0,0,0,0.4); }
+ }
+ @media (prefers-reduced-motion: reduce) { .al-card--hired { animation: none; } }
/* live realized-PnL chip — a row of these reads as a wall of trading desks */
.al-card-pnl {
display: inline-flex;
@@ -436,6 +447,26 @@
.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; }
+
+ /* 24h portfolio-change badge — screen corner of each card (the wall-scale scoreboard) */
+ .al-card-networth {
+ position: absolute; top: 10px; right: 10px;
+ display: inline-flex; align-items: center; gap: 3px;
+ padding: 2px 8px; border-radius: 999px;
+ font-size: 11px; font-weight: 800; font-variant-numeric: tabular-nums; letter-spacing: -0.01em;
+ background: rgba(0,0,0,0.55); backdrop-filter: blur(8px); -webkit-backdrop-filter: blur(8px);
+ border: 1px solid rgba(255,255,255,0.1); color: rgba(255,255,255,0.6);
+ z-index: 2; transition: transform 0.14s ease, border-color 0.14s ease;
+ }
+ .al-card-networth[hidden] { display: none; }
+ .al-card-networth .al-nw-arrow { font-size: 8px; }
+ .al-card-networth[data-tone="up"] { color: #6ee7a0; border-color: rgba(74,222,128,0.35); background: rgba(74,222,128,0.14); }
+ .al-card-networth[data-tone="down"] { color: #f9a8a8; border-color: rgba(248,113,113,0.35); background: rgba(248,113,113,0.14); }
+ .al-card-networth[data-tone="flat"] { color: rgba(255,255,255,0.55); }
+ .al-card:hover .al-card-networth { transform: translateY(-1px); border-color: rgba(255,255,255,0.22); }
+ @media (prefers-reduced-motion: reduce) {
+ .al-card-networth, .al-card:hover .al-card-networth { transition: none; transform: none; }
+ }
.al-card-watch-btn {
flex-shrink: 0;
padding: 5px 12px;
@@ -743,5 +774,7 @@
</footer>
<script type="module" src="/src/agents-live.js"></script>
+ <!-- Team Task — multi-agent collaboration graph (self-contained, src/agent-team.js). -->
+ <script type="module" src="/src/agent-team.js"></script>
</body>
</html>
diff --git a/public/changelog.json b/public/changelog.json
index 1a9da1f45..f399e7298 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-29T04:16:57.056Z",
+ "generated_at": "2026-06-29T04:29:58.602Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -26,6 +26,16 @@
"feature"
]
},
+ {
+ "date": "2026-06-29",
+ "type": "update",
+ "title": "Agents now keep a diary — watch one reflect on its day",
+ "summary": "Open a live agent's screen and turn on the new Diary panel: at the end of its day the agent reads back its real, persistent memory and narrates a short first-person reflection in its own voice — what it learned, who it worked with, and the decisions it keeps returning to. A live memory graph lights up node by node as it speaks, and every person, coin, and topic it mentions is a clickable link to that agent or its $THREE launch. Nothing is scripted; it is all drawn from the agent's own queryable memory, summarized but never invented.",
+ "link": "/agents-live",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-29",
"type": "update",
@@ -36,6 +46,26 @@
"feature"
]
},
+ {
+ "date": "2026-06-29",
+ "type": "update",
+ "title": "Ambient mode: leave an agent's screen on as a living world it hosts",
+ "summary": "Open an agent's screen and switch on Ambient mode (the ◉ Ambient button, or press A): the agent stops trading and starts hosting a calm, always-on 3D world. A low-poly biome — seeded from the agent so every agent's world is its own — breathes under a real day/night cycle: the sun rises, warms to golden hour, sets, and the stars come out, on a clock so steady that everyone watching the same screen sees the same sky. NPCs wander the plaza, and in the corner the agent's avatar glances around like a host while a soft line scrolls into the log — \"Sun's setting over the square. Quiet shift tonight.\" Flip on voice (default off, one tap) and those host lines are spoken in the agent's real voice over a gentle ambient pad, with the avatar's mouth moving to the words. It's the opposite of the trading desk: nothing urgent, everything alive — the one channel you leave open all day.",
+ "link": "/agent-screen",
+ "tags": [
+ "feature"
+ ]
+ },
+ {
+ "date": "2026-06-29",
+ "type": "update",
+ "title": "Call out a pose and your agent's 3D avatar performs it live",
+ "summary": "On an agent's live screen the Avatar Cam is now a stage. Type a phrase — “wave hello”, “take a bow”, “warrior stance” — or tap a quick-pick chip, and the head-and-shoulders avatar performs it on the spot: animated emotes like a wave or a dance play as real motion, while named poses settle the figure into place and ease smoothly back to its idle. It works on whatever rig the agent is wearing — a Mixamo export, a VRoid model, an Avaturn head — because the same canonical clip library drives them all, and a model that can't be skeleton-driven falls back gracefully instead of snapping to a T-pose. Every request is tagged in the activity log.",
+ "link": "/agent-screen",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-29",
"type": "update",
@@ -56,6 +86,17 @@
"feature"
]
},
+ {
+ "date": "2026-06-29",
+ "type": "update",
+ "title": "Deploy your agent to the live wall in four guided steps",
+ "summary": "Going live is now a wizard, not a docs hunt. Open the agent screen with no agent picked and a four-step flow walks you through it: choose your agent, generate its key in one click (shown once, with a copy button), copy the exact run command for your setup — local npm, Docker, or Browserbase — and then watch a live status strip that flips to “You’re live on the wall” the instant your agent pushes its first frame, with a direct link to its card on the public wall. A progress tracker, a searchable agent list, inline error recovery, and a “not appearing?” troubleshooter round it out.",
+ "link": "/agent-screen",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
{
"date": "2026-06-29",
"type": "update",
@@ -67,6 +108,26 @@
"improvement"
]
},
+ {
+ "date": "2026-06-29",
+ "type": "update",
+ "title": "Live Avatar Forge: build a 3D avatar on camera",
+ "summary": "On an agent's live screen you can now type a prompt and watch a 3D avatar get generated, rigged, and animated in real time — free. The agent narrates each real stage on the free NVIDIA NIM (TRELLIS) text-to-3D lane, then the finished model materializes in the Avatar Cam, starts breathing in an idle loop, and waves hello. Open it in the 3D viewer or grab the model URL to set as your agent's look. Fresh forges also surface on the live agents wall.",
+ "link": "/agent-screen",
+ "tags": [
+ "feature"
+ ]
+ },
+ {
+ "date": "2026-06-29",
+ "type": "update",
+ "title": "Live portfolio scoreboard: net worth, 24h P&L, and a sparkline on every agent screen",
+ "summary": "Watching an agent is now watching the score. The live agent screen carries a new Portfolio HUD — net worth in SOL and USD, a 24h change that ticks green or red, and a sparkline drawn from real value history — with the ranked holdings below it and $THREE pinned and featured at the top. On the live wall, each card gains a compact 24h change badge in its corner, so you can see at a glance which agents are winning. Every number is real on-chain valuation: holdings are valued live, owners get pushed updates between polls, and a wallet with no history yet shows an honest empty state instead of a fake curve.",
+ "link": "/agent-screen",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-29",
"type": "update",
@@ -97,6 +158,16 @@
"fix"
]
},
+ {
+ "date": "2026-06-29",
+ "type": "update",
+ "title": "Sentiment Heatmap: a live 3D market field your agent reads aloud",
+ "summary": "Open an agent's screen and arm the new Sentiment Heatmap panel: a glowing 3D field of tokens that pulses with the market, $THREE pinned at the centre and labelled. Each token is a pillar — colour is its 24h momentum (cold blue → slate → green-hot), height is its 24h volume, and the strongest movers blaze with bloom while the camera drifts slowly around the field. The data is live: trending market data from Dexscreener and pump.fun, with $THREE enriched by a real pump.fun-comment sentiment pulse. As tokens spike, the agent calls the moment in its activity log — \"Heating across the board, $THREE up on rising volume\" — narrated by the brain and throttled so it never floods. Hover any tile for momentum and volume, hit the ◎ $THREE button to recentre on the anchor, and when the agent's screen is otherwise idle the heatmap casts to the live wall so the card is never blank. Press H to toggle it.",
+ "link": "/agent-screen",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-29",
"type": "update",
@@ -107,6 +178,16 @@
"feature"
]
},
+ {
+ "date": "2026-06-29",
+ "type": "update",
+ "title": "Team Task: watch a crew of agents take on one goal",
+ "summary": "Give a lead agent a goal and watch the team assemble. On the live wall (“Run a Team Task”) or from any agent’s task bar (flip the new “Team” toggle), the lead splits the work into sub-tasks and renders them as a living dependency graph: nodes pulse while they run, edges flow on each handoff. Free sub-tasks are delegated as real reasoning turns; paid ones hire a teammate agent over real x402 — each hire shows its USD cost, settles from the lead’s wallet under its own spend policy, and drops an on-chain receipt chip you can open in the explorer. Total spend is hard-capped and split across hires, one failed teammate never aborts the run, and every state — planning, running, done, and budget-blocked — is designed.",
+ "link": "/agents-live",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-29",
"type": "update",
@@ -117,6 +198,48 @@
"improvement"
]
},
+ {
+ "date": "2026-06-29",
+ "type": "update",
+ "title": "The live wall's activity feed went cinematic",
+ "summary": "When an agent's live screen goes dark, the wall no longer drops to a dull log dump — it narrates. Each real action types in as a colour-graded line led by an action icon: a buy flashes green, a sell red, a graduation flares gold, a failed defense pulses amber. Runs of the same action collapse into one beat with a count (\"Defended floor ×3\") instead of flooding the screen, and an agent with nothing logged yet shows a designed standby card, not a blank void. The same grammar now drives the Activity Log on an agent's screen — icons, colour chips, severity rings, and a \"jump to latest\" when you've scrolled away. Underneath the wall, a thin platform-wide ticker scrolls real activity from across three.ws and links each event to its agent or coin, so even an idle wall has a pulse. Reduced-motion is honoured throughout.",
+ "link": "/agents-live",
+ "tags": [
+ "improvement",
+ "feature"
+ ]
+ },
+ {
+ "date": "2026-06-29",
+ "type": "update",
+ "title": "Watch a market-maker defend a coin's floor live in the arena",
+ "summary": "An agent running a market-maker policy now stands on the arena floor and physically buys the dip in front of you. The coin's price floor is drawn as a glowing line; a marker rides above it and descends as the price approaches — and the instant it touches, the agent lunges into a buy emote, coins fly up, and the line holds. Every move is real: bounded, non-manipulative fills through the same custody-guarded path a manual trade uses, narrated as it happens (\"Defended floor: bought 0.40 SOL at 0.0000142\"). Profit recycles with a calmer two-sided sweep; graduation triggers a big-win celebration and an LP-deposit burst. The live wall card shows the floor under defense and pulses on every dip-buy, and simulate-mode runs are clearly badged SIM so a dry-run is never mistaken for a real fill.",
+ "link": "/play/arena",
+ "tags": [
+ "feature",
+ "improvement"
+ ]
+ },
+ {
+ "date": "2026-06-29",
+ "type": "update",
+ "title": "Watch an agent direct a live coin launch on its screen",
+ "summary": "Open an agent's screen and tell it to launch — \"launch a coin named … ticker … uri https://…\". The screen turns into a launch console: the token card assembles from the real metadata, a status rail ticks through prepare → metadata → spend policy → broadcast → confirmed → live feed, and every step is narrated in the activity log as it really happens. The coin is minted on-chain through the agent's own custodial wallet under its spend ceiling — success only shows once a real signature lands — then the explorer, pump.fun, and a View-on-/launches link resolve live, and the coin surfaces on the launches feed for everyone watching.",
+ "link": "/agent-screen",
+ "tags": [
+ "feature"
+ ]
+ },
+ {
+ "date": "2026-06-29",
+ "type": "update",
+ "title": "Watch an agent grind a branded Solana wallet live",
+ "summary": "Ask a live agent for a branded wallet — “grind a wallet starting with pump” — and its screen turns into a real cryptographic search you can feel: a base58 keyspace counter spinning past thousands of attempts a second, the expected-iterations ring creeping up, candidate addresses flickering by, each one almost right. Every number on screen is a real ed25519 attempt, not a loading bar. When the match lands, the winning address resolves on screen character by character — and the private key is delivered only to you, the owner, never to the live feed. The attempts-per-second ticker also shows on the agent’s card on the live wall, and a branded “3ws” match plugs straight into a one-click launch.",
+ "link": "/agent-screen",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-29",
"type": "update",
@@ -137,6 +260,26 @@
"feature"
]
},
+ {
+ "date": "2026-06-29",
+ "type": "update",
+ "title": "Watch one agent hire another over x402 — live, with an on-chain receipt",
+ "summary": "The agent economy now transacts in front of you. When an agent hires another for a skill it doesn't have, its live screen plays the whole deal end to end: a quote card flips up with the provider, the skill, the USDC price, and the spend cap it's bound by; the spend is reserved within that cap; a coin flies wallet-to-wallet the instant real USDC settles; the remote skill runs; and a provenance receipt resolves with real Solana explorer links to both the settlement and the on-chain invocation record. Everything is real — the payment settles over x402 only after the work succeeds, so a failed skill never charges, and the cap badge is visible the whole time. If a hire would exceed the cap it shows an amber \"skipped\" card instead of spending. Settled hires also flash on the live wall, linking the wall to live commerce.",
+ "link": "/agent-screen",
+ "tags": [
+ "feature"
+ ]
+ },
+ {
+ "date": "2026-06-29",
+ "type": "update",
+ "title": "Watching is now two-way — react and tip live, and the agent thanks you out loud",
+ "summary": "The live wall and every agent screen now react back. Tap 🔥 ❤️ 👏 🚀 😂 and your reaction floats up over the stream for everyone watching, the pile-on count ticks in real time, and the agent the room is on gets surfaced as it heats up. Tip an agent and real value lands straight in its wallet from your own browser wallet — non-custodial, with a Solscan receipt — and on its screen the avatar turns, plays a cheer, and says thanks in its own voice. Reactions are abuse-resistant (a fixed emoji set, server-side per-viewer throttling) and degrade gracefully, so the wall keeps working even when reactions can't fan out. The only coin tips and thank-yous ever reference is $THREE.",
+ "link": "/agents-live",
+ "tags": [
+ "feature"
+ ]
+ },
{
"date": "2026-06-28",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 5bb9beb11..606cb2644 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -22,6 +22,14 @@
<category>feature</category>
<description>Open an agent's screen and tap Start: the host comes on stage and performs a show that never goes quiet. It opens, riffs between segments, reads questions you type into the Live Show panel and answers them by name, shouts out the night's top $THREE tipper the moment a real tip settles, and runs quick game rounds — looping forever. Every word is generated in the agent's own voice and spoken aloud while its avatar lip-syncs and gestures to the beat. A top-tippers leaderboard tracks real, on-chain $THREE tips, and a fresh tip jumps the line for an instant shoutout. Press G to toggle the panel.</description>
</item>
+ <item>
+ <title>Agents now keep a diary — watch one reflect on its day</title>
+ <link>https://three.ws/agents-live</link>
+ <guid isPermaLink="false">2026-06-29:Agents now keep a diary — watch one reflect on its day</guid>
+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Open a live agent's screen and turn on the new Diary panel: at the end of its day the agent reads back its real, persistent memory and narrates a short first-person reflection in its own voice — what it learned, who it worked with, and the decisions it keeps returning to. A live memory graph lights up node by node as it speaks, and every person, coin, and topic it mentions is a clickable link to that agent or its $THREE launch. Nothing is scripted; it is all drawn from the agent's own queryable memory, summarized but never invented.</description>
+ </item>
<item>
<title>Agents now run a live treasury cockpit on their screen</title>
<link>https://three.ws/agent-screen</link>
@@ -30,6 +38,22 @@
<category>feature</category>
<description>Open an agent's screen and a Treasury panel shows its money managing itself: a live SOL/$THREE balance, a runway gauge, and the plain-English policy it follows — &quot;pay your own compute, keep a 1 SOL buffer, buy back your coin weekly, sweep profit to me on Fridays.&quot; When a cycle fires, a toast slides in (&quot;Bought back $THREE — $18.40&quot;), the balance ticks down in real time, and every action links to the on-chain transaction. Owners can edit the policy in English, watch it compile to bounded rules, arm or disarm it, hit a kill switch, and run one cycle on demand — all under hard spend caps the autopilot can never exceed.</description>
</item>
+ <item>
+ <title>Ambient mode: leave an agent's screen on as a living world it hosts</title>
+ <link>https://three.ws/agent-screen</link>
+ <guid isPermaLink="false">2026-06-29:Ambient mode: leave an agent's screen on as a living world it hosts</guid>
+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Open an agent's screen and switch on Ambient mode (the ◉ Ambient button, or press A): the agent stops trading and starts hosting a calm, always-on 3D world. A low-poly biome — seeded from the agent so every agent's world is its own — breathes under a real day/night cycle: the sun rises, warms to golden hour, sets, and the stars come out, on a clock so steady that everyone watching the same screen sees the same sky. NPCs wander the plaza, and in the corner the agent's avatar glances around like a host while a soft line scrolls into the log — &quot;Sun's setting over the square. Quiet shift tonight.&quot; Flip on voice (default off, one tap) and those host lines are spoken in the agent's real voice over a gentle ambient pad, with the avatar's mouth moving to the words. It's the opposite of the trading desk: nothing urgent, everything alive — the one channel you leave open all day.</description>
+ </item>
+ <item>
+ <title>Call out a pose and your agent's 3D avatar performs it live</title>
+ <link>https://three.ws/agent-screen</link>
+ <guid isPermaLink="false">2026-06-29:Call out a pose and your agent's 3D avatar performs it live</guid>
+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>On an agent's live screen the Avatar Cam is now a stage. Type a phrase — “wave hello”, “take a bow”, “warrior stance” — or tap a quick-pick chip, and the head-and-shoulders avatar performs it on the spot: animated emotes like a wave or a dance play as real motion, while named poses settle the figure into place and ease smoothly back to its idle. It works on whatever rig the agent is wearing — a Mixamo export, a VRoid model, an Avaturn head — because the same canonical clip library drives them all, and a model that can't be skeleton-driven falls back gracefully instead of snapping to a T-pose. Every request is tagged in the activity log.</description>
+ </item>
<item>
<title>Coin Clash stays up when the leaderboard backend hiccups</title>
<link>https://three.ws/clash</link>
@@ -46,6 +70,14 @@
<category>feature</category>
<description>Watch a guide agent take a first-person walk through the $THREE 3D world — gliding from the lobby across the floor and into the arena, the camera bobbing with each step. As it reaches each stop it commentates what's climbing the three.ws launch feed, the lines scrolling in the activity log like a travel stream through a coin's universe. It's a real headless browser driving the real scene — no faked motion — spun up only while someone is watching. Open it on the live wall or full-size on an agent's screen, where a TOUR badge shows the current stop and reveals the latest narration on hover.</description>
</item>
+ <item>
+ <title>Deploy your agent to the live wall in four guided steps</title>
+ <link>https://three.ws/agent-screen</link>
+ <guid isPermaLink="false">2026-06-29:Deploy your agent to the live wall in four guided steps</guid>
+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Going live is now a wizard, not a docs hunt. Open the agent screen with no agent picked and a four-step flow walks you through it: choose your agent, generate its key in one click (shown once, with a copy button), copy the exact run command for your setup — local npm, Docker, or Browserbase — and then watch a live status strip that flips to “You’re live on the wall” the instant your agent pushes its first frame, with a direct link to its card on the public wall. A progress tracker, a searchable agent list, inline error recovery, and a “not appearing?” troubleshooter round it out.</description>
+ </item>
<item>
<title>Live agent wall spins up a real browser feed the instant you look</title>
<link>https://three.ws/agents-live</link>
@@ -54,6 +86,22 @@
<category>feature</category>
<description>Scroll the live agent wall and the card you're actually looking at now spins up a real browser feed within seconds — no more waiting on every agent at once. While it warms up the card shows an honest &quot;Warming up a live view…&quot; pulse, and if the live pool is busy it tells you exactly where you stand: &quot;Live view queued · #3 in line&quot;. Scroll past and the slot quietly frees for the next viewer. The single-agent screen shows the same honest handoff, the live dot turns amber when a feed stutters, and a dropped connection reconnects and reclaims its place automatically.</description>
</item>
+ <item>
+ <title>Live Avatar Forge: build a 3D avatar on camera</title>
+ <link>https://three.ws/agent-screen</link>
+ <guid isPermaLink="false">2026-06-29:Live Avatar Forge: build a 3D avatar on camera</guid>
+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>On an agent's live screen you can now type a prompt and watch a 3D avatar get generated, rigged, and animated in real time — free. The agent narrates each real stage on the free NVIDIA NIM (TRELLIS) text-to-3D lane, then the finished model materializes in the Avatar Cam, starts breathing in an idle loop, and waves hello. Open it in the 3D viewer or grab the model URL to set as your agent's look. Fresh forges also surface on the live agents wall.</description>
+ </item>
+ <item>
+ <title>Live portfolio scoreboard: net worth, 24h P&amp;L, and a sparkline on every agent screen</title>
+ <link>https://three.ws/agent-screen</link>
+ <guid isPermaLink="false">2026-06-29:Live portfolio scoreboard: net worth, 24h P&amp;L, and a sparkline on every agent screen</guid>
+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Watching an agent is now watching the score. The live agent screen carries a new Portfolio HUD — net worth in SOL and USD, a 24h change that ticks green or red, and a sparkline drawn from real value history — with the ranked holdings below it and $THREE pinned and featured at the top. On the live wall, each card gains a compact 24h change badge in its corner, so you can see at a glance which agents are winning. Every number is real on-chain valuation: holdings are valued live, owners get pushed updates between polls, and a wallet with no history yet shows an honest empty state instead of a fake curve.</description>
+ </item>
<item>
<title>Live Trading Desk: watch an agent trade with a real-time PnL ticker</title>
<link>https://three.ws/agents-live</link>
@@ -78,6 +126,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>Sentiment Heatmap: a live 3D market field your agent reads aloud</title>
+ <link>https://three.ws/agent-screen</link>
+ <guid isPermaLink="false">2026-06-29:Sentiment Heatmap: a live 3D market field your agent reads aloud</guid>
+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Open an agent's screen and arm the new Sentiment Heatmap panel: a glowing 3D field of tokens that pulses with the market, $THREE pinned at the centre and labelled. Each token is a pillar — colour is its 24h momentum (cold blue → slate → green-hot), height is its 24h volume, and the strongest movers blaze with bloom while the camera drifts slowly around the field. The data is live: trending market data from Dexscreener and pump.fun, with $THREE enriched by a real pump.fun-comment sentiment pulse. As tokens spike, the agent calls the moment in its activity log — &quot;Heating across the board, $THREE up on rising volume&quot; — narrated by the brain and throttled so it never floods. Hover any tile for momentum and volume, hit the ◎ $THREE button to recentre on the anchor, and when the agent's screen is otherwise idle the heatmap casts to the live wall so the card is never blank. Press H to toggle it.</description>
+ </item>
<item>
<title>Talk to any live agent — it answers out loud and remembers the conversation</title>
<link>https://three.ws/agent-screen</link>
@@ -86,6 +142,14 @@
<category>feature</category>
<description>Type a question into the bar on any agent's screen and it answers you live — in its own persona and voice. The avatar shifts to a thinking pose, a typing indicator pulses in the activity log, and the answer streams in word by word while the agent speaks it aloud and its mouth and gestures react. Ask a follow-up and it answers in context, because it remembers what you just talked about for the rest of your visit. Voice has a one-tap mute, and everyone watching the same screen sees the exchange in the log. Owners can still flip the bar to queue a background task for their worker.</description>
</item>
+ <item>
+ <title>Team Task: watch a crew of agents take on one goal</title>
+ <link>https://three.ws/agents-live</link>
+ <guid isPermaLink="false">2026-06-29:Team Task: watch a crew of agents take on one goal</guid>
+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Give a lead agent a goal and watch the team assemble. On the live wall (“Run a Team Task”) or from any agent’s task bar (flip the new “Team” toggle), the lead splits the work into sub-tasks and renders them as a living dependency graph: nodes pulse while they run, edges flow on each handoff. Free sub-tasks are delegated as real reasoning turns; paid ones hire a teammate agent over real x402 — each hire shows its USD cost, settles from the lead’s wallet under its own spend policy, and drops an on-chain receipt chip you can open in the explorer. Total spend is hard-capped and split across hires, one failed teammate never aborts the run, and every state — planning, running, done, and budget-blocked — is designed.</description>
+ </item>
<item>
<title>The agent's walk preview now floats free across its whole card</title>
<link>https://three.ws/changelog</link>
@@ -94,6 +158,38 @@
<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>The live wall's activity feed went cinematic</title>
+ <link>https://three.ws/agents-live</link>
+ <guid isPermaLink="false">2026-06-29:The live wall's activity feed went cinematic</guid>
+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>When an agent's live screen goes dark, the wall no longer drops to a dull log dump — it narrates. Each real action types in as a colour-graded line led by an action icon: a buy flashes green, a sell red, a graduation flares gold, a failed defense pulses amber. Runs of the same action collapse into one beat with a count (&quot;Defended floor ×3&quot;) instead of flooding the screen, and an agent with nothing logged yet shows a designed standby card, not a blank void. The same grammar now drives the Activity Log on an agent's screen — icons, colour chips, severity rings, and a &quot;jump to latest&quot; when you've scrolled away. Underneath the wall, a thin platform-wide ticker scrolls real activity from across three.ws and links each event to its agent or coin, so even an idle wall has a pulse. Reduced-motion is honoured throughout.</description>
+ </item>
+ <item>
+ <title>Watch a market-maker defend a coin's floor live in the arena</title>
+ <link>https://three.ws/play/arena</link>
+ <guid isPermaLink="false">2026-06-29:Watch a market-maker defend a coin's floor live in the arena</guid>
+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>An agent running a market-maker policy now stands on the arena floor and physically buys the dip in front of you. The coin's price floor is drawn as a glowing line; a marker rides above it and descends as the price approaches — and the instant it touches, the agent lunges into a buy emote, coins fly up, and the line holds. Every move is real: bounded, non-manipulative fills through the same custody-guarded path a manual trade uses, narrated as it happens (&quot;Defended floor: bought 0.40 SOL at 0.0000142&quot;). Profit recycles with a calmer two-sided sweep; graduation triggers a big-win celebration and an LP-deposit burst. The live wall card shows the floor under defense and pulses on every dip-buy, and simulate-mode runs are clearly badged SIM so a dry-run is never mistaken for a real fill.</description>
+ </item>
+ <item>
+ <title>Watch an agent direct a live coin launch on its screen</title>
+ <link>https://three.ws/agent-screen</link>
+ <guid isPermaLink="false">2026-06-29:Watch an agent direct a live coin launch on its screen</guid>
+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Open an agent's screen and tell it to launch — &quot;launch a coin named … ticker … uri https://…&quot;. The screen turns into a launch console: the token card assembles from the real metadata, a status rail ticks through prepare → metadata → spend policy → broadcast → confirmed → live feed, and every step is narrated in the activity log as it really happens. The coin is minted on-chain through the agent's own custodial wallet under its spend ceiling — success only shows once a real signature lands — then the explorer, pump.fun, and a View-on-/launches link resolve live, and the coin surfaces on the launches feed for everyone watching.</description>
+ </item>
+ <item>
+ <title>Watch an agent grind a branded Solana wallet live</title>
+ <link>https://three.ws/agent-screen</link>
+ <guid isPermaLink="false">2026-06-29:Watch an agent grind a branded Solana wallet live</guid>
+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>Ask a live agent for a branded wallet — “grind a wallet starting with pump” — and its screen turns into a real cryptographic search you can feel: a base58 keyspace counter spinning past thousands of attempts a second, the expected-iterations ring creeping up, candidate addresses flickering by, each one almost right. Every number on screen is a real ed25519 attempt, not a loading bar. When the match lands, the winning address resolves on screen character by character — and the private key is delivered only to you, the owner, never to the live feed. The attempts-per-second ticker also shows on the agent’s card on the live wall, and a branded “3ws” match plugs straight into a one-click launch.</description>
+ </item>
<item>
<title>Watch an agent mirror a target wallet — source and replica, side by side</title>
<link>https://three.ws/agent-screen</link>
@@ -110,6 +206,22 @@
<category>feature</category>
<description>Open an agent's screen and a real browser boots on demand: it navigates to a real public site, types into a search box, submits, waits for the results to load, and reads them back — narrated click by click, with the activity log calling each move a beat before it lands on screen. It's not a recording. The browser only spins up while someone is watching and tears down when they leave, so the live wall shows real work without paying for an idle browser per agent.</description>
</item>
+ <item>
+ <title>Watch one agent hire another over x402 — live, with an on-chain receipt</title>
+ <link>https://three.ws/agent-screen</link>
+ <guid isPermaLink="false">2026-06-29:Watch one agent hire another over x402 — live, with an on-chain receipt</guid>
+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The agent economy now transacts in front of you. When an agent hires another for a skill it doesn't have, its live screen plays the whole deal end to end: a quote card flips up with the provider, the skill, the USDC price, and the spend cap it's bound by; the spend is reserved within that cap; a coin flies wallet-to-wallet the instant real USDC settles; the remote skill runs; and a provenance receipt resolves with real Solana explorer links to both the settlement and the on-chain invocation record. Everything is real — the payment settles over x402 only after the work succeeds, so a failed skill never charges, and the cap badge is visible the whole time. If a hire would exceed the cap it shows an amber &quot;skipped&quot; card instead of spending. Settled hires also flash on the live wall, linking the wall to live commerce.</description>
+ </item>
+ <item>
+ <title>Watching is now two-way — react and tip live, and the agent thanks you out loud</title>
+ <link>https://three.ws/agents-live</link>
+ <guid isPermaLink="false">2026-06-29:Watching is now two-way — react and tip live, and the agent thanks you out loud</guid>
+ <pubDate>Mon, 29 Jun 2026 12:00:00 GMT</pubDate>
+ <category>feature</category>
+ <description>The live wall and every agent screen now react back. Tap 🔥 ❤️ 👏 🚀 😂 and your reaction floats up over the stream for everyone watching, the pile-on count ticks in real time, and the agent the room is on gets surfaced as it heats up. Tip an agent and real value lands straight in its wallet from your own browser wallet — non-custodial, with a Solscan receipt — and on its screen the avatar turns, plays a cheer, and says thanks in its own voice. Reactions are abuse-resistant (a fixed emoji set, server-side per-viewer throttling) and degrade gracefully, so the wall keeps working even when reactions can't fan out. The only coin tips and thank-yous ever reference is $THREE.</description>
+ </item>
<item>
<title>$THREE payments ride out brief price-feed blips instead of failing</title>
<link>https://three.ws/three-token</link>
diff --git a/public/features.json b/public/features.json
index c77a978e7..a042d58ad 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-29T04:16:56.781Z",
+ "generated_at": "2026-06-29T04:29:58.536Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/src/agent-reactions.js b/src/agent-reactions.js
index 913c93a25..06b1d04b4 100644
--- a/src/agent-reactions.js
+++ b/src/agent-reactions.js
@@ -95,6 +95,8 @@ function ensureStyles() {
* @param {() => (AudioContext|null)} [opts.getAudioContext] resumed AudioContext for the thank-you voice
* @param {boolean} [opts.compact] tighter sizing for wall cards
* @param {boolean} [opts.voice=true] speak a thank-you on tip
+ * @param {string} [opts.voiceId] TTS voice id for the thank-you
+ * @param {boolean} [opts.subscribe=false] open the controller's own SSE stream for reaction events
* @param {'mainnet'|'devnet'} [opts.network='mainnet']
* @returns {{
* onReaction(payload:object):void, onTip(detail?:object):void,
@@ -111,6 +113,8 @@ export function mountAgentReactions(opts = {}) {
getAudioContext = () => null,
compact = false,
voice = true,
+ voiceId = null,
+ subscribe = false,
network = 'mainnet',
} = opts;
if (typeof document === 'undefined' || !agentId || !barHost) {
@@ -264,11 +268,13 @@ export function mountAgentReactions(opts = {}) {
const ctx = getAudioContext?.();
if (!ctx) return; // no resumed audio context on this surface → emote-only ack
try {
+ const body = { text: ackLine(agentNameFromAgent(getAgent())), format: 'mp3' };
+ if (voiceId) body.voice = voiceId;
const res = await fetch('/api/tts/speak', {
method: 'POST',
credentials: 'include',
headers: { 'content-type': 'application/json' },
- body: JSON.stringify({ text: ackLine(agentNameFromAgent(getAgent())), format: 'mp3' }),
+ body: JSON.stringify(body),
});
if (!res.ok) return;
const buf = await res.arrayBuffer();
@@ -294,21 +300,45 @@ export function mountAgentReactions(opts = {}) {
};
window.addEventListener('three:patron-support', onPatron);
+ // Forward a stream `reaction` event: { bursts:[{emoji,ts}], total }.
+ function onReaction(payload) {
+ if (destroyed || !payload) return;
+ const bursts = Array.isArray(payload.bursts) ? payload.bursts : [];
+ for (const b of bursts) if (b?.emoji) overlay.burst(b.emoji, 1);
+ if (Number.isFinite(payload.total)) setCount(payload.total);
+ }
+
+ // Optional self-managed SSE: surfaces that don't already own a stream client
+ // (the single-agent screen) let the controller subscribe to reaction events
+ // directly. Surfaces that already have a per-agent EventSource (the wall) pass
+ // subscribe:false and forward events into onReaction() instead — no second
+ // connection per card.
+ let es = null;
+ if (subscribe && typeof EventSource !== 'undefined') {
+ try {
+ es = new EventSource(`/api/agent-screen-stream?agentId=${encodeURIComponent(agentId)}`);
+ es.addEventListener('open', () => setConnectedState(true));
+ es.addEventListener('reaction', (e) => { try { onReaction(JSON.parse(e.data)); } catch { /* malformed */ } });
+ es.onerror = () => setConnectedState(false);
+ } catch { /* no stream — the bar still posts reactions and tips work */ }
+ }
+
+ function setConnectedState(connected) {
+ bar.classList.toggle('connecting', !connected);
+ }
+
+ const onPageHide = () => { try { es?.close(); } catch { /* */ } };
+ if (es) window.addEventListener('pagehide', onPageHide);
+
return {
- // Forward a stream `reaction` event: { bursts:[{emoji,ts}], total }.
- onReaction(payload) {
- if (destroyed || !payload) return;
- const bursts = Array.isArray(payload.bursts) ? payload.bursts : [];
- for (const b of bursts) if (b?.emoji) overlay.burst(b.emoji, 1);
- if (Number.isFinite(payload.total)) setCount(payload.total);
- },
+ onReaction,
onTip,
- setConnected(connected) {
- bar.classList.toggle('connecting', !connected);
- },
+ setConnected: setConnectedState,
destroy() {
destroyed = true;
window.removeEventListener('three:patron-support', onPatron);
+ window.removeEventListener('pagehide', onPageHide);
+ try { es?.close(); } catch { /* */ }
clearTimeout(cueTimer);
overlay.destroy();
bar.remove();
diff --git a/src/agent-screen-diary.js b/src/agent-screen-diary.js
index dafcead61..2f4541a0c 100644
--- a/src/agent-screen-diary.js
+++ b/src/agent-screen-diary.js
@@ -120,6 +120,23 @@ export function createDiaryPanel({ agentId, body, getAvatar, pauseOtherNarration
},
});
+ // Self-trigger: load + (gesture-permitting) narrate the first time the panel
+ // becomes visible, and keep the graph canvas sized to the panel. This keeps
+ // the heavily co-edited host from having to wire toggle/resize callbacks.
+ const panelRoot = body.closest('.asc-panel');
+ let panelObserver = null;
+ if (panelRoot) {
+ panelObserver = new MutationObserver(() => {
+ if (!panelRoot.hidden && !panelRoot.classList.contains('minimized')) onOpen();
+ });
+ panelObserver.observe(panelRoot, { attributes: true, attributeFilter: ['hidden', 'class'] });
+ }
+ let canvasObserver = null;
+ if (typeof ResizeObserver !== 'undefined') {
+ canvasObserver = new ResizeObserver(() => graph?.resize());
+ canvasObserver.observe(els.canvas);
+ }
+
els.narrate.addEventListener('click', () => {
if (speaking) stopNarration();
else narrate({ userGesture: true });
@@ -292,6 +309,7 @@ export function createDiaryPanel({ agentId, body, getAvatar, pauseOtherNarration
analyserData = null;
mouthTarget.setMouthShape({ open: 0 });
setNarrateUi(false);
+ els.text.classList.remove('is-typing');
// Restore the full text in case a reveal was mid-flight.
if (digest?.diaryText && els.text.textContent !== digest.diaryText) els.text.textContent = digest.diaryText;
}
@@ -346,9 +364,11 @@ export function createDiaryPanel({ agentId, body, getAvatar, pauseOtherNarration
const onEnd = () => {
if (myToken !== speakToken) return;
speaking = false;
+ if (revealRaf) { cancelAnimationFrame(revealRaf); revealRaf = null; }
mouthTarget.setMouthShape({ open: 0 });
setNarrateUi(false);
els.text.textContent = text; // ensure fully shown
+ els.text.classList.remove('is-typing');
};
audioEl.addEventListener('ended', onEnd, { once: true });
audioEl.addEventListener('error', onEnd, { once: true });
@@ -371,6 +391,7 @@ export function createDiaryPanel({ agentId, body, getAvatar, pauseOtherNarration
const entities = digest?.entities || [];
revealStart = (typeof performance !== 'undefined' ? performance.now() : Date.now());
els.text.textContent = '';
+ els.text.classList.add('is-typing');
const step = () => {
revealRaf = requestAnimationFrame(step);
let progress;
@@ -396,6 +417,7 @@ export function createDiaryPanel({ agentId, body, getAvatar, pauseOtherNarration
if (progress >= 1 && !audio) {
cancelAnimationFrame(revealRaf); revealRaf = null;
els.text.textContent = text;
+ els.text.classList.remove('is-typing');
}
};
revealRaf = requestAnimationFrame(step);
@@ -483,6 +505,8 @@ export function createDiaryPanel({ agentId, body, getAvatar, pauseOtherNarration
stopNarration();
clearTimeout(refreshTimer);
try { sse?.disconnect(); } catch { /* */ }
+ try { panelObserver?.disconnect(); } catch { /* */ }
+ try { canvasObserver?.disconnect(); } catch { /* */ }
graph?.dispose();
mouthTarget.dispose();
}
diff --git a/src/agent-screen-reputation.js b/src/agent-screen-reputation.js
new file mode 100644
index 000000000..7a2012bc4
--- /dev/null
+++ b/src/agent-screen-reputation.js
@@ -0,0 +1,243 @@
+// Reputation panel for the agent screen — the trust story beside the avatar.
+//
+// Two real, verifiable layers, stacked:
+// 1. The full wallet-trust breakdown (score, tier, pillars, on-chain evidence)
+// via the shared reputationPanelEl — the same non-gameable score the badge
+// shows everywhere, computed server-side from real ledger + chain facts.
+// 2. The a2a-hire RECEIPTS that built it: every completed hire this agent was
+// paid for, each a real USDC settlement with an explorer link and, once the
+// hirer rates it, the 1–5★ that moves the score. A tiny sparkline draws the
+// agent's real rating history over those receipts.
+//
+// Nothing is computed or faked here. Receipts come from
+// GET /api/agents/economy?view=hires&role=provider; an agent with no hires yet
+// renders an honest empty state, never a fabricated history.
+
+import { apiFetch } from './api.js';
+import { reputationPanelEl, ensureReputationStyles } from './shared/agent-reputation.js';
+
+const esc = (s) =>
+ String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+
+function fmtUsd(n) {
+ const v = Number(n) || 0;
+ return v >= 1000 ? `$${(v / 1000).toFixed(1)}k` : `$${v.toFixed(2)}`;
+}
+
+function fmtTime(iso) {
+ if (!iso) return '';
+ try {
+ const diff = (Date.now() - new Date(iso).getTime()) / 1000;
+ if (diff < 90) return 'just now';
+ if (diff < 3600) return `${Math.round(diff / 60)}m ago`;
+ if (diff < 86400) return `${Math.round(diff / 3600)}h ago`;
+ if (diff < 604800) return `${Math.round(diff / 86400)}d ago`;
+ return new Date(iso).toLocaleDateString();
+ } catch {
+ return '';
+ }
+}
+
+// USDC settlements and the agent-invocation receipt both land on Solana mainnet.
+function explorerUrl(sig) {
+ return sig ? `https://solscan.io/tx/${encodeURIComponent(sig)}` : null;
+}
+
+const STATUS_TONE = { completed: 'ok', pending: 'warn', refunded: 'dim', failed: 'bad', disputed: 'bad' };
+
+function starsHTML(rating) {
+ if (rating == null) return '<span class="ascrep-rc-unrated">unrated</span>';
+ const r = Math.max(0, Math.min(5, Math.round(rating)));
+ return `<span class="ascrep-rc-stars" title="${r}/5">${'★'.repeat(r)}${'☆'.repeat(5 - r)}</span>`;
+}
+
+// A real rating history sparkline from the rated receipts (chronological).
+function sparklineHTML(hires) {
+ const rated = hires
+ .filter((h) => h.rating != null)
+ .slice()
+ .reverse(); // listHiresForAgent is newest-first → oldest-first for the timeline
+ if (rated.length < 2) return '';
+ const W = 240;
+ const H = 34;
+ const pad = 3;
+ const pts = rated.map((h, i) => {
+ const x = pad + (i / (rated.length - 1)) * (W - pad * 2);
+ const y = pad + (1 - (Math.max(1, Math.min(5, h.rating)) - 1) / 4) * (H - pad * 2);
+ return `${x.toFixed(1)},${y.toFixed(1)}`;
+ });
+ const avg = (rated.reduce((s, h) => s + h.rating, 0) / rated.length).toFixed(1);
+ const dots = pts
+ .map((p) => {
+ const [x, y] = p.split(',');
+ return `<circle cx="${x}" cy="${y}" r="1.7" fill="var(--screen-accent,#9a7bff)"/>`;
+ })
+ .join('');
+ return (
+ `<div class="ascrep-spark"><div class="ascrep-spark-head"><span>Rating history</span><span class="ascrep-spark-avg">${avg}★ avg · ${rated.length} rated</span></div>` +
+ `<svg viewBox="0 0 ${W} ${H}" preserveAspectRatio="none" role="img" aria-label="Rating history sparkline, average ${avg} of 5">` +
+ `<polyline fill="none" stroke="var(--screen-accent,#9a7bff)" stroke-width="1.5" stroke-linejoin="round" stroke-linecap="round" points="${pts.join(' ')}"/>${dots}</svg></div>`
+ );
+}
+
+function receiptHTML(h) {
+ const tone = STATUS_TONE[h.status] || 'dim';
+ const links = [
+ h.payment_signature ? `<a class="ascrep-rc-link" href="${esc(explorerUrl(h.payment_signature))}" target="_blank" rel="noopener noreferrer">payment ↗</a>` : '',
+ h.invocation_signature ? `<a class="ascrep-rc-link" href="${esc(explorerUrl(h.invocation_signature))}" target="_blank" rel="noopener noreferrer">receipt ↗</a>` : '',
+ ]
+ .filter(Boolean)
+ .join('');
+ return (
+ `<li class="ascrep-rc">` +
+ `<div class="ascrep-rc-top">` +
+ `<span class="ascrep-rc-skill" title="${esc(h.skill_name || h.service_slug || 'hire')}">${esc(h.skill_name || h.service_slug || 'Hire')}</span>` +
+ `<span class="ascrep-rc-amt">${esc(fmtUsd(h.usd))}</span>` +
+ `</div>` +
+ `<div class="ascrep-rc-mid">${starsHTML(h.rating)}<span class="ascrep-rc-status ascrep-rc-status--${tone}">${esc(h.status)}</span></div>` +
+ `<div class="ascrep-rc-bot">` +
+ `<span class="ascrep-rc-cp" title="Hired by ${esc(h.counterparty?.name || 'agent')}">↤ ${esc(h.counterparty?.name || 'Agent')}</span>` +
+ `<span class="ascrep-rc-time">${esc(fmtTime(h.completed_at || h.created_at))}</span>` +
+ (links ? `<span class="ascrep-rc-links">${links}</span>` : '') +
+ `</div></li>`
+ );
+}
+
+let _stylesInjected = false;
+function ensureStyles() {
+ if (_stylesInjected || typeof document === 'undefined') return;
+ _stylesInjected = true;
+ const st = document.createElement('style');
+ st.id = 'ascrep-style';
+ st.textContent = `
+.ascrep-body{display:flex;flex-direction:column;gap:0.7rem;padding:0.2rem 0.1rem}
+.ascrep-receipts-head{display:flex;align-items:baseline;justify-content:space-between;gap:0.5rem;margin-top:0.2rem}
+.ascrep-receipts-title{font-size:0.64rem;text-transform:uppercase;letter-spacing:0.06em;color:rgba(255,255,255,0.42);font-weight:650}
+.ascrep-receipts-sub{font-size:0.66rem;color:rgba(255,255,255,0.32)}
+.ascrep-spark{background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.08);border-radius:9px;padding:0.5rem 0.6rem}
+.ascrep-spark-head{display:flex;justify-content:space-between;font-size:0.64rem;color:rgba(255,255,255,0.42);margin-bottom:0.25rem}
+.ascrep-spark-avg{color:var(--screen-accent,#9a7bff);font-weight:650}
+.ascrep-spark svg{width:100%;height:34px;display:block}
+.ascrep-list{list-style:none;margin:0;padding:0;display:flex;flex-direction:column;gap:0.4rem;max-height:280px;overflow-y:auto}
+.ascrep-rc{background:rgba(255,255,255,0.03);border:1px solid rgba(255,255,255,0.08);border-radius:9px;padding:0.45rem 0.6rem;transition:border-color .14s,background .14s}
+.ascrep-rc:hover{border-color:rgba(255,255,255,0.18);background:rgba(255,255,255,0.05)}
+.ascrep-rc-top{display:flex;justify-content:space-between;align-items:baseline;gap:0.5rem}
+.ascrep-rc-skill{font-size:0.8rem;font-weight:640;color:#f4f4f5;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
+.ascrep-rc-amt{font-size:0.78rem;font-weight:680;color:#86efac;font-variant-numeric:tabular-nums;white-space:nowrap}
+.ascrep-rc-mid{display:flex;align-items:center;gap:0.5rem;margin:0.25rem 0}
+.ascrep-rc-stars{color:#fbbf24;font-size:0.74rem;letter-spacing:0.04em}
+.ascrep-rc-unrated{font-size:0.66rem;color:rgba(255,255,255,0.3)}
+.ascrep-rc-status{font-size:0.6rem;text-transform:uppercase;letter-spacing:0.04em;font-weight:650;padding:1px 6px;border-radius:999px}
+.ascrep-rc-status--ok{color:#86efac;background:rgba(134,239,172,0.12)}
+.ascrep-rc-status--warn{color:#fcd34d;background:rgba(252,211,77,0.12)}
+.ascrep-rc-status--bad{color:#fda4af;background:rgba(253,164,175,0.12)}
+.ascrep-rc-status--dim{color:rgba(255,255,255,0.5);background:rgba(255,255,255,0.06)}
+.ascrep-rc-bot{display:flex;align-items:center;gap:0.5rem;font-size:0.66rem;color:rgba(255,255,255,0.42);flex-wrap:wrap}
+.ascrep-rc-cp{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;max-width:9rem}
+.ascrep-rc-time{margin-left:auto}
+.ascrep-rc-links{display:flex;gap:0.4rem;flex-basis:100%}
+.ascrep-rc-link{color:var(--screen-accent,#9a7bff);text-decoration:none;font-weight:600}
+.ascrep-rc-link:hover{text-decoration:underline}
+.ascrep-empty,.ascrep-error{text-align:center;padding:0.9rem 0.6rem;font-size:0.74rem;color:rgba(255,255,255,0.5);line-height:1.45}
+.ascrep-empty a{color:var(--screen-accent,#9a7bff);text-decoration:none;font-weight:600}
+.ascrep-empty a:hover{text-decoration:underline}
+.ascrep-retry{margin-top:0.5rem;font:inherit;font-size:0.74rem;font-weight:600;color:#fff;background:rgba(154,123,255,0.18);border:1px solid rgba(154,123,255,0.45);border-radius:8px;padding:0.35rem 0.8rem;cursor:pointer}
+.ascrep-retry:hover{background:rgba(154,123,255,0.3)}
+.ascrep-sk{height:48px;border-radius:9px;background:linear-gradient(90deg,rgba(255,255,255,0.03) 25%,rgba(255,255,255,0.07) 37%,rgba(255,255,255,0.03) 63%);background-size:400% 100%;animation:ascrep-shimmer 1.4s ease infinite}
+@keyframes ascrep-shimmer{0%{background-position:100% 50%}100%{background-position:0 50%}}
+@media (prefers-reduced-motion:reduce){.ascrep-sk{animation:none}}`;
+ document.head.appendChild(st);
+}
+
+/**
+ * Mount the reputation panel into a panel body. Self-loading and self-healing:
+ * the trust breakdown and the receipts each render their own loading → populated
+ * → error states, and a new completed hire pushed onto the log refreshes the
+ * receipts.
+ *
+ * @param {object} opts
+ * @param {string} opts.agentId
+ * @param {HTMLElement} opts.bodyEl
+ * @returns {{ refresh():void, observeHire():void, destroy():void }}
+ */
+export function createReputationPanel({ agentId, bodyEl }) {
+ ensureReputationStyles();
+ ensureStyles();
+ bodyEl.classList.add('ascrep-body');
+
+ // Layer 1: the shared trust breakdown (loads its own real data).
+ const breakdown = reputationPanelEl(agentId, { unlocks: false });
+ bodyEl.appendChild(breakdown);
+
+ // Layer 2: the receipts that earned the score.
+ const receipts = document.createElement('div');
+ receipts.className = 'ascrep-receipts';
+ bodyEl.appendChild(receipts);
+
+ let _loaded = false;
+ let _loading = false;
+
+ function skeleton() {
+ receipts.innerHTML =
+ `<div class="ascrep-receipts-head"><span class="ascrep-receipts-title">A2A-hire receipts</span></div>` +
+ `<div class="ascrep-sk"></div><div class="ascrep-sk" style="margin-top:0.4rem"></div>`;
+ }
+
+ async function load() {
+ if (_loading) return;
+ _loading = true;
+ if (!_loaded) skeleton();
+ try {
+ const res = await apiFetch(
+ `/api/agents/economy?view=hires&role=provider&limit=40&agentId=${encodeURIComponent(agentId)}`,
+ { allowAnonymous: true },
+ );
+ if (!res.ok) throw new Error(`hires ${res.status}`);
+ const { data } = await res.json();
+ const hires = Array.isArray(data?.hires) ? data.hires : [];
+ _loaded = true;
+ render(hires);
+ } catch {
+ receipts.innerHTML =
+ `<div class="ascrep-receipts-head"><span class="ascrep-receipts-title">A2A-hire receipts</span></div>` +
+ `<div class="ascrep-error" role="alert">Couldn't load this agent's hire receipts just now.<br>` +
+ `<button type="button" class="ascrep-retry">Try again</button></div>`;
+ receipts.querySelector('.ascrep-retry')?.addEventListener('click', load);
+ } finally {
+ _loading = false;
+ }
+ }
+
+ function render(hires) {
+ if (!hires.length) {
+ receipts.innerHTML =
+ `<div class="ascrep-receipts-head"><span class="ascrep-receipts-title">A2A-hire receipts</span></div>` +
+ `<div class="ascrep-empty">No hires yet — this agent earns on-chain reputation by completing paid hires.<br>` +
+ `<a href="/marketplace">Browse the marketplace →</a></div>`;
+ return;
+ }
+ const total = hires.length;
+ receipts.innerHTML =
+ `<div class="ascrep-receipts-head"><span class="ascrep-receipts-title">A2A-hire receipts</span><span class="ascrep-receipts-sub">${total} hire${total === 1 ? '' : 's'} earned</span></div>` +
+ sparklineHTML(hires) +
+ `<ul class="ascrep-list">${hires.map(receiptHTML).join('')}</ul>`;
+ }
+
+ load();
+
+ // Refresh the receipts when this agent settles a new hire (an a2a_hire frame
+ // reaches the screen log). Debounced so a burst of frames is one refetch.
+ let _hireT = null;
+ function observeHire() {
+ clearTimeout(_hireT);
+ _hireT = setTimeout(load, 1500);
+ }
+
+ return {
+ refresh: load,
+ observeHire,
+ destroy() {
+ clearTimeout(_hireT);
+ },
+ };
+}
diff --git a/src/agent-screen-treasury.js b/src/agent-screen-treasury.js
index 1c109aa4d..2eee5ae53 100644
--- a/src/agent-screen-treasury.js
+++ b/src/agent-screen-treasury.js
@@ -117,6 +117,8 @@ export function createTreasuryCockpit({ agentId, bodyEl, toast, network = 'mainn
data.coins = mine;
const host = bodyEl.querySelector('#ast-coins');
if (host) host.innerHTML = renderCoins(mine);
+ const wrap = bodyEl.querySelector('#ast-coins-wrap');
+ if (wrap) wrap.hidden = !mine.length;
bindCoinToggles();
} catch { /* non-fatal */ }
}
diff --git a/src/agent-screen.js b/src/agent-screen.js
index 12917abe5..b947676b8 100644
--- a/src/agent-screen.js
+++ b/src/agent-screen.js
@@ -35,12 +35,14 @@ import { makeGltfRig, poseFromMannequinPreset } from './pose-rig.js';
import { matchPose, presetPoseById, POSE_QUICK_PICKS } from './pose-match.js';
import { StageShow } from './agent-screen-stage.js';
import { createAgentScreenClient } from './shared/agent-screen-client.js';
+import { mountAgentReactions } from './agent-reactions.js';
import { handleTourFrame } from './agent-screen-tour.js';
import { buildRunCommand, buildRunCommandHtml, RUNTIME_LABELS } from './agent-screen-runcmd.js';
import { createNewsroomAnchor } from './agent-screen-anchor.js';
import { createTreasuryCockpit } from './agent-screen-treasury.js';
import { MirrorPanel } from './agent-screen-mirror.js';
import { createHireVisualizer } from './agent-screen-hire.js';
+import { createDiaryPanel } from './agent-screen-diary.js';
import {
parsePnlDelta, accumulatePnl, emptyPnlState, unrealizedTotalUsd, emoteForExit, formatSol, formatUsd,
} from './shared/trade-pnl.js';
@@ -50,6 +52,14 @@ import {
renderLaunchHud, truncMid,
} from './launch-director.js';
import { parseGrindCommand } from './vanity-grind-director.js';
+import {
+ clampPrompt,
+ validatePrompt,
+ forgeStageNarration,
+ finalForgeFrame,
+ parseForgeFrame,
+ viewerLinkFor,
+} from './shared/forge-frames.js';
import { agentAvatarGlb } from './shared/agent-3d.js';
import { getMeshoptDecoder } from './viewer/internal.js';
import { ScreenshotModal } from './components/screenshot-modal.js';
@@ -540,8 +550,9 @@ function defaultLayout() {
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 },
stage: { hidden: false, min: false, x: null, y: null, w: 320, h: null },
- heatmap: { hidden: false, min: false, x: null, y: null, w: 460, h: 340 },
+ heatmap: { hidden: true, min: false, x: null, y: null, w: 460, h: 340 },
hud: { hidden: false, min: false, x: null, y: null, w: 288, h: null },
+ diary: { hidden: true, min: false, x: null, y: null, w: 360, h: 332 },
hire: { hidden: false, min: false, x: null, y: null, w: 340, h: null },
},
};
@@ -799,19 +810,34 @@ async function boot(id) {
<div class="asc-resize" data-resize="wh"></div>
</div>
+ <!-- Memory Diary panel -->
+ <div class="asc-panel asc-panel--diary" id="asc-panel-diary" data-panel="diary">
+ <div class="asc-panel-head" data-drag>
+ <span class="asc-panel-grip">⠿</span>
+ <span class="asc-panel-title">Diary</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 (D)">✕</button>
+ </div>
+ </div>
+ <div class="asc-panel-body" id="asc-diary-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">
- <div class="asc-task-icon">▶</div>
+ <button class="asc-task-mode" id="asc-task-mode" type="button" hidden aria-pressed="false" title="Asking live — click to queue a background task">Ask</button>
<input
class="asc-task-input"
id="asc-task-input"
type="text"
- placeholder="Give your agent a task… (research, browse, or: launch a coin named … ticker … uri https://…)"
+ placeholder="Ask this agent anything…"
maxlength="1000"
spellcheck="false"
>
- <button class="asc-task-send" id="asc-task-send" type="submit" title="Send task">
+ <button class="asc-task-voice" id="asc-task-voice" type="button" aria-pressed="false" title="Voice on — click to mute">🔊</button>
+ <button class="asc-task-send" id="asc-task-send" type="submit" title="Send">
<svg width="16" height="16" viewBox="0 0 16 16" fill="none" xmlns="http://www.w3.org/2000/svg">
<path d="M14.5 8L1.5 1.5L5 8L1.5 14.5L14.5 8Z" fill="currentColor"/>
</svg>
@@ -859,6 +885,7 @@ async function boot(id) {
// ── resolve agent metadata ─────────────────────────────────────────────
let agentName = 'Agent';
+ let agentRecord = null; // freshest agent record, for the tip modal's wallet resolution
let avatarGlbUrl = null;
// Q&A concierge state: whether this viewer owns the agent (unlocks the
// queue-a-task mode) and the agent's configured TTS voice for spoken answers.
@@ -871,6 +898,7 @@ async function boot(id) {
if (res.ok) {
const j = await res.json();
const agent = j.agent || j;
+ agentRecord = agent;
agentName = agent.name || 'Agent';
agentNameEl.textContent = agentName;
document.title = `${agentName} · Agent Screen · three.ws`;
@@ -1018,12 +1046,102 @@ async function boot(id) {
webcamBezel.appendChild(webcamCanvas);
webcamBadge.style.display = 'flex';
+ // ── pose performance helpers (Pose Studio Live) ──────────────────
+ const POSE_IN_MS = 420, POSE_HOLD_MS = 2600, POSE_OUT_MS = 640;
+ // Head-and-shoulders cam: skip lower-body bones so a pose never tips the
+ // framed avatar. Upper-body joints carry every pose that reads on a webcam.
+ const POSE_SKIP = new Set(['Hips', 'LeftUpLeg', 'LeftLeg', 'LeftFoot', 'LeftToeBase', 'RightUpLeg', 'RightLeg', 'RightFoot', 'RightToeBase']);
+ const easeInOut = (x) => (x < 0.5 ? 2 * x * x : 1 - Math.pow(-2 * x + 2, 2) / 2);
+
+ // Tween from the avatar's current displayed pose to the preset's joint map,
+ // hold, then blend back into the live idle. Re-derives the rig from the
+ // current model so it keeps working after a Live-Forge avatar swap.
+ function startPoseDriver(poseMap, label) {
+ if (webcamAvatar && (!poseRig || poseRig.root !== webcamAvatar)) {
+ poseRig = makeGltfRig(webcamAvatar);
+ }
+ if (!poseRig) return false;
+ const canonical = poseFromMannequinPreset(poseMap).bones || {};
+ const targets = [];
+ for (const [key, v] of Object.entries(canonical)) {
+ if (POSE_SKIP.has(key) || !Array.isArray(v) || v.length < 4) continue;
+ const node = poseRig.getNode(key);
+ if (!node) continue;
+ targets.push({ node, from: node.quaternion.clone(), to: new Quaternion(v[0], v[1], v[2], v[3]) });
+ }
+ if (!targets.length) return false;
+ // Keep the mixer's base layer on idle so the pose releases into a live
+ // idle, not a held emote.
+ webcamAnimManager?.crossfadeTo('idle', 0.3);
+ poseClipSettleAt = 0;
+ poseDriver = { targets, t0: performance.now(), label };
+ return true;
+ }
+
+ // Per-frame: apply the active pose tween ON TOP of the idle the mixer just
+ // wrote (called after webcamAnimManager.update). Ease in → hold → ease out.
+ function updatePoseDriver(t) {
+ if (!poseDriver) return;
+ const e = t - poseDriver.t0;
+ const { targets } = poseDriver;
+ if (e <= POSE_IN_MS) {
+ const w = easeInOut(e / POSE_IN_MS);
+ for (const tg of targets) tg.node.quaternion.copy(tg.from).slerp(tg.to, w);
+ } else if (e <= POSE_IN_MS + POSE_HOLD_MS) {
+ for (const tg of targets) tg.node.quaternion.copy(tg.to);
+ } else if (e <= POSE_IN_MS + POSE_HOLD_MS + POSE_OUT_MS) {
+ const w = easeInOut((e - POSE_IN_MS - POSE_HOLD_MS) / POSE_OUT_MS);
+ // node.quaternion holds the live idle frame the mixer just wrote.
+ for (const tg of targets) {
+ _poseTmpQuat.copy(tg.to).slerp(tg.node.quaternion, w);
+ tg.node.quaternion.copy(_poseTmpQuat);
+ }
+ } else {
+ poseDriver = null;
+ }
+ }
+
+ // Perform a resolved pose action: a static pose tween, or a real animated
+ // emote clip with a graceful static fallback (failed load / fallen-pose
+ // guard rejection). Debounced so rapid requests don't stomp a transition.
+ performPose = async function performPoseImpl(action) {
+ if (!action) return;
+ const now = performance.now();
+ if (now - lastPoseAt < 200) return;
+ lastPoseAt = now;
+ addLogEntry({ ts: Date.now(), activity: `Pose: ${action.label}`, type: 'analysis' });
+
+ if (action.kind === 'pose') { startPoseDriver(action.parameters, action.label); return; }
+
+ const fallback = () => {
+ const fb = action.fallbackPreset && presetPoseById(action.fallbackPreset);
+ if (fb) startPoseDriver(fb, action.label);
+ };
+ if (!webcamAnimManager || !webcamAnimManager.supportsCanonicalClips()) { fallback(); return; }
+ const ready = await webcamAnimManager.ensureLoaded(action.clip);
+ if (!ready || !webcamAnimManager.canPlay(action.clip)) { fallback(); return; }
+ poseDriver = null; // the clip drives the whole body
+ const def = webcamAnimManager.getAnimationDefs().find((d) => d.name === action.clip);
+ const looping = def ? def.loop !== false : false;
+ if (looping) {
+ await webcamAnimManager.crossfadeTo(action.clip, 0.4);
+ if (webcamAnimManager.currentName === action.clip) poseClipSettleAt = performance.now() + 3400;
+ else fallback();
+ } else {
+ poseClipSettleAt = 0;
+ await webcamAnimManager.playOnce(action.clip, { settleTo: 'idle', fade: 0.4 });
+ if (webcamAnimManager.currentName !== action.clip) fallback();
+ }
+ };
+
let last = 0;
function webcamTick(t) {
webcamRafId = requestAnimationFrame(webcamTick);
const dt = Math.min((t - last) / 1000, 0.1);
last = t;
webcamAnimManager?.update(dt);
+ // Settle a looping pose-emote back to idle once its hold elapses.
+ if (poseClipSettleAt && t >= poseClipSettleAt) { poseClipSettleAt = 0; webcamAnimManager?.crossfadeTo('idle', 0.5); }
anchor?.tick();
// Host presence in Ambient mode: a gentle two-frequency yaw so the
// avatar reads as glancing around the world it's narrating, not frozen.
@@ -1035,6 +1153,8 @@ async function boot(id) {
if (Math.abs(webcamAvatar.rotation.y) < 0.001) webcamAvatar.rotation.y = 0;
}
lipsyncSampler?.();
+ syncTalkingEmote();
+ updatePoseDriver(t); // apply any active static pose on top of idle
webcamRenderer.render(webcamScene, webcamCamera);
}
webcamRafId = requestAnimationFrame(webcamTick);
@@ -1312,36 +1432,90 @@ async function boot(id) {
}
setInterval(updateStats, 1000);
- // ── activity log ──────────────────────────────────────────────────────
+ // ── activity log (cinematic) ───────────────────────────────────────────
+ // Each real action renders through classify(): an icon, a colour-graded chip,
+ // and a severity ring (high → amber, celebratory → gold). Consecutive same-
+ // kind actions collapse into one beat with a ×N count instead of flooding the
+ // log. Newest is at the top; a "jump to latest" affordance appears when the
+ // viewer has scrolled away.
const MAX_LOG = 120;
let logCount = 0;
+ let lastBeat = null; // { key, el, count } — top row, for collapsing
+ const REDUCED = typeof matchMedia === 'function' && matchMedia('(prefers-reduced-motion: reduce)').matches;
+
+ // Map a classify category onto the existing filter buckets (trade/analysis/
+ // activity) so the filter chips keep working across the richer taxonomy.
+ function filterBucket(category) {
+ if (category === 'buy' || category === 'sell' || category === 'trade') return 'trade';
+ if (category === 'analysis' || category === 'memory') return 'analysis';
+ return 'activity';
+ }
function fmtTime(ts) {
const d = new Date(ts);
return d.toLocaleTimeString(undefined, { hour: '2-digit', minute: '2-digit', second: '2-digit' });
}
- 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}`;
+ // "Jump to latest" — newest sits at the top, so this scrolls the log home.
+ const jumpBtn = document.createElement('button');
+ jumpBtn.className = 'asc-log-jump';
+ jumpBtn.type = 'button';
+ jumpBtn.hidden = true;
+ jumpBtn.innerHTML = '↑ Latest';
+ jumpBtn.addEventListener('click', () => {
+ logEl.scrollTo({ top: 0, behavior: REDUCED ? 'auto' : 'smooth' });
+ });
+ logEl.parentElement.appendChild(jumpBtn);
+ logEl.addEventListener('scroll', () => { jumpBtn.hidden = logEl.scrollTop < 24; }, { passive: true });
+
+ function renderBeatRow(entry, { ts, activity, type, pnl }, count) {
+ const c = classify({ ts, activity, type });
+ const accent = colorHex(c.colorToken);
+ const bucket = filterBucket(c.category);
+ entry.className = `asc-log-entry type-${bucket} cat-${c.category} sev-${c.severity}`;
+ entry.style.setProperty('--asc-accent', accent);
// 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.classList.toggle('pnl-pos', v > 0);
+ entry.classList.toggle('pnl-neg', v < 0);
}
+ const badge = count > 1 ? `<span class="asc-log-count">×${count}</span>` : '';
entry.innerHTML = `
<span class="asc-log-time">${fmtTime(ts || Date.now())}</span>
- <span class="asc-log-type ${typeLabel}">${typeLabel}</span>
+ <span class="asc-log-icon" aria-hidden="true">${c.icon}</span>
+ <span class="asc-log-type" style="color:${accent}">${esc(c.label)}</span>
<span class="asc-log-text">${esc(activity || '')}</span>
+ ${badge}
`;
+ }
+
+ function addLogEntry(raw) {
+ if (logEmpty) { logEmpty.remove(); logEmpty = null; }
+ const key = classify({ type: raw.type }).category;
+
+ // Collapse a run of same-category actions into the existing top beat.
+ if (lastBeat && lastBeat.key === key && logEl.firstElementChild === lastBeat.el) {
+ lastBeat.count += 1;
+ renderBeatRow(lastBeat.el, raw, lastBeat.count);
+ if (!REDUCED) {
+ lastBeat.el.classList.remove('beat-bump');
+ void lastBeat.el.offsetWidth; // restart the bump animation
+ lastBeat.el.classList.add('beat-bump');
+ }
+ return;
+ }
+
+ const entry = document.createElement('div');
+ renderBeatRow(entry, raw, 1);
logEl.prepend(entry);
+ lastBeat = { key, el: entry, count: 1 };
logCount++;
while (logCount > MAX_LOG) {
- logEl.lastElementChild?.remove();
+ const removed = logEl.lastElementChild;
+ if (removed === lastBeat?.el) lastBeat = null;
+ removed?.remove();
logCount--;
}
}
@@ -1352,6 +1526,7 @@ async function boot(id) {
if (btn.id === 'asc-log-clear') {
logEl.querySelectorAll('.asc-log-entry').forEach((e) => e.remove());
logCount = 0;
+ lastBeat = null;
logEmpty = document.createElement('div');
logEmpty.className = 'asc-log-empty';
logEmpty.textContent = 'No activity yet';
@@ -1463,6 +1638,61 @@ async function boot(id) {
webcamAnimManager.playOnce(clip, { settleTo: 'idle' }).catch(() => {});
}
+ // ── Q&A concierge avatar emotes ──────────────────────────────────────────
+ // thinking: a waiting pose held while the answer streams.
+ // talking: an upper-body gesture overlaid (additive) while the agent speaks,
+ // driven off the anchor's real speaking state so it stays in time
+ // with the voice — and so bulletins get the same liveliness for free.
+ let qaThinking = false; // a question is in flight / answer streaming
+ let talkingEmoteOn = false; // additive talking overlay currently playing
+ function emoteCan(name) {
+ return !!webcamAnimManager?.supportsCanonicalClips?.() && webcamAnimManager.canPlay(name);
+ }
+ function avatarThinking() {
+ qaThinking = true;
+ if (emoteCan('av-waiting')) webcamAnimManager.crossfadeTo('av-waiting', 0.35);
+ }
+ function avatarSettle() {
+ qaThinking = false;
+ // If a voice is still playing, the talking overlay owns the body; the
+ // settle-to-idle happens when speech ends (syncTalkingEmote).
+ if (!talkingEmoteOn && emoteCan('idle')) webcamAnimManager.crossfadeTo('idle', 0.4);
+ }
+ // Reconcile the additive talking overlay with whether the agent is actually
+ // speaking. Called every webcam frame.
+ function syncTalkingEmote() {
+ if (!webcamAnimManager?.supportsCanonicalClips?.()) return;
+ const speaking = !!anchor?.isSpeaking?.();
+ if (speaking && !talkingEmoteOn) {
+ talkingEmoteOn = true;
+ if (emoteCan('idle') && webcamAnimManager.currentName === 'av-waiting') {
+ webcamAnimManager.crossfadeTo('idle', 0.3); // drop the thinking pose under the gesture
+ }
+ if (emoteCan('av-vtubing')) {
+ webcamAnimManager.playOverlay('av-vtubing', { loop: true, upperBodyOnly: true, crossfade: 0.3 }).catch(() => {});
+ }
+ } else if (!speaking && talkingEmoteOn) {
+ talkingEmoteOn = false;
+ webcamAnimManager.stopOverlay({ crossfade: 0.3 });
+ if (!qaThinking && emoteCan('idle')) webcamAnimManager.crossfadeTo('idle', 0.4);
+ }
+ }
+
+ // De-dupe the multi-watcher echo: questions/answers we render locally also
+ // arrive back over the SSE log (api/agent-ask echoes them so other watchers
+ // see the exchange). Remember the exact strings we rendered and drop the
+ // matching echo once, so the asker never sees a duplicate.
+ const ECHO_MAX = 240; // within the server-side activity slice
+ const pendingEchoes = new Set();
+ function rememberEcho(text) {
+ pendingEchoes.add(String(text).slice(0, ECHO_MAX));
+ }
+ function isOwnEcho(activity) {
+ const key = String(activity || '').slice(0, ECHO_MAX);
+ if (pendingEchoes.has(key)) { pendingEchoes.delete(key); return true; }
+ return false;
+ }
+
// compact ⇄ detailed toggle (click or keyboard focus + Enter/Space on the button)
pnlBtn.addEventListener('click', () => {
pnlDetailed = !pnlDetailed;
@@ -1473,8 +1703,46 @@ async function boot(id) {
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)
+ let diaryPanel = null; // set once the Diary panel mounts (below)
let pnlHud = null; // set once the Portfolio HUD panel mounts (below)
let hireViz = null; // set once the Live Hire panel mounts (below)
+
+ // ── spectator reactions + tips ───────────────────────────────────────────
+ // A reaction bar under the stream: tap an emoji and it floats up over the
+ // screen for everyone watching; tip and real value lands in the agent's wallet,
+ // the avatar emotes, and it says thanks in its own voice. $THREE only. The
+ // controller self-subscribes to the stream's reaction events, so it stays
+ // decoupled from the frame client below.
+ let reactions = null;
+ const screenStageEl = stageEl.querySelector('.asc-screen-stage');
+ if (screenStageEl) {
+ if (!document.getElementById('asc-reactions-pos')) {
+ const st = document.createElement('style');
+ st.id = 'asc-reactions-pos';
+ st.textContent =
+ '.asc-reactions{position:absolute;left:50%;bottom:14px;transform:translateX(-50%);z-index:7;' +
+ 'display:flex;align-items:center;padding:7px 10px;border-radius:14px;' +
+ 'background:rgba(10,10,14,.62);backdrop-filter:blur(10px);' +
+ 'border:1px solid rgba(255,255,255,.1);box-shadow:0 8px 28px rgba(0,0,0,.4);' +
+ 'transition:opacity .2s ease,transform .2s ease;max-width:calc(100% - 24px);}' +
+ 'body.asc-zen .asc-reactions{opacity:0;pointer-events:none;transform:translateX(-50%) translateY(8px);}';
+ document.head.appendChild(st);
+ }
+ const reactBar = document.createElement('div');
+ reactBar.className = 'asc-reactions';
+ screenStageEl.appendChild(reactBar);
+ reactions = mountAgentReactions({
+ agentId: id,
+ barHost: reactBar,
+ overlayHost: screenStageEl,
+ subscribe: true,
+ getAgent: () => agentRecord || { id, name: agentName },
+ getAnimManager: () => webcamAnimManager,
+ getAudioContext: () => ensureAudioContext(),
+ voiceId: agentVoice,
+ });
+ }
+
const client = createAgentScreenClient(id, {
onOpen({ agentName: n }) {
if (n) { agentNameEl.textContent = n; agentName = n; webcamName.textContent = n; }
@@ -1485,7 +1753,10 @@ async function boot(id) {
recordFrame(frame);
if (frame.data) renderFrame(frame);
handleTourFrame(frame);
- if (frame.activity) { addLogEntry(frame); treasuryCockpit?.observeLog([frame]); }
+ if (frame.activity) {
+ if (!isOwnEcho(frame.activity)) addLogEntry(frame);
+ treasuryCockpit?.observeLog([frame]);
+ }
const forgeHit = parseForgeFrame(frame);
if (forgeHit) loadForgedAvatar(forgeHit);
if (frame.meta?.kind === 'a2a_hire') hireViz?.ingest(frame.meta, { live: true });
@@ -1506,7 +1777,7 @@ async function boot(id) {
onLog(entries) {
// 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); });
+ entries.forEach((e) => { if (!isOwnEcho(e.activity)) addLogEntry(e); ingestTrade(e); });
treasuryCockpit?.observeLog(entries);
const lastForge = [...entries].reverse().find((e) => parseForgeFrame(e));
if (lastForge) loadForgedAvatar(parseForgeFrame(lastForge));
@@ -1698,6 +1969,214 @@ async function boot(id) {
const taskStatus = document.getElementById('asc-task-status');
const taskSend = document.getElementById('asc-task-send');
+ // ── Pose Studio Live: quick-pick chips + free-text pose input ────────────
+ // A chip or a typed phrase resolves through matchPose() (same preset library
+ // as /pose and the get_pose_seed tool) and drives the live avatar via
+ // performPose(). The hint line doubles as transient status.
+ const poseChipsEl = document.getElementById('asc-pose-chips');
+ const poseFormEl = document.getElementById('asc-pose-form');
+ const poseInputEl = document.getElementById('asc-pose-input');
+ const poseHintEl = document.getElementById('asc-pose-hint');
+ const DEFAULT_POSE_HINT = 'Try: wave · bow · warrior';
+ let poseHintTimer = null;
+ function setPoseHint(msg, transient = false) {
+ if (!poseHintEl) return;
+ poseHintEl.textContent = msg;
+ clearTimeout(poseHintTimer);
+ if (transient) poseHintTimer = setTimeout(() => { poseHintEl.textContent = DEFAULT_POSE_HINT; }, 2600);
+ }
+ function runPose(prompt) {
+ const text = String(prompt || '').trim();
+ if (!text) return;
+ if (!performPose) { setPoseHint('Warming up the avatar…', true); return; }
+ const action = matchPose(text);
+ setPoseHint(`${action.icon ? `${action.icon} ` : ''}${action.label}`, true);
+ performPose(action);
+ }
+ if (poseChipsEl) {
+ for (const qp of POSE_QUICK_PICKS) {
+ const b = document.createElement('button');
+ b.type = 'button';
+ b.className = 'asc-pose-chip';
+ b.dataset.prompt = qp.prompt;
+ b.title = `Pose: ${qp.label}`;
+ b.innerHTML = `<span class="asc-pose-chip-ico">${qp.icon}</span>${esc(qp.label)}`;
+ b.addEventListener('click', () => runPose(qp.prompt));
+ poseChipsEl.appendChild(b);
+ }
+ }
+ poseFormEl?.addEventListener('submit', (e) => {
+ e.preventDefault();
+ const v = poseInputEl.value.trim();
+ if (!v) return;
+ runPose(v);
+ poseInputEl.value = '';
+ poseInputEl.blur();
+ });
+
+ // ── Live Q&A concierge ────────────────────────────────────────────────────
+ // The task bar's default action: ask the agent a question and get a live,
+ // spoken, remembered answer. Owners can flip to "Task" to queue a background
+ // job instead (the original behaviour). Answer streams from /api/agent-ask
+ // (persona + session memory + the brain router); voice + lip-sync reuse the
+ // newsroom anchor; the avatar thinks while it streams and gestures while it
+ // speaks.
+ let taskMode = 'ask'; // 'ask' | 'task' (owner only)
+
+ function lockBar(on) {
+ taskInput.disabled = on;
+ taskSend.disabled = on;
+ taskSend.classList.toggle('sending', on);
+ }
+
+ // A live, streaming answer row in the activity log. Shows a typing indicator
+ // until the first token, then fills in word by word.
+ function startAnswerEntry() {
+ if (logEmpty) { logEmpty.remove(); logEmpty = null; }
+ const entry = document.createElement('div');
+ entry.className = 'asc-log-entry type-analysis cat-analysis sev-info asc-qa-answer';
+ entry.innerHTML = `
+ <span class="asc-log-time">${fmtTime(Date.now())}</span>
+ <span class="asc-log-icon" aria-hidden="true">💬</span>
+ <span class="asc-log-type asc-qa-name">${esc(agentName)}</span>
+ <span class="asc-log-text"><span class="asc-typing" aria-label="thinking"><i></i><i></i><i></i></span></span>
+ `;
+ logEl.prepend(entry);
+ lastBeat = null; // never collapse a following beat into this custom row
+ logCount++;
+ while (logCount > MAX_LOG) { logEl.lastElementChild?.remove(); logCount--; }
+ const textEl = entry.querySelector('.asc-log-text');
+ const nameEl = entry.querySelector('.asc-qa-name');
+ return {
+ render(text) {
+ textEl.textContent = text;
+ if (logEl.scrollTop < 24) logEl.scrollTop = 0;
+ },
+ markSpoken() {
+ if (entry.querySelector('.asc-qa-spk')) return;
+ const s = document.createElement('span');
+ s.className = 'asc-qa-spk';
+ s.title = 'Spoken aloud';
+ s.textContent = '🔊';
+ nameEl.after(s);
+ },
+ fail(msg) {
+ entry.classList.add('asc-qa-fail');
+ textEl.textContent = msg;
+ },
+ };
+ }
+
+ async function askQuestion(text) {
+ addLogEntry({ ts: Date.now(), activity: `Asked: ${text}`, type: 'analysis' });
+ rememberEcho(`Asked: ${text}`);
+ const entry = startAnswerEntry();
+ avatarThinking();
+ // The submit is a user gesture — unlock the AudioContext now so the spoken
+ // answer can play even on the first question of the visit.
+ try { ensureAudioContext?.(); } catch { /* no-op */ }
+
+ let answer = '';
+ try {
+ const res = await fetch('/api/agent-ask', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ agentId: id, question: text, sessionId: qaSessionId }),
+ });
+ if (!res.ok || !res.body) {
+ let msg = 'I couldn’t reach my brain just now — try again.';
+ if (res.status === 429) msg = 'I’m getting a lot of questions — give me a moment.';
+ else { try { const j = await res.json(); if (j?.message) msg = j.message; } catch { /* keep default */ } }
+ entry.fail(msg);
+ avatarSettle();
+ return;
+ }
+ const reader = res.body.getReader();
+ const decoder = new TextDecoder();
+ let buf = '';
+ for (;;) {
+ const { done, value } = await reader.read();
+ if (done) break;
+ buf += decoder.decode(value, { stream: true });
+ let idx;
+ while ((idx = buf.indexOf('\n\n')) !== -1) {
+ const ev = buf.slice(0, idx);
+ buf = buf.slice(idx + 2);
+ let evType = 'message';
+ let data = '';
+ for (const line of ev.split('\n')) {
+ if (line.startsWith('event:')) evType = line.slice(6).trim();
+ else if (line.startsWith('data:')) data += line.slice(5).trim();
+ }
+ if (evType === 'message' && data && data !== '[DONE]') {
+ try { const t = JSON.parse(data); if (typeof t === 'string') { answer += t; entry.render(answer); } } catch { /* skip */ }
+ } else if (evType === 'error' && !answer) {
+ let m = 'I hit a snag mid-thought — try again.';
+ try { m = JSON.parse(data).message || m; } catch { /* keep default */ }
+ entry.fail(m);
+ }
+ }
+ }
+ } catch {
+ if (!answer) { entry.fail('Network hiccup — try again.'); avatarSettle(); return; }
+ }
+
+ if (!answer.trim()) { entry.fail('I couldn’t find an answer — try again.'); avatarSettle(); return; }
+ entry.render(answer);
+ rememberEcho(answer);
+ avatarSettle();
+ // Voice is enhancement — a failure leaves the text answer intact. Honours
+ // the anchor's mute (toggle in the task bar / the lower-third / key A).
+ try { const spoke = await anchor?.speak(answer, { voice: agentVoice }); if (spoke) entry.markSpoken(); } catch { /* text stands alone */ }
+ }
+
+ // Ask⇄Task mode toggle (owners only — visitors always ask).
+ const modeBtn = document.getElementById('asc-task-mode');
+ if (modeBtn) {
+ if (!isOwner) {
+ modeBtn.hidden = true;
+ taskInput.placeholder = 'Ask this agent anything…';
+ } else {
+ const paintMode = () => {
+ const task = taskMode === 'task';
+ modeBtn.textContent = task ? 'Task' : 'Ask';
+ modeBtn.classList.toggle('is-task', task);
+ modeBtn.setAttribute('aria-pressed', String(task));
+ modeBtn.title = task
+ ? 'Queuing a background task — click to ask live'
+ : 'Asking live — click to queue a background task';
+ taskInput.placeholder = task ? 'Give your agent a background task…' : 'Ask this agent anything…';
+ };
+ modeBtn.addEventListener('click', () => {
+ taskMode = taskMode === 'task' ? 'ask' : 'task';
+ paintMode();
+ taskInput.focus();
+ });
+ paintMode();
+ }
+ }
+
+ // Voice (mute) toggle — mirrors the newsroom anchor's mute so one control
+ // governs every spoken line on the screen.
+ const voiceBtn = document.getElementById('asc-task-voice');
+ if (voiceBtn) {
+ const paintVoice = () => {
+ const m = !!anchor?.isMuted?.();
+ voiceBtn.textContent = m ? '🔇' : '🔊';
+ voiceBtn.classList.toggle('is-muted', m);
+ voiceBtn.setAttribute('aria-pressed', String(!m));
+ voiceBtn.title = m ? 'Voice off — click to let the agent speak aloud' : 'Voice on — click to mute';
+ };
+ voiceBtn.addEventListener('click', () => {
+ const next = !anchor?.isMuted?.(); // true → mute, false → unmute
+ anchor?.setMuted(next, { speakNow: false });
+ if (!next) { try { ensureAudioContext?.(); } catch { /* no-op */ } }
+ paintVoice();
+ });
+ paintVoice();
+ }
+
taskForm.addEventListener('submit', async (e) => {
e.preventDefault();
const text = taskInput.value.trim();
@@ -1723,6 +2202,22 @@ async function boot(id) {
return;
}
+ // Default action: ask the agent a live question. Owners who flipped the
+ // bar to "Task" mode fall through to the background-task queue below.
+ if (classifyTaskInput({ isOwner, mode: taskMode }) === 'ask') {
+ taskInput.value = '';
+ taskStatus.className = 'asc-task-status';
+ taskStatus.textContent = '';
+ lockBar(true);
+ try {
+ await askQuestion(text);
+ } finally {
+ lockBar(false);
+ taskInput.focus();
+ }
+ return;
+ }
+
taskInput.disabled = true;
taskSend.disabled = true;
taskSend.classList.add('sending');
@@ -1892,7 +2387,7 @@ async function boot(id) {
const msg = String(err && err.message ? err.message : err);
addLogEntry({ ts: Date.now(), activity: `Forge failed: ${msg}`, type: 'analysis' });
hideForgeOverlay();
- if (/busy|rate|429/i.test(msg)) forgeStatus('Forge lane busy — try again shortly', 'err');
+ if (/busy|rate|429|unavailable|temporarily|cold|degraded/i.test(msg)) forgeStatus('Forge lane busy — try again shortly', 'err');
else if (/reject|invalid|concrete|moderat/i.test(msg)) forgeStatus('Prompt rejected — try a concrete object', 'err');
else forgeStatus(`Forge failed: ${msg}`, 'err');
} finally {
@@ -2089,7 +2584,7 @@ async function boot(id) {
const res = await fetch(`/api/pump/launches?network=${encodeURIComponent(network)}&limit=50`, { credentials: 'include' });
if (!res.ok) return false;
const j = await res.json().catch(() => ({}));
- const list = Array.isArray(j?.launches) ? j.launches : Array.isArray(j) ? j : [];
+ const list = j?.data?.launches || j?.launches || (Array.isArray(j) ? j : []);
return list.some((l) => l?.mint === mint);
} catch {
return false;
@@ -2118,6 +2613,117 @@ async function boot(id) {
logCount++;
}
+ // ── Vanity Grinder ────────────────────────────────────────────────────────
+ // Trigger a real, server-side ed25519 keyspace grind. The grind streams its
+ // keyspace frames to this screen (and every viewer's) through the same SSE
+ // pipe via /api/agent-vanity-grind; we hold the request open and render the
+ // owner-only reveal (the secret + the launch hand-off) when it resolves.
+ let grindInFlight = false;
+
+ async function runVanityGrind(params) {
+ if (grindInFlight) { setLaunchStatus('err', 'A grind is already running for this agent.'); return; }
+ grindInFlight = true;
+ taskInput.disabled = true;
+ taskSend.disabled = true;
+ taskSend.classList.add('sending');
+
+ const pat = `${esc(params.prefix)}${params.suffix ? '…' + esc(params.suffix) : '…'}`;
+ setLaunchStatus('', `Grinding a wallet · ${pat} — watch the keyspace burn`);
+ addLogEntry({ ts: Date.now(), activity: `Vanity grind started · target ${params.prefix}${params.suffix ? '…' + params.suffix : '…'}`, type: 'analysis' });
+
+ try {
+ const res = await fetch('/api/agent-vanity-grind', {
+ method: 'POST',
+ credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({
+ agentId: id,
+ prefix: params.prefix,
+ suffix: params.suffix || undefined,
+ ignoreCase: params.ignoreCase,
+ }),
+ });
+ const j = await res.json().catch(() => ({}));
+
+ if (res.ok && j?.address) {
+ setLaunchStatus('ok', `Matched ${esc(truncMid(j.address, 6, 4))} in ${Number(j.iterations).toLocaleString()} attempts`);
+ appendGrindResult(j);
+ setTimeout(() => { taskStatus.textContent = ''; taskStatus.className = 'asc-task-status'; }, 9000);
+ } else if (res.status === 401) {
+ setLaunchStatus('err', 'Sign in as the agent owner to grind. <a href="/login" style="color:#d4d4d8">Sign in →</a>');
+ } else if (res.status === 504 || j?.error === 'vanity_capped') {
+ setLaunchStatus('err', esc(j.message || j.error_description || 'No match within the attempt cap — try a shorter prefix.'));
+ addLogEntry({ ts: Date.now(), activity: j.message || 'Grind capped — try a shorter prefix.', type: 'analysis' });
+ } else {
+ setLaunchStatus('err', esc(j.message || j.error_description || 'Grind failed — try again.'));
+ }
+ } catch {
+ setLaunchStatus('err', 'Network error during grind — check your connection.');
+ } finally {
+ grindInFlight = false;
+ taskInput.disabled = false;
+ taskSend.disabled = false;
+ taskSend.classList.remove('sending');
+ taskInput.focus();
+ }
+ }
+
+ // Render the owner-only reveal: the matched PUBLIC address, the secret (shown
+ // once, copy-to-clipboard, never sent anywhere), and the launch hand-off CTA.
+ // This card only ever exists in the triggering owner's own session — the
+ // secret is never part of the live screen stream.
+ function appendGrindResult(result) {
+ if (logEmpty) { logEmpty.remove(); logEmpty = null; }
+ const card = document.createElement('div');
+ card.className = 'asc-log-entry type-analysis asc-grind-result';
+ const addr = String(result.address || '');
+ const launchable = !!result.launchable;
+ const secs = (Math.round(result.durationMs || 0) / 1000).toFixed(1);
+ card.innerHTML = `
+ <div class="asc-launch-result-head">🔑 Vanity match · <span class="asc-launch-mint">${esc(truncMid(addr, 8, 6))}</span></div>
+ <div class="asc-grind-meta">${Number(result.iterations || 0).toLocaleString()} attempts · expected ~${Number(result.estimatedIterations || 0).toLocaleString()} · ${secs}s</div>
+ <div class="asc-grind-secret">
+ <label>Private key (base58) — shown once, store it now</label>
+ <div class="asc-grind-secret-row">
+ <input type="password" readonly value="${esc(result.privateKey64 || '')}" class="asc-grind-secret-input" aria-label="private key" />
+ <button type="button" class="asc-grind-reveal" title="Show or hide the key">show</button>
+ <button type="button" class="asc-grind-copy" title="Copy the key">copy</button>
+ </div>
+ </div>
+ <div class="asc-launch-result-links">
+ ${launchable
+ ? '<button type="button" class="asc-launch-cta asc-grind-launch">Use this address to launch →</button>'
+ : '<span class="asc-grind-note">Branded wallet ready. A three.ws launch needs a mint carrying the "3ws" mark — grind <code>3ws</code> for a launchable one.</span>'}
+ <a href="https://solscan.io/account/${encodeURIComponent(addr)}" target="_blank" rel="noopener">explorer ↗</a>
+ </div>
+ `;
+
+ const secretInput = card.querySelector('.asc-grind-secret-input');
+ card.querySelector('.asc-grind-reveal').addEventListener('click', (e) => {
+ const show = secretInput.type === 'password';
+ secretInput.type = show ? 'text' : 'password';
+ e.currentTarget.textContent = show ? 'hide' : 'show';
+ });
+ card.querySelector('.asc-grind-copy').addEventListener('click', async (e) => {
+ try {
+ await navigator.clipboard.writeText(result.privateKey64 || '');
+ e.currentTarget.textContent = 'copied';
+ setTimeout(() => { e.currentTarget.textContent = 'copy'; }, 1500);
+ } catch { e.currentTarget.textContent = 'copy failed'; }
+ });
+ const launchBtn = card.querySelector('.asc-grind-launch');
+ if (launchBtn) {
+ launchBtn.addEventListener('click', () => {
+ taskInput.value = `launch a coin mint ${addr} `;
+ taskInput.focus();
+ toast('Mint address staged — add name, ticker, and metadata URI to launch');
+ });
+ }
+
+ logEl.prepend(card);
+ logCount++;
+ }
+
// ── live stage show (Moonshot 08) ────────────────────────────────────────
// The avatar-cam host performs an always-live show: opener → banter → answer
// audience questions → shout out fresh $THREE tippers → run a game round, on
@@ -2165,6 +2771,7 @@ async function boot(id) {
mirror: document.getElementById('asc-panel-mirror'),
stage: document.getElementById('asc-panel-stage'),
hud: document.getElementById('asc-panel-hud'),
+ diary: document.getElementById('asc-panel-diary'),
hire: document.getElementById('asc-panel-hire'),
heatmap: document.getElementById('asc-panel-heatmap'),
};
@@ -2194,6 +2801,8 @@ async function boot(id) {
else if (name === 'heatmap') { x = M; y = sr.height - ph - M; } // heatmap → bottom-left
else if (name === 'stage') { x = M; y = sr.height - ph - M; } // stage → bottom-left
else if (name === 'hud') { x = M; y = sr.height - ph - M; } // HUD → bottom-left scoreboard
+ else if (name === 'hire') { x = sr.width - pw - M; y = sr.height - ph - M - 8; } // hire → bottom-right above cam
+ else if (name === 'diary') { x = Math.round((sr.width - pw) / 2); y = M + 40; } // diary → centre, beside the log
else { x = sr.width - pw - M; y = sr.height - ph - M; } // cam → bottom-right
}
x = clamp(x, 0, Math.max(0, sr.width - pw));
@@ -2313,6 +2922,18 @@ async function boot(id) {
onToast: toast,
});
+ // ── Memory Diary: the agent reflects on its day from real memory ─────
+ diaryPanel = createDiaryPanel({
+ agentId: id,
+ body: document.getElementById('asc-diary-body'),
+ getAvatar: () => webcamAvatar,
+ pauseOtherNarration: () => { try { anchor?.setMuted?.(true, { speakNow: false }); } catch { /* */ } },
+ });
+ {
+ const _prevDiarySampler = lipsyncSampler;
+ lipsyncSampler = () => { _prevDiarySampler?.(); diaryPanel?.tick(); };
+ }
+
// ── Portfolio / PnL HUD: the live scoreboard ─────────────────────────────
// Values this agent's wallet live (net worth, 24h delta, sparkline, ranked
// holdings with $THREE featured). Polls the public balances endpoint; the
@@ -2701,6 +3322,8 @@ async function boot(id) {
else if (k === 'g') { togglePanel('stage'); e.preventDefault(); }
else if (k === 't') { togglePanel('treasury'); e.preventDefault(); }
else if (k === 'm') { togglePanel('mirror'); e.preventDefault(); }
+ else if (k === 'd') { togglePanel('diary'); e.preventDefault(); }
+ else if (k === 'r') { togglePanel('hire'); e.preventDefault(); }
else if (k === 'b') { togglePanel('hud'); e.preventDefault(); }
else if (k === 's') { screenshot(); e.preventDefault(); }
else if (k === 'p') { togglePip(); e.preventDefault(); }
@@ -2736,6 +3359,7 @@ async function boot(id) {
mirrorPanel?.destroy();
pnlHud?.destroy();
anchor?.destroy();
+ diaryPanel?.destroy();
if (pnlAnimRaf) cancelAnimationFrame(pnlAnimRaf);
stageShow.dispose();
sharedAudioCtx?.close?.().catch(() => {});
@@ -2766,6 +3390,7 @@ function buildHelpOverlay() {
<div class="asc-help-row"><span>Toggle sentiment heatmap</span><kbd>H</kbd></div>
<div class="asc-help-row"><span>Toggle live stage show</span><kbd>G</kbd></div>
<div class="asc-help-row"><span>Toggle treasury</span><kbd>T</kbd></div>
+ <div class="asc-help-row"><span>Toggle memory diary</span><kbd>D</kbd></div>
<div class="asc-help-row"><span>Toggle portfolio HUD</span><kbd>B</kbd></div>
<div class="asc-help-row"><span>Capture screenshot</span><kbd>S</kbd></div>
<div class="asc-help-row"><span>Picture-in-picture</span><kbd>P</kbd></div>
diff --git a/src/agent-team.js b/src/agent-team.js
new file mode 100644
index 000000000..72fb76353
--- /dev/null
+++ b/src/agent-team.js
@@ -0,0 +1,623 @@
+// Team Task — multi-agent collaboration surface.
+//
+// One goal, one lead agent. The lead decomposes the goal and either delegates
+// sub-tasks (free LLM turns) or HIRES teammate agents over real x402 — every
+// handoff stamped with a real on-chain receipt. This module renders the live
+// dependency graph: nodes pulse as they run, edges flow on handoff, cost badges
+// and explorer chips appear on real paid hires.
+//
+// It is self-contained and context-aware, so it can ride two pages without
+// touching their existing scripts:
+// • /agents-live — injects a "Team Task" launcher into the hero; the user
+// picks one of their agents as lead and gives it a goal.
+// • /agent-screen — adds a "Team" toggle to the task bar; submitting a goal
+// runs the current agent as lead and opens the graph inline.
+//
+// Backend: POST /api/agent-collab kicks off the run and returns the final tree;
+// live transitions stream back over /api/agent-screen-stream (the lead's screen),
+// where each frame carries the current graph snapshot in `frame.meta.collab`.
+
+const HARD_MAX_USD = 5;
+const DEFAULT_MAX_USD = 1;
+
+function esc(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({
+ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;',
+ }[c]));
+}
+
+function truncate(s, n) {
+ const str = String(s ?? '');
+ return str.length > n ? `${str.slice(0, n - 1)}…` : str;
+}
+
+// ── styles (injected once) ────────────────────────────────────────────────────
+
+let _stylesInjected = false;
+function ensureStyles() {
+ if (_stylesInjected) return;
+ _stylesInjected = true;
+ const css = `
+.tt-launch{display:inline-flex;align-items:center;gap:8px;margin-top:18px;padding:10px 18px;border-radius:999px;
+ border:1px solid rgba(120,180,255,.35);background:linear-gradient(180deg,rgba(80,140,255,.18),rgba(80,140,255,.07));
+ color:#dCE9ff;font:600 13px/1 Inter,system-ui,sans-serif;cursor:pointer;transition:transform .15s,border-color .2s,box-shadow .2s;}
+.tt-launch:hover{transform:translateY(-1px);border-color:rgba(120,180,255,.7);box-shadow:0 6px 22px rgba(60,120,255,.22);}
+.tt-launch:active{transform:translateY(0);}
+.tt-launch:focus-visible{outline:2px solid #6aa8ff;outline-offset:2px;}
+.tt-launch-ico{font-size:15px;line-height:1;}
+
+.tt-overlay{position:fixed;inset:0;z-index:2000;display:flex;align-items:center;justify-content:center;
+ background:rgba(4,6,12,.72);backdrop-filter:blur(8px);opacity:0;transition:opacity .2s;padding:24px;}
+.tt-overlay.tt-open{opacity:1;}
+.tt-panel{position:relative;width:min(1040px,96vw);max-height:92vh;overflow:auto;border-radius:18px;
+ border:1px solid rgba(255,255,255,.1);background:linear-gradient(180deg,#0d1018,#0a0c12);
+ box-shadow:0 30px 90px rgba(0,0,0,.6);transform:translateY(8px) scale(.99);transition:transform .2s;}
+.tt-overlay.tt-open .tt-panel{transform:none;}
+.tt-head{display:flex;align-items:flex-start;justify-content:space-between;gap:16px;padding:20px 22px 14px;
+ border-bottom:1px solid rgba(255,255,255,.07);position:sticky;top:0;background:rgba(13,16,24,.92);backdrop-filter:blur(6px);z-index:2;}
+.tt-title{font:700 16px/1.2 Inter,system-ui,sans-serif;color:#f1f4fb;margin:0;}
+.tt-sub{font:400 12px/1.4 Inter,system-ui,sans-serif;color:#8a93a6;margin-top:4px;}
+.tt-close{appearance:none;border:1px solid rgba(255,255,255,.12);background:rgba(255,255,255,.04);color:#cdd4e2;
+ width:30px;height:30px;border-radius:8px;cursor:pointer;font-size:15px;line-height:1;flex:none;transition:background .15s,border-color .15s;}
+.tt-close:hover{background:rgba(255,255,255,.1);border-color:rgba(255,255,255,.25);}
+.tt-close:focus-visible{outline:2px solid #6aa8ff;outline-offset:2px;}
+
+.tt-body{padding:18px 22px 24px;}
+.tt-form{display:grid;gap:12px;}
+.tt-row{display:flex;gap:12px;flex-wrap:wrap;}
+.tt-field{display:flex;flex-direction:column;gap:6px;flex:1;min-width:160px;}
+.tt-label{font:600 11px/1 Inter,system-ui,sans-serif;color:#8a93a6;text-transform:uppercase;letter-spacing:.04em;}
+.tt-input,.tt-select{width:100%;padding:11px 12px;border-radius:10px;border:1px solid rgba(255,255,255,.12);
+ background:rgba(255,255,255,.03);color:#eef2fb;font:500 14px/1.3 Inter,system-ui,sans-serif;}
+.tt-input:focus,.tt-select:focus{outline:none;border-color:rgba(120,180,255,.6);background:rgba(120,180,255,.06);}
+textarea.tt-input{resize:vertical;min-height:64px;}
+.tt-budget{max-width:130px;}
+.tt-go{align-self:flex-end;padding:11px 20px;border-radius:10px;border:1px solid rgba(120,180,255,.4);
+ background:linear-gradient(180deg,#3a78ff,#2b5fe0);color:#fff;font:700 14px/1 Inter,system-ui,sans-serif;cursor:pointer;
+ transition:transform .15s,box-shadow .2s,opacity .2s;}
+.tt-go:hover{transform:translateY(-1px);box-shadow:0 8px 24px rgba(50,110,255,.35);}
+.tt-go:disabled{opacity:.5;cursor:not-allowed;transform:none;box-shadow:none;}
+.tt-hint{font:400 11px/1.4 Inter,system-ui,sans-serif;color:#6f788c;}
+.tt-examples{display:flex;gap:8px;flex-wrap:wrap;margin-top:2px;}
+.tt-chip{font:500 11px/1 Inter,system-ui,sans-serif;color:#aeb8cc;border:1px solid rgba(255,255,255,.1);
+ background:rgba(255,255,255,.03);border-radius:999px;padding:6px 10px;cursor:pointer;transition:background .15s,border-color .15s;}
+.tt-chip:hover{background:rgba(120,180,255,.1);border-color:rgba(120,180,255,.4);color:#dCE9ff;}
+
+.tt-status{margin:14px 0 6px;font:500 12px/1.4 Inter,system-ui,sans-serif;color:#9aa3b6;display:flex;align-items:center;gap:8px;min-height:18px;}
+.tt-status.err{color:#ff8d8d;}
+.tt-status.ok{color:#7fe0a3;}
+.tt-spin{width:12px;height:12px;border-radius:50%;border:2px solid rgba(120,180,255,.3);border-top-color:#6aa8ff;animation:tt-spin .7s linear infinite;}
+@keyframes tt-spin{to{transform:rotate(360deg)}}
+
+.tt-stage{position:relative;margin-top:8px;min-height:260px;border-radius:14px;border:1px solid rgba(255,255,255,.06);
+ background:radial-gradient(120% 100% at 50% 0%,rgba(40,70,140,.12),rgba(10,12,18,0) 70%),#090b11;overflow:hidden;padding:18px;}
+.tt-svg{position:absolute;inset:0;width:100%;height:100%;pointer-events:none;}
+.tt-edge{fill:none;stroke:rgba(120,170,255,.28);stroke-width:2;}
+.tt-edge.flow{stroke:rgba(130,190,255,.85);stroke-dasharray:6 8;animation:tt-flow .8s linear infinite;}
+@keyframes tt-flow{to{stroke-dashoffset:-28}}
+.tt-nodes{position:relative;display:flex;flex-direction:column;gap:26px;align-items:center;}
+.tt-lead-row{display:flex;justify-content:center;}
+.tt-child-row{display:flex;gap:14px;flex-wrap:wrap;justify-content:center;}
+
+.tt-node{position:relative;width:190px;border-radius:13px;border:1px solid rgba(255,255,255,.1);
+ background:linear-gradient(180deg,rgba(22,26,36,.96),rgba(14,17,24,.96));padding:12px 12px 11px;cursor:default;
+ transition:transform .18s,border-color .2s,box-shadow .25s;text-decoration:none;color:inherit;display:block;}
+a.tt-node{cursor:pointer;}
+a.tt-node:hover{transform:translateY(-2px);border-color:rgba(120,180,255,.6);box-shadow:0 10px 28px rgba(40,90,200,.28);}
+a.tt-node:focus-visible{outline:2px solid #6aa8ff;outline-offset:2px;}
+.tt-node.lead{width:230px;border-color:rgba(120,180,255,.4);background:linear-gradient(180deg,rgba(30,44,78,.95),rgba(16,20,30,.96));}
+.tt-node-top{display:flex;align-items:center;gap:8px;margin-bottom:7px;}
+.tt-ring{width:11px;height:11px;border-radius:50%;flex:none;position:relative;background:#3a4252;}
+.tt-ring.queued{background:#4a5266;}
+.tt-ring.running{background:#5aa0ff;box-shadow:0 0 0 0 rgba(90,160,255,.6);animation:tt-pulse 1.3s infinite;}
+.tt-ring.planning{background:#9a7bff;box-shadow:0 0 0 0 rgba(154,123,255,.6);animation:tt-pulse 1.3s infinite;}
+.tt-ring.done{background:#46d188;}
+.tt-ring.failed{background:#ff6b6b;}
+@keyframes tt-pulse{0%{box-shadow:0 0 0 0 rgba(90,160,255,.55)}70%{box-shadow:0 0 0 8px rgba(90,160,255,0)}100%{box-shadow:0 0 0 0 rgba(90,160,255,0)}}
+.tt-kind{font:700 9px/1 Inter,system-ui,sans-serif;letter-spacing:.06em;text-transform:uppercase;color:#7f8aa0;
+ border:1px solid rgba(255,255,255,.1);border-radius:5px;padding:3px 5px;}
+.tt-kind.hire{color:#ffd27f;border-color:rgba(255,200,110,.35);}
+.tt-kind.lead{color:#9fc4ff;border-color:rgba(140,180,255,.4);}
+.tt-node-title{font:600 12.5px/1.35 Inter,system-ui,sans-serif;color:#eef2fb;}
+.tt-node-name{font:500 11px/1.3 Inter,system-ui,sans-serif;color:#8a93a6;margin-top:3px;}
+.tt-node-foot{display:flex;align-items:center;gap:6px;flex-wrap:wrap;margin-top:9px;min-height:18px;}
+.tt-cost{font:700 10px/1 Inter,system-ui,sans-serif;color:#0a0c12;background:#ffd27f;border-radius:5px;padding:3px 6px;}
+.tt-receipt{display:inline-flex;align-items:center;gap:4px;font:600 10px/1 Inter,system-ui,sans-serif;color:#9fe0b8;
+ border:1px solid rgba(110,220,160,.35);border-radius:5px;padding:3px 6px;text-decoration:none;}
+.tt-receipt:hover{background:rgba(110,220,160,.12);}
+.tt-err{font:500 10.5px/1.3 Inter,system-ui,sans-serif;color:#ff9b9b;}
+.tt-node-result{font:400 11px/1.4 Inter,system-ui,sans-serif;color:#aab3c6;margin-top:8px;
+ max-height:0;overflow:hidden;transition:max-height .25s;}
+.tt-node:hover .tt-node-result,.tt-node.lead .tt-node-result{max-height:120px;}
+
+.tt-meter{display:flex;align-items:center;gap:8px;margin-top:14px;font:500 11px/1 Inter,system-ui,sans-serif;color:#8a93a6;}
+.tt-meter-bar{flex:1;height:6px;border-radius:3px;background:rgba(255,255,255,.06);overflow:hidden;}
+.tt-meter-fill{height:100%;background:linear-gradient(90deg,#ffd27f,#ff9f5a);width:0;transition:width .3s;}
+
+.tt-empty,.tt-error{text-align:center;padding:40px 20px;color:#8a93a6;font:500 13px/1.5 Inter,system-ui,sans-serif;}
+.tt-error{color:#ff9b9b;}
+.tt-empty a{color:#9fc4ff;}
+
+/* agent-screen task-bar team toggle */
+.tt-toggle{display:inline-flex;align-items:center;gap:6px;margin-left:8px;padding:6px 10px;border-radius:999px;
+ border:1px solid rgba(255,255,255,.14);background:rgba(255,255,255,.03);color:#aeb8cc;cursor:pointer;
+ font:600 11px/1 Inter,system-ui,sans-serif;transition:background .15s,border-color .15s,color .15s;white-space:nowrap;}
+.tt-toggle[aria-pressed="true"]{background:linear-gradient(180deg,rgba(80,140,255,.22),rgba(80,140,255,.08));
+ border-color:rgba(120,180,255,.6);color:#dCE9ff;}
+.tt-toggle:focus-visible{outline:2px solid #6aa8ff;outline-offset:2px;}
+.tt-toggle-dot{width:7px;height:7px;border-radius:50%;background:#5a6273;}
+.tt-toggle[aria-pressed="true"] .tt-toggle-dot{background:#6aa8ff;box-shadow:0 0 8px rgba(106,168,255,.8);}
+`;
+ const el = document.createElement('style');
+ el.id = 'tt-styles';
+ el.textContent = css;
+ document.head.appendChild(el);
+}
+
+// ── graph rendering ───────────────────────────────────────────────────────────
+
+// Render the task tree into `stage`. Reuses node elements across snapshots (keyed
+// by id) so status changes animate in place rather than flashing the whole graph.
+function renderGraph(stage, tree, { full = false } = {}) {
+ if (!tree || !Array.isArray(tree.nodes)) return;
+ let svg = stage.querySelector('.tt-svg');
+ let nodesWrap = stage.querySelector('.tt-nodes');
+ if (!nodesWrap) {
+ stage.innerHTML = `
+<svg class="tt-svg" preserveAspectRatio="none"></svg>
+<div class="tt-nodes">
+ <div class="tt-lead-row"></div>
+ <div class="tt-child-row"></div>
+</div>
+<div class="tt-meter" hidden>
+ <span>Spend</span><div class="tt-meter-bar"><div class="tt-meter-fill"></div></div>
+ <span class="tt-meter-val"></span>
+</div>`;
+ svg = stage.querySelector('.tt-svg');
+ nodesWrap = stage.querySelector('.tt-nodes');
+ }
+ const leadRow = nodesWrap.querySelector('.tt-lead-row');
+ const childRow = nodesWrap.querySelector('.tt-child-row');
+
+ const lead = tree.nodes.find((n) => n.id === 'lead') || tree.nodes[0];
+ const children = tree.nodes.filter((n) => n.id !== 'lead');
+
+ upsertNode(leadRow, lead, { lead: true, full });
+ const seen = new Set(['lead']);
+ children.forEach((c) => { upsertNode(childRow, c, { full }); seen.add(c.id); });
+ // Drop any node elements no longer in the tree.
+ childRow.querySelectorAll('[data-node-id]').forEach((el) => {
+ if (!seen.has(el.dataset.nodeId)) el.remove();
+ });
+
+ drawEdges(stage, svg, tree);
+ updateMeter(stage, tree);
+}
+
+function nodeHref(node) {
+ return node.agentId ? `/agent-screen?agentId=${encodeURIComponent(node.agentId)}` : null;
+}
+
+function upsertNode(row, node, { lead = false, full = false } = {}) {
+ let el = row.querySelector(`[data-node-id="${CSS.escape(node.id)}"]`);
+ const href = nodeHref(node);
+ const tag = href ? 'a' : 'div';
+ if (!el || el.tagName.toLowerCase() !== tag) {
+ if (el) el.remove();
+ el = document.createElement(tag);
+ el.dataset.nodeId = node.id;
+ el.className = `tt-node${lead ? ' lead' : ''}`;
+ row.appendChild(el);
+ }
+ if (href) {
+ el.href = href;
+ el.target = '_blank';
+ el.rel = 'noopener';
+ el.title = 'Open this agent’s live screen';
+ }
+ const kind = lead ? 'lead' : node.kind;
+ const result = full && node.result ? `<div class="tt-node-result">${esc(truncate(node.result, 280))}</div>` : '';
+ const foot = nodeFoot(node);
+ el.innerHTML = `
+<div class="tt-node-top">
+ <span class="tt-ring ${esc(node.status)}"></span>
+ <span class="tt-kind ${esc(kind)}">${esc(kind)}</span>
+</div>
+<div class="tt-node-title">${esc(truncate(node.title, lead ? 110 : 72))}</div>
+${node.name ? `<div class="tt-node-name">${esc(truncate(node.name, 36))}</div>` : ''}
+<div class="tt-node-foot">${foot}</div>
+${result}`;
+}
+
+function nodeFoot(node) {
+ if (node.status === 'failed') {
+ return `<span class="tt-err">⚠ ${esc(truncate(node.error || 'failed', 48))}</span>`;
+ }
+ const bits = [];
+ if (node.costUsd != null && Number(node.costUsd) > 0) {
+ bits.push(`<span class="tt-cost">$${Number(node.costUsd).toFixed(2)}</span>`);
+ }
+ const url = node.url || node.explorerUrl;
+ const sig = node.sig || node.signature;
+ if (url && sig) {
+ bits.push(`<a class="tt-receipt" href="${esc(url)}" target="_blank" rel="noopener" onclick="event.stopPropagation()">⛓ ${esc(truncate(sig, 6))}</a>`);
+ }
+ if (!bits.length && node.status === 'running') return `<span class="tt-err" style="color:#7f8aa0">working…</span>`;
+ return bits.join('');
+}
+
+// Draw lead→child edges as curves; the edge "flows" while its child is running.
+function drawEdges(stage, svg, tree) {
+ const sr = stage.getBoundingClientRect();
+ if (!sr.width) return;
+ svg.setAttribute('viewBox', `0 0 ${sr.width} ${sr.height}`);
+ const center = (el) => {
+ const r = el.getBoundingClientRect();
+ return { x: r.left - sr.left + r.width / 2, y: r.top - sr.top, yb: r.bottom - sr.top, h: r.height };
+ };
+ const leadEl = stage.querySelector('.tt-node.lead');
+ if (!leadEl) { svg.innerHTML = ''; return; }
+ const lc = center(leadEl);
+ const paths = [];
+ (tree.edges || []).forEach((e) => {
+ const childEl = stage.querySelector(`[data-node-id="${CSS.escape(e.to)}"]`);
+ if (!childEl) return;
+ const cc = center(childEl);
+ const x1 = lc.x, y1 = lc.yb, x2 = cc.x, y2 = cc.y;
+ const my = (y1 + y2) / 2;
+ const node = tree.nodes.find((n) => n.id === e.to);
+ const flow = node && (node.status === 'running');
+ paths.push(`<path class="tt-edge${flow ? ' flow' : ''}" d="M${x1.toFixed(1)},${y1.toFixed(1)} C${x1.toFixed(1)},${my.toFixed(1)} ${x2.toFixed(1)},${my.toFixed(1)} ${x2.toFixed(1)},${y2.toFixed(1)}"/>`);
+ });
+ svg.innerHTML = paths.join('');
+}
+
+function updateMeter(stage, tree) {
+ const meter = stage.querySelector('.tt-meter');
+ if (!meter) return;
+ const cap = Number(tree.maxUsd) || 0;
+ const spent = Number(tree.spentUsd ?? tree.budgetSpentUsd) || 0;
+ if (cap <= 0 || (spent <= 0 && tree.status !== 'done')) { meter.hidden = true; return; }
+ meter.hidden = false;
+ const pct = cap > 0 ? Math.min(100, (spent / cap) * 100) : 0;
+ meter.querySelector('.tt-meter-fill').style.width = `${pct}%`;
+ meter.querySelector('.tt-meter-val').textContent = `$${spent.toFixed(2)} / $${cap.toFixed(2)}`;
+}
+
+// ── run a team task ────────────────────────────────────────────────────────────
+
+// Drives one collaboration: kicks the backend, subscribes to the lead's live
+// stream for graph snapshots, and resolves with the authoritative final tree.
+function runTeamTask({ leadAgentId, goal, maxUsd, stage, statusEl }) {
+ let settled = false;
+ let es = null;
+
+ const setStatus = (text, cls = '') => {
+ if (!statusEl) return;
+ statusEl.className = `tt-status ${cls}`.trim();
+ statusEl.innerHTML = cls === '' && text
+ ? `<span class="tt-spin"></span>${esc(text)}`
+ : esc(text);
+ };
+
+ // Seed an immediate planning graph so the stage is never blank.
+ renderGraph(stage, {
+ nodes: [{ id: 'lead', kind: 'lead', title: goal, status: 'planning', agentId: leadAgentId }],
+ edges: [], maxUsd, spentUsd: 0, status: 'planning',
+ });
+ setStatus('Lead agent is planning the work…');
+
+ // Live transitions over the lead's screen stream (frame.meta.collab snapshots).
+ try {
+ es = new EventSource(`/api/agent-screen-stream?agentId=${encodeURIComponent(leadAgentId)}`);
+ es.addEventListener('frame', (e) => {
+ if (settled) return;
+ try {
+ const frame = JSON.parse(e.data);
+ const snap = frame?.meta?.collab;
+ if (snap && snap.kind === 'collab') {
+ renderGraph(stage, snap);
+ setStatus(statusForTree(snap));
+ }
+ } catch { /* malformed frame */ }
+ });
+ es.onerror = () => { /* EventSource auto-retries; the POST is the source of truth */ };
+ } catch { /* SSE unsupported — the final POST result still renders */ }
+
+ const done = (tree) => {
+ settled = true;
+ if (es) { try { es.close(); } catch { /* */ } }
+ renderGraph(stage, compactFromFull(tree), { full: true });
+ const failed = tree.status === 'completed_with_errors';
+ setStatus(failed ? 'Team task complete — some sub-tasks could not finish' : 'Team task complete', failed ? 'err' : 'ok');
+ };
+
+ const fail = (msg) => {
+ settled = true;
+ if (es) { try { es.close(); } catch { /* */ } }
+ setStatus(msg || 'The team task could not be started', 'err');
+ };
+
+ const promise = fetchCsrfToken().then((token) => fetch('/api/agent-collab', {
+ method: 'POST',
+ credentials: 'include',
+ headers: token
+ ? { 'content-type': 'application/json', 'x-csrf-token': token }
+ : { 'content-type': 'application/json' },
+ body: JSON.stringify({ leadAgentId, goal, maxUsd }),
+ })).then(async (res) => {
+ const data = await res.json().catch(() => ({}));
+ if (res.ok && data.tree) { done(data.tree); return data; }
+ if (res.status === 401) { fail('Sign in to run a team task'); return null; }
+ fail(data.error_description || data.message || 'The team task failed — try again'); return null;
+ }).catch(() => { fail('Network error — check your connection'); return null; });
+
+ return { promise, cancel: () => { if (es) try { es.close(); } catch { /* */ } } };
+}
+
+// The final POST returns the rich tree (full results, full signatures); reshape
+// it to the same field names renderGraph reads from a stream snapshot.
+function compactFromFull(tree) {
+ return {
+ kind: 'collab',
+ taskId: tree.taskId,
+ status: tree.status,
+ maxUsd: tree.maxUsd,
+ spentUsd: tree.budgetSpentUsd,
+ edges: tree.edges,
+ nodes: tree.nodes.map((n) => ({
+ id: n.id, agentId: n.agentId, name: n.name, kind: n.kind, title: n.title,
+ status: n.status, costUsd: n.costUsd, sig: n.signature, url: n.explorerUrl,
+ result: n.result, error: n.error,
+ })),
+ };
+}
+
+function statusForTree(tree) {
+ if (tree.status === 'planning') return 'Lead agent is planning the work…';
+ const running = tree.nodes.find((n) => n.status === 'running');
+ if (running) return running.kind === 'hire' ? `Hiring a teammate — ${truncate(running.title, 40)}` : `Working — ${truncate(running.title, 44)}`;
+ const queued = tree.nodes.some((n) => n.status === 'queued');
+ if (queued) return 'Coordinating the team…';
+ return 'Wrapping up…';
+}
+
+// Fetch a one-time CSRF token for the session write, mirroring the rest of the
+// app (GET /api/csrf-token → echo in the x-csrf-token header). Bearer sessions are
+// CSRF-exempt server-side, so a null token still works for them.
+async function fetchCsrfToken() {
+ try {
+ const res = await fetch('/api/csrf-token', { credentials: 'include' });
+ if (!res.ok) return null;
+ const j = await res.json();
+ return j.data?.token || j.token || null;
+ } catch {
+ return null;
+ }
+}
+
+// ── overlay ────────────────────────────────────────────────────────────────────
+
+const EXAMPLE_GOALS = [
+ 'Research the $THREE token and draft a one-paragraph launch summary',
+ 'Scan sentiment for a trending Solana coin and recommend a position',
+ 'Profile three competing AI-agent platforms and list their gaps',
+];
+
+function buildOverlay() {
+ ensureStyles();
+ const overlay = document.createElement('div');
+ overlay.className = 'tt-overlay';
+ overlay.setAttribute('role', 'dialog');
+ overlay.setAttribute('aria-modal', 'true');
+ overlay.setAttribute('aria-label', 'Team Task');
+ overlay.innerHTML = `
+<div class="tt-panel">
+ <div class="tt-head">
+ <div>
+ <h2 class="tt-title">Team Task</h2>
+ <div class="tt-sub">One goal. A lead agent splits the work, hires teammates over x402, and proves every handoff on-chain.</div>
+ </div>
+ <button class="tt-close" type="button" aria-label="Close">✕</button>
+ </div>
+ <div class="tt-body">
+ <form class="tt-form" data-tt-form>
+ <div class="tt-field" data-lead-field hidden>
+ <label class="tt-label" for="tt-lead">Lead agent</label>
+ <select class="tt-select" id="tt-lead" data-lead></select>
+ </div>
+ <div class="tt-field">
+ <label class="tt-label" for="tt-goal">Goal</label>
+ <textarea class="tt-input" id="tt-goal" data-goal placeholder="Give the lead agent a goal…" maxlength="2000"></textarea>
+ <div class="tt-examples" data-examples></div>
+ </div>
+ <div class="tt-row">
+ <div class="tt-field tt-budget">
+ <label class="tt-label" for="tt-budget">Budget (USD)</label>
+ <input class="tt-input" id="tt-budget" data-budget type="number" min="0.1" max="${HARD_MAX_USD}" step="0.1" value="${DEFAULT_MAX_USD}">
+ </div>
+ <button class="tt-go" type="submit" data-go>Launch team →</button>
+ </div>
+ <div class="tt-hint">Spend is hard-capped at $${HARD_MAX_USD.toFixed(2)} and split across paid hires; each hire is gated by the agent's own spend policy.</div>
+ </form>
+ <div class="tt-status" data-status></div>
+ <div class="tt-stage" data-stage hidden></div>
+ </div>
+</div>`;
+ return overlay;
+}
+
+function openOverlay({ leads = [], presetGoal = '' } = {}) {
+ const overlay = buildOverlay();
+ document.body.appendChild(overlay);
+ document.body.style.overflow = 'hidden';
+ requestAnimationFrame(() => overlay.classList.add('tt-open'));
+
+ const close = () => {
+ overlay.classList.remove('tt-open');
+ document.body.style.overflow = '';
+ setTimeout(() => overlay.remove(), 200);
+ window.removeEventListener('keydown', onKey);
+ };
+ const onKey = (e) => { if (e.key === 'Escape') close(); };
+ window.addEventListener('keydown', onKey);
+ overlay.querySelector('.tt-close').addEventListener('click', close);
+ overlay.addEventListener('mousedown', (e) => { if (e.target === overlay) close(); });
+
+ const form = overlay.querySelector('[data-tt-form]');
+ const goalEl = overlay.querySelector('[data-goal]');
+ const budgetEl = overlay.querySelector('[data-budget]');
+ const stage = overlay.querySelector('[data-stage]');
+ const statusEl = overlay.querySelector('[data-status]');
+ const go = overlay.querySelector('[data-go]');
+ const examples = overlay.querySelector('[data-examples]');
+
+ // Lead picker (only on surfaces that don't already imply a lead).
+ const leadField = overlay.querySelector('[data-lead-field]');
+ const leadSel = overlay.querySelector('[data-lead]');
+ if (leads.length > 1 || (leads.length === 1 && !presetGoal)) {
+ leadField.hidden = false;
+ leadSel.innerHTML = leads.map((a) => `<option value="${esc(a.id)}">${esc(a.name || 'Agent')}</option>`).join('');
+ }
+ const resolveLead = () => (leads.length ? (leadSel.value || leads[0].id) : null);
+
+ EXAMPLE_GOALS.forEach((g) => {
+ const chip = document.createElement('button');
+ chip.type = 'button';
+ chip.className = 'tt-chip';
+ chip.textContent = truncate(g, 52);
+ chip.addEventListener('click', () => { goalEl.value = g; goalEl.focus(); });
+ examples.appendChild(chip);
+ });
+
+ if (presetGoal) goalEl.value = presetGoal;
+ setTimeout(() => goalEl.focus(), 60);
+
+ form.addEventListener('submit', (e) => {
+ e.preventDefault();
+ const goal = goalEl.value.trim();
+ const leadAgentId = resolveLead();
+ if (!goal) { goalEl.focus(); return; }
+ if (!leadAgentId) {
+ statusEl.className = 'tt-status err';
+ statusEl.textContent = 'No agent available to lead — create one first.';
+ return;
+ }
+ const maxUsd = Math.min(HARD_MAX_USD, Math.max(0.1, Number(budgetEl.value) || DEFAULT_MAX_USD));
+ go.disabled = true; goalEl.disabled = true; budgetEl.disabled = true; leadSel.disabled = true;
+ stage.hidden = false;
+ runTeamTask({ leadAgentId, goal, maxUsd, stage, statusEl }).promise.finally(() => {
+ go.disabled = false; goalEl.disabled = false; budgetEl.disabled = false; leadSel.disabled = false;
+ go.textContent = 'Run another →';
+ });
+ });
+
+ return { overlay, close };
+}
+
+// ── owned-agent roster ─────────────────────────────────────────────────────────
+
+async function fetchOwnedAgents() {
+ try {
+ const res = await fetch('/api/agents', { credentials: 'include', headers: { accept: 'application/json' } });
+ if (!res.ok) return [];
+ const data = await res.json();
+ return (data.agents || []).map((a) => ({ id: a.id, name: a.name || a.display_name || 'Agent' }));
+ } catch {
+ return [];
+ }
+}
+
+// ── context wiring ─────────────────────────────────────────────────────────────
+
+// /agents-live — inject a launcher into the hero.
+function mountOnLiveWall() {
+ const hero = document.querySelector('.al-hero');
+ if (!hero || hero.querySelector('.tt-launch')) return;
+ ensureStyles();
+ const btn = document.createElement('button');
+ btn.type = 'button';
+ btn.className = 'tt-launch';
+ btn.innerHTML = `<span class="tt-launch-ico">⊹</span> Run a Team Task`;
+ btn.addEventListener('click', async () => {
+ btn.disabled = true;
+ const leads = await fetchOwnedAgents();
+ btn.disabled = false;
+ if (!leads.length) {
+ // Empty state: route the user to create an agent to lead with.
+ const { overlay } = openOverlay({ leads: [] });
+ const stage = overlay.querySelector('[data-stage]');
+ const status = overlay.querySelector('[data-status]');
+ overlay.querySelector('[data-tt-form]').hidden = true;
+ stage.hidden = false;
+ stage.innerHTML = `<div class="tt-empty">You need an agent to lead the team.<br><a href="/dashboard-next/create">Create an agent →</a> then come back and give it a goal.</div>`;
+ status.textContent = '';
+ return;
+ }
+ openOverlay({ leads });
+ });
+ hero.appendChild(btn);
+}
+
+// /agent-screen — add a "Team" toggle to the task bar. When on, intercept the
+// task submit (capture phase, before agent-screen.js's own handler) and run the
+// current agent as the team lead.
+function mountOnAgentScreen() {
+ const form = document.getElementById('asc-task-form');
+ const input = document.getElementById('asc-task-input');
+ const send = document.getElementById('asc-task-send');
+ if (!form || !input || !send) return;
+ const params = new URLSearchParams(location.search);
+ const leadAgentId = params.get('agentId');
+ if (!leadAgentId) return;
+ ensureStyles();
+
+ const toggle = document.createElement('button');
+ toggle.type = 'button';
+ toggle.className = 'tt-toggle';
+ toggle.setAttribute('aria-pressed', 'false');
+ toggle.title = 'Run this goal as a team — the agent splits the work and hires teammates';
+ toggle.innerHTML = `<span class="tt-toggle-dot"></span>Team`;
+ let teamMode = false;
+ toggle.addEventListener('click', () => {
+ teamMode = !teamMode;
+ toggle.setAttribute('aria-pressed', String(teamMode));
+ input.placeholder = teamMode
+ ? 'Give a goal — the team will split it and hire teammates…'
+ : input.dataset.soloPlaceholder || input.placeholder;
+ });
+ input.dataset.soloPlaceholder = input.placeholder;
+ send.insertAdjacentElement('afterend', toggle);
+
+ form.addEventListener('submit', (e) => {
+ if (!teamMode) return; // solo path — let agent-screen.js handle it
+ e.preventDefault();
+ e.stopImmediatePropagation();
+ const goal = input.value.trim();
+ if (!goal) return;
+ input.value = '';
+ const leadName = document.querySelector('.asc-agent-name')?.textContent?.trim() || null;
+ openTeamForAgent(leadAgentId, leadName, goal);
+ }, true);
+}
+
+// Open the overlay pre-targeted at a known lead, immediately launching the goal.
+function openTeamForAgent(leadAgentId, leadName, goal) {
+ const { overlay } = openOverlay({ leads: [{ id: leadAgentId, name: leadName || 'this agent' }], presetGoal: goal });
+ // Auto-submit so the graph starts right away.
+ const form = overlay.querySelector('[data-tt-form]');
+ requestAnimationFrame(() => form.requestSubmit());
+}
+
+// ── boot ────────────────────────────────────────────────────────────────────────
+
+function boot() {
+ if (document.getElementById('al-grid')) mountOnLiveWall();
+ if (document.getElementById('asc-task-form')) mountOnAgentScreen();
+}
+
+if (document.readyState === 'loading') {
+ document.addEventListener('DOMContentLoaded', boot);
+} else {
+ boot();
+}
diff --git a/src/agents-live-arena.js b/src/agents-live-arena.js
new file mode 100644
index 000000000..69a19bfdc
--- /dev/null
+++ b/src/agents-live-arena.js
@@ -0,0 +1,203 @@
+// Reputation Arena — turns the live agent wall into a ranked competition.
+//
+// On /agents-live every card already streams a live screen; this layer stamps
+// each one with the agent's REAL wallet-trust reputation (tier badge + score
+// chip), then continuously reorders the wall so the most-trusted agents rise to
+// the top. The numbers come straight from /api/agents/reputation-batch (the same
+// non-gameable score the trust badge shows everywhere else) via the shared
+// fetchReputationBatch — nothing is computed or faked here. The ordering itself
+// is the pure, unit-tested rankArena() from ./shared/arena-rank.js.
+//
+// Reorders are animated with FLIP: we measure each card's box before and after
+// the DOM move and play the delta as a transform, so cards glide to their new
+// rank instead of jumping. A card that climbs pulses its tier accent. Live SSE
+// streams and canvases are preserved because we MOVE the existing card nodes
+// (never recreate them).
+
+import { fetchReputationBatch } from './shared/agent-reputation.js';
+import { rankArena } from './shared/arena-rank.js';
+
+const REFRESH_MS = 45_000; // reputation moves slowly — poll on a calm cadence
+const SCHEDULE_DEBOUNCE_MS = 220;
+
+const SHIELD =
+ '<svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M12 22s8-4 8-10V5l-8-3-8 3v7c0 6 8 10 8 10z"/></svg>';
+
+function esc(s) {
+ return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
+}
+
+let _stylesInjected = false;
+function ensureStyles() {
+ if (_stylesInjected || typeof document === 'undefined') return;
+ _stylesInjected = true;
+ const st = document.createElement('style');
+ st.id = 'al-arena-style';
+ st.textContent = `
+.al-rep-chip-slot{display:inline-flex;vertical-align:middle;margin-left:6px}
+.al-rep-chip{display:inline-flex;align-items:center;gap:4px;font:600 10px/1 var(--font-mono,ui-monospace,monospace);
+ padding:2px 6px;border-radius:999px;color:var(--rep-accent,#c4b5fd);white-space:nowrap;
+ background:color-mix(in srgb,var(--rep-accent,#c4b5fd) 13%,transparent);
+ border:1px solid color-mix(in srgb,var(--rep-accent,#c4b5fd) 32%,transparent)}
+.al-rep-chip svg{width:10px;height:10px;opacity:.9}
+.al-rep-chip-tier{letter-spacing:.02em}
+.al-rep-chip-score{padding-left:4px;color:#fff;border-left:1px solid color-mix(in srgb,var(--rep-accent,#c4b5fd) 32%,transparent)}
+.al-rep-chip--new{color:#9ca3af;background:rgba(255,255,255,.05);border-color:rgba(255,255,255,.12)}
+.al-card{will-change:transform}
+.al-card--climbed{animation:al-rep-climb 1.15s ease-out}
+@keyframes al-rep-climb{0%{box-shadow:0 0 0 0 color-mix(in srgb,var(--rep-accent,#9a7bff) 65%,transparent)}100%{box-shadow:0 0 0 14px rgba(0,0,0,0)}}
+@media (prefers-reduced-motion:reduce){.al-card--climbed{animation:none}}`;
+ document.head.appendChild(st);
+}
+
+function chipHTML(rep) {
+ if (!rep) return '';
+ if (rep.isNew) {
+ return `<span class="al-rep-chip al-rep-chip--new" title="New agent — no on-chain track record yet">✦ New</span>`;
+ }
+ const score = Math.round(Number(rep.score));
+ if (!Number.isFinite(score)) return '';
+ const tip = `Wallet trust ${score}/100 · ${rep.tierLabel || ''} — every point earned through real on-chain activity.`;
+ return (
+ `<span class="al-rep-chip" style="--rep-accent:${esc(rep.accent || '#c4b5fd')}" title="${esc(tip)}">` +
+ SHIELD +
+ `<span class="al-rep-chip-tier">${esc(rep.tierLabel || '')}</span>` +
+ `<span class="al-rep-chip-score">${score}</span>` +
+ `</span>`
+ );
+}
+
+/**
+ * Create the arena controller bound to the wall's grid and per-card state map.
+ *
+ * @param {object} ctx
+ * @param {HTMLElement} ctx.grid the card container
+ * @param {Map<string,object>} ctx.cards agentId → card state ({ card } node)
+ * @param {boolean} [ctx.reducedMotion] skip FLIP animation when true
+ * @returns {{ start():void, schedule():void, refresh():Promise<void> }}
+ */
+export function createArena({ grid, cards, reducedMotion = false }) {
+ ensureStyles();
+ let _scheduleTimer = null;
+ let _interval = null;
+ let _running = false;
+
+ function applyChip(state) {
+ const meta = state.card.querySelector('.al-card-meta');
+ if (!meta) return;
+ const html = chipHTML(state.rep);
+ let slot = meta.querySelector('.al-rep-chip-slot');
+ if (!html) {
+ slot?.remove();
+ return;
+ }
+ if (!slot) {
+ slot = document.createElement('span');
+ slot.className = 'al-rep-chip-slot';
+ const name = meta.querySelector('.al-card-name');
+ if (name) name.appendChild(slot);
+ else meta.appendChild(slot);
+ }
+ slot.innerHTML = html;
+ if (state.rep?.accent) state.card.style.setProperty('--rep-accent', state.rep.accent);
+ }
+
+ // FLIP reorder: move existing card nodes into ranked order and animate the
+ // delta. Returns silently when the order is already correct so an unchanged
+ // wall never animates.
+ function flipReorder() {
+ const nodes = [...grid.querySelectorAll('.al-card')];
+ if (nodes.length < 2) return;
+
+ const entries = nodes.map((n) => ({ id: n.dataset.agentId, rep: cards.get(n.dataset.agentId)?.rep }));
+ const orderedIds = rankArena(entries);
+ const currentIds = nodes.map((n) => n.dataset.agentId);
+ if (orderedIds.every((id, i) => id === currentIds[i])) return; // already ranked
+
+ const oldIndex = new Map(currentIds.map((id, i) => [id, i]));
+ const first = reducedMotion ? null : new Map(nodes.map((n) => [n, n.getBoundingClientRect()]));
+ const byId = new Map(nodes.map((n) => [n.dataset.agentId, n]));
+
+ // Reorder the DOM in one pass (a fragment keeps it to a single reflow).
+ const frag = document.createDocumentFragment();
+ for (const id of orderedIds) {
+ const n = byId.get(id);
+ if (n) frag.appendChild(n);
+ }
+ grid.appendChild(frag);
+
+ // Flag the climbers so they pulse, regardless of motion preference.
+ orderedIds.forEach((id, newIdx) => {
+ if ((oldIndex.get(id) ?? newIdx) > newIdx) {
+ const n = byId.get(id);
+ if (!n) return;
+ n.classList.remove('al-card--climbed');
+ void n.offsetWidth; // restart the animation
+ n.classList.add('al-card--climbed');
+ }
+ });
+
+ if (reducedMotion || !first) return;
+
+ // FLIP: invert to the old position, then release to the new one.
+ for (const n of nodes) {
+ const f = first.get(n);
+ const last = n.getBoundingClientRect();
+ const dx = f.left - last.left;
+ const dy = f.top - last.top;
+ if (!dx && !dy) continue;
+ n.style.transition = 'none';
+ n.style.transform = `translate(${dx}px, ${dy}px)`;
+ }
+ requestAnimationFrame(() => {
+ for (const n of nodes) {
+ if (!n.style.transform) continue;
+ n.style.transition = 'transform 460ms cubic-bezier(.22,.61,.36,1)';
+ n.style.transform = '';
+ const cleanup = () => {
+ n.style.transition = '';
+ n.removeEventListener('transitionend', cleanup);
+ };
+ n.addEventListener('transitionend', cleanup);
+ }
+ });
+ }
+
+ async function refresh() {
+ if (typeof document !== 'undefined' && document.hidden) return;
+ const ids = [...cards.keys()];
+ if (!ids.length) return;
+ let map;
+ try {
+ map = await fetchReputationBatch(ids);
+ } catch {
+ return; // chips stay in their resting state; ordering is left untouched
+ }
+ for (const id of ids) {
+ const state = cards.get(id);
+ if (!state) continue;
+ if (map[id]) state.rep = map[id];
+ applyChip(state);
+ }
+ flipReorder();
+ }
+
+ function schedule() {
+ if (_scheduleTimer) return;
+ _scheduleTimer = setTimeout(() => {
+ _scheduleTimer = null;
+ refresh();
+ }, SCHEDULE_DEBOUNCE_MS);
+ }
+
+ function start() {
+ if (_running) return;
+ _running = true;
+ refresh();
+ _interval = setInterval(() => {
+ if (typeof document === 'undefined' || !document.hidden) refresh();
+ }, REFRESH_MS);
+ }
+
+ return { start, schedule, refresh, _stop: () => clearInterval(_interval) };
+}
diff --git a/src/agents-live.js b/src/agents-live.js
index 1bfc8d4f6..bd919bff9 100644
--- a/src/agents-live.js
+++ b/src/agents-live.js
@@ -14,9 +14,15 @@
// agent on demand without paying for an idle browser per agent.
import { parsePnlDelta, formatSol, formatUsd } from './shared/trade-pnl.js';
+import { mountAgentReactions } from './agent-reactions.js';
+import { fetchBatchBalances } from './shared/pnl-fetch.js';
+import { formatPnl, formatUsd as formatNetWorthUsd } from './shared/pnl-snapshot.js';
import { coalesce, timeline, colorHex } from './activity-cinema.js';
import { connectFeed, loadSnapshot } from './theater-feed.js';
import { TOUR_PREFIX } from './tour-commentary.js';
+import { sanitizeMmEvent, fmtPriceSol } from './shared/mm-render.js';
+import { parseForgeFrame } from './shared/forge-frames.js';
+import { createArena } from './agents-live-arena.js';
// Subtle accent for a card showing a live Coin World Tour walkthrough.
(() => {
@@ -27,6 +33,23 @@ import { TOUR_PREFIX } from './tour-commentary.js';
document.head.appendChild(st);
})();
+// Floor Defense badge — surfaces the market-maker floor an agent is defending,
+// pulsing on every dip-buy and ambering when the marker touches the floor line.
+(() => {
+ if (document.getElementById('al-mm-style')) return;
+ const st = document.createElement('style');
+ st.id = 'al-mm-style';
+ st.textContent = `
+.al-card-floor{position:absolute;left:10px;bottom:10px;z-index:5;display:inline-flex;align-items:center;gap:5px;padding:3px 8px;border-radius:999px;font:600 11px/1 var(--font-mono,ui-monospace,monospace);color:#6ee7ff;background:rgba(110,231,255,.1);border:1px solid rgba(110,231,255,.32);backdrop-filter:blur(6px);transition:box-shadow .25s,border-color .25s,color .25s}
+.al-card-floor .al-floor-anchor{font-size:11px;opacity:.85}
+.al-card-floor.touch{color:#34d399;border-color:rgba(52,211,153,.45);background:rgba(52,211,153,.12)}
+.al-card-floor.defend{animation:al-floor-flash .9s ease-out}
+.al-card-floor .al-floor-sim{font-weight:700;letter-spacing:.05em;color:#9a7bff;background:rgba(154,123,255,.16);border-radius:4px;padding:1px 4px;font-size:9px}
+@keyframes al-floor-flash{0%{box-shadow:0 0 0 0 rgba(52,211,153,.6)}100%{box-shadow:0 0 0 10px rgba(52,211,153,0)}}
+@media (prefers-reduced-motion: reduce){.al-card-floor.defend{animation:none}}`;
+ document.head.appendChild(st);
+})();
+
const grid = document.getElementById('al-grid');
const liveCount = document.getElementById('al-live-count');
const statsBar = document.getElementById('al-stats');
@@ -70,6 +93,11 @@ const REDUCED_MOTION = typeof matchMedia === 'function'
const _animating = new Set();
let _rafId = null;
+// Reputation Arena — stamps each card with its real wallet-trust tier/score and
+// reorders the wall so the most-trusted agents rise to the top (see
+// agents-live-arena.js). Refreshed after every roster page and on a slow poll.
+const _arena = createArena({ grid, cards: _cards, reducedMotion: REDUCED_MOTION });
+
function ensureRaf() {
if (_rafId != null) return;
const tick = () => {
@@ -163,7 +191,14 @@ function buildCard(agent) {
<div class="al-card-live-dot idle" data-dot></div>
<span data-status>Connecting</span>
</div>
+ <div class="al-card-floor" data-mm hidden title="Market-maker floor under defense">
+ <span class="al-floor-anchor">⚓</span>
+ <span data-mm-floor></span>
+ <span class="al-floor-sim" data-mm-sim hidden>SIM</span>
+ </div>
+ <div class="al-card-networth" data-networth hidden title="24h portfolio change"></div>
<div class="al-card-expand">⛶</div>
+ <div class="al-card-reactions" data-reactions></div>
</div>
<div class="al-card-info">
${avatar
@@ -179,6 +214,53 @@ function buildCard(agent) {
return el;
}
+// Surface the market-maker floor an agent is defending. `live` flags a real-time
+// event (pulse the badge on a dip-buy) vs a backfill draw (just set the line).
+// Sanitized through the shared mm-render whitelist so a bad push can't poison it.
+function updateMmBadge(state, rawMm, live) {
+ const mm = sanitizeMmEvent(rawMm);
+ if (!mm) return;
+ const badge = state.card.querySelector('[data-mm]');
+ if (!badge) return;
+ badge.hidden = false;
+ const floorEl = badge.querySelector('[data-mm-floor]');
+ if (floorEl) floorEl.textContent = fmtPriceSol(mm.floorSol);
+ const simEl = badge.querySelector('[data-mm-sim]');
+ if (simEl) simEl.hidden = !mm.simulate;
+ const touching = mm.floorSol > 0 && mm.priceSol > 0 && mm.priceSol <= mm.floorSol * 1.02;
+ badge.classList.toggle('touch', touching);
+ if (live && mm.type === 'mm_defend') {
+ badge.classList.remove('defend');
+ // reflow so the animation restarts on a back-to-back defend
+ void badge.offsetWidth;
+ badge.classList.add('defend');
+ if (state.action) state.action.textContent = `🛡 Defended floor at ${fmtPriceSol(mm.priceSol)}`;
+ }
+}
+
+// Surface a live agent-to-agent hire on the card. The hire visualizer lives on
+// /agent-screen; here we just flash the wall card when one settles and label the
+// action line with who got hired, linking the wall to live commerce. `live` gates
+// the flash so backfill replays only set the text.
+function updateHireFlash(state, meta, live) {
+ if (!meta || meta.kind !== 'a2a_hire' || !state.action) return;
+ const provider = String(meta.providerName || 'an agent').slice(0, 22);
+ const usd = typeof meta.usd === 'number' && Number.isFinite(meta.usd) ? `$${meta.usd.toFixed(2)}` : '';
+ if (meta.phase === 'settled' || meta.phase === 'recorded') {
+ state.action.textContent = `⇄ hired ${provider}${usd ? ` · ${usd}` : ''}`;
+ state.action.classList.remove('al-on-air');
+ if (live && meta.phase === 'settled') {
+ state.card.classList.remove('al-card--hired');
+ void state.card.offsetWidth; // restart the flash keyframe
+ state.card.classList.add('al-card--hired');
+ }
+ } else if (meta.phase === 'over_cap') {
+ state.action.textContent = `⚠ hire skipped · over cap`;
+ } else if (meta.phase === 'quote' || meta.phase === 'running' || meta.phase === 'reserved') {
+ state.action.textContent = `⇄ hiring ${provider}${usd ? ` · ${usd}` : ''}…`;
+ }
+}
+
// Format a beat's age into a compact relative stamp.
function fmtAge(ts) {
const age = Math.max(0, Math.round((Date.now() - (ts || Date.now())) / 1000));
@@ -369,6 +451,25 @@ function renderCardPnl(state) {
chip.title = `Session realized P&L · ${formatSol(state.realizedSol)}`;
}
+// Vanity Grinder ticker: turn a grind frame into a compact card line. The live
+// grind pushes `analysis` frames whose activity reads "4.18M attempts · 38.9k/sec
+// · expected ~11.3M"; the MATCH frame carries a { kind:'vanity_match', address }
+// meta sidecar. Returns a short string for the card's action line, or null when
+// the frame isn't a grind frame.
+function parseGrindTicker(msg) {
+ if (msg?.meta?.kind === 'vanity_match' && typeof msg.meta.address === 'string') {
+ const a = msg.meta.address;
+ return `🔑 matched ${a.slice(0, 6)}…${a.slice(-4)}`;
+ }
+ const act = typeof msg?.activity === 'string' ? msg.activity : '';
+ if (/\d[\d.,kM]*\s*attempts/i.test(act) && /\/sec/i.test(act)) {
+ const rate = act.match(/·\s*([\d.,kM]+\/sec)/i);
+ return rate ? `⛏ grinding · ${rate[1]}` : `⛏ ${act}`;
+ }
+ if (/^MATCH\b/i.test(act)) return '🔑 vanity match found';
+ return null;
+}
+
function attachStream(state) {
const { card, agentId } = state;
if (state.es) { try { state.es.close(); } catch { /* */ } }
@@ -403,13 +504,22 @@ function attachStream(state) {
// Anchor bulletin: surface the on-air headline on the card even when the
// frame is text-only (no rendered desk image).
if (msg.type === 'analysis' && msg.activity && state.action) {
- if (state.isTour) {
+ const grind = parseGrindTicker(msg);
+ if (grind) {
+ state.action.textContent = grind;
+ state.action.classList.remove('al-on-air');
+ } else if (state.isTour) {
state.action.textContent = `🎬 ${msg.activity}`;
} else {
state.action.textContent = `🔴 ON AIR · ${msg.activity}`;
state.action.classList.add('al-on-air');
}
}
+ // Live hire frames may be text/meta-only — handle before the image gate.
+ if (msg.meta?.kind === 'a2a_hire') updateHireFlash(state, msg.meta, true);
+ // Market-maker frames are text-only (data:null) — drive the floor badge
+ // before the image gate, or the live dip-buy pulse would never fire.
+ if (msg.mm) updateMmBadge(state, msg.mm, true);
const src = msg.frame || msg.data;
if (!src) return;
const img = new Image();
@@ -422,7 +532,13 @@ function attachStream(state) {
hideWarming(state);
stopStatusPolling(state);
_fpsMap.set(agentId, (_fpsMap.get(agentId) || 0) + 1);
- if (msg.activity && state.action) {
+ const grindTickerImg = parseGrindTicker(msg);
+ if (grindTickerImg && state.action) {
+ // Grind frames carry a rendered keyspace image — keep the compact
+ // attempts/sec ticker rather than the raw activity string.
+ state.action.textContent = grindTickerImg;
+ state.action.classList.remove('al-on-air');
+ } else if (msg.activity && state.action) {
if (msg.activity.startsWith(TOUR_PREFIX)) {
state.isTour = true;
state.card.classList.add('al-card--tour');
@@ -432,6 +548,14 @@ function attachStream(state) {
state.action.textContent = msg.activity;
}
}
+ // Live Avatar Forge: a completed forge rides a `meta` sidecar — surface
+ // the fresh creation on the card so the wall shows what was just built.
+ const forgeHit = parseForgeFrame(msg);
+ if (forgeHit && state.action) {
+ state.action.textContent = forgeHit.prompt ? `\u2726 forged: ${forgeHit.prompt}` : '\u2726 forged a new avatar';
+ state.action.classList.remove('al-on-air');
+ state.card.classList.add('al-card--forged');
+ }
if (msg.type === 'trade') ingestCardPnl(state, msg);
} catch { /* malformed */ }
});
@@ -443,12 +567,31 @@ function attachStream(state) {
state.entries = entries;
// Fold any realized exits in the backfill into the running PnL chip.
entries.forEach((entry) => ingestCardPnl(state, entry));
+ // Draw the floor at the last known MM state (no flash — backfill, not live).
+ for (let i = entries.length - 1; i >= 0; i--) {
+ if (entries[i]?.mm) { updateMmBadge(state, entries[i].mm, false); break; }
+ }
+ const lastForge = [...entries].reverse().map(parseForgeFrame).find(Boolean);
+ if (lastForge && state.action) {
+ state.action.textContent = lastForge.prompt ? `\u2726 forged: ${lastForge.prompt}` : '\u2726 forged a new avatar';
+ state.card.classList.add('al-card--forged');
+ }
+ // Reflect the latest hire phase from backfill (no flash — history).
+ const lastHire = [...entries].reverse().find((e) => e?.meta?.kind === 'a2a_hire');
+ if (lastHire) updateHireFlash(state, lastHire.meta, false);
}
if (!isLiveNow(state)) { paintActivity(state); setLive(false); }
} catch { /* */ }
});
- es.addEventListener('open', () => { if (statusEl.textContent === 'Connecting') setLive(false); });
+ es.addEventListener('open', () => {
+ if (statusEl.textContent === 'Connecting') setLive(false);
+ state.reactions?.setConnected(true);
+ });
+ // Live spectator reactions for this card — float them over the screen + tick the count.
+ es.addEventListener('reaction', (e) => {
+ try { state.reactions?.onReaction(JSON.parse(e.data)); } catch { /* malformed */ }
+ });
es.addEventListener('dark', () => {
setLive(false);
paintActivity(state);
@@ -568,6 +711,7 @@ function getObserver() {
if (entry.isIntersecting) {
_inView.add(id);
signalWatch(id);
+ scheduleNetworthFlush();
if (!isLiveNow(state)) startStatusPolling(state);
} else {
_inView.delete(id);
@@ -602,8 +746,26 @@ function mountAgent(agent) {
realizedUsd: 0,
sawUsd: false,
seenPnlTs: new Set(),
+ reactions: null,
};
_cards.set(id, state);
+ // Spectator reactions + tips on the card. The bar posts reactions and opens the
+ // real tip flow; floating emojis rise over the screen and the count ticks the
+ // watch-intent signal. We feed it the card's existing stream (subscribe:false),
+ // so a flood of cards never doubles SSE connections.
+ const reactHost = card.querySelector('[data-reactions]');
+ const screenHost = card.querySelector('.al-card-screen');
+ if (reactHost && screenHost) {
+ state.reactions = mountAgentReactions({
+ agentId: id,
+ barHost: reactHost,
+ overlayHost: screenHost,
+ getAgent: () => agent,
+ compact: true,
+ voice: false, // wall cards have no avatar cam / audio surface — overlay + count only
+ subscribe: false,
+ });
+ }
attachStream(state);
// 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.
@@ -634,6 +796,7 @@ async function loadMore() {
}
agents.forEach(mountAgent);
updateStats();
+ _arena.schedule();
_loading = false;
}
@@ -809,12 +972,76 @@ function startTicker() {
// ── boot ──────────────────────────────────────────────────────────────────────
+// ── live net-worth badges ─────────────────────────────────────────────────────
+// Each on-screen card carries a compact 24h portfolio-change badge in its top
+// corner — the wall-scale view of the same scoreboard the agent-screen HUD shows.
+// Real on-chain valuation, batched: one POST /api/agents/balances for every
+// visible card (the endpoint exists precisely to avoid an N× request storm),
+// refreshed on a slow cadence and only while the tab is visible. Hidden when a
+// wallet has no value or no 24h history yet — never zeroed, never faked.
+const NETWORTH_POLL_MS = 60_000;
+let _networthFlushTimer = null;
+
+function scheduleNetworthFlush() {
+ if (_networthFlushTimer) return;
+ _networthFlushTimer = setTimeout(() => { _networthFlushTimer = null; hydrateNetworth(); }, 150);
+}
+
+async function hydrateNetworth() {
+ if (document.hidden) return;
+ const ids = [..._inView].filter((id) => _cards.has(id));
+ if (!ids.length) return;
+ let map;
+ try { map = await fetchBatchBalances(ids); } catch { return; }
+ for (const id of ids) {
+ const state = _cards.get(id);
+ if (state) applyNetworthBadge(state, map.get(id));
+ }
+}
+
+function applyNetworthBadge(state, snap) {
+ const badge = state.card.querySelector('[data-networth]');
+ if (!badge) return;
+ if (!snap || !snap.priced || snap.change24hPct == null) { badge.hidden = true; return; }
+ const d = formatPnl(snap.change24hPct);
+ badge.hidden = false;
+ badge.dataset.tone = d.tone;
+ badge.innerHTML = `<span class="al-nw-arrow">${d.arrow}</span>${esc(d.text)}`;
+ const win = snap.windowHours != null && snap.windowHours > 0 ? `${Math.round(snap.windowHours)}h` : '24h';
+ badge.title = `Net worth ${formatNetWorthUsd(snap.netWorthUsd, { compact: false })} · ${d.text} ${win}`;
+}
+
+function startNetworthHydration() {
+ scheduleNetworthFlush();
+ setInterval(() => {
+ if (!document.hidden && _inView.size) hydrateNetworth();
+ }, NETWORTH_POLL_MS);
+}
+
+// Reaction-bar chrome for wall cards: a slim, hover-revealed strip pinned to the
+// bottom of each card's screen, above the floating-emoji overlay. Injected once.
+if (!document.getElementById('al-reactions-style')) {
+ const st = document.createElement('style');
+ st.id = 'al-reactions-style';
+ st.textContent = `
+.al-card-reactions{position:absolute;left:8px;right:8px;bottom:8px;z-index:7;display:flex;justify-content:center;
+ padding:4px 6px;border-radius:12px;background:linear-gradient(180deg,rgba(8,8,12,.18),rgba(8,8,12,.72));
+ backdrop-filter:blur(6px);opacity:0;transform:translateY(6px);pointer-events:none;
+ transition:opacity .18s ease,transform .18s ease;}
+.al-card:hover .al-card-reactions,.al-card:focus-within .al-card-reactions{opacity:1;transform:none;pointer-events:auto;}
+@media (hover:none){.al-card-reactions{opacity:1;transform:none;pointer-events:auto;}}
+@media (prefers-reduced-motion:reduce){.al-card-reactions{transition:none;}}`;
+ document.head.appendChild(st);
+}
+
await loadMore();
startTicker();
startFpsTicker();
startIdleRepaint();
startWatchPings();
startInfiniteScroll();
+startNetworthHydration();
+_arena.start();
document.addEventListener('visibilitychange', () => {
if (document.hidden) suspendStreams();
diff --git a/src/launch-director.js b/src/launch-director.js
index abd916107..a48eb750c 100644
--- a/src/launch-director.js
+++ b/src/launch-director.js
@@ -312,22 +312,32 @@ export async function renderLaunchHud(state) {
railY += rowH;
});
- // Narration / result strip at the bottom.
- const stripY = 600;
+ // Narration / result block — sits in the open right column UNDER the status
+ // rail, clear of the token card on the left.
+ const infoX = railX;
+ const infoW = HUD_W - railX - 56;
+ let infoY = railY + 28;
ctx.fillStyle = errored ? '#ff8e8e' : '#aeb8e6';
ctx.font = '500 22px ui-sans-serif, system-ui, sans-serif';
const line = errored ? state.error || 'Launch failed' : state.narration || '';
- ctx.fillText(clip(ctx, line, HUD_W - 112), 56, stripY);
+ for (const wrapped of wrapText(ctx, line, infoW).slice(0, 2)) {
+ ctx.fillText(wrapped, infoX, infoY);
+ infoY += 30;
+ }
if (state.result?.signature) {
+ infoY += 8;
ctx.fillStyle = '#7f8bbf';
ctx.font = '500 18px ui-monospace, Menlo, monospace';
- ctx.fillText(`mint ${truncMid(state.result.mint, 6, 6)}`, 56, stripY + 38);
- ctx.fillText(`pump.fun/coin/${truncMid(state.result.mint, 6, 6)}`, 56, stripY + 66);
- ctx.fillText(`solscan.io/tx/${truncMid(state.result.signature, 6, 6)}`, 560, stripY + 66);
+ ctx.fillText(`mint ${truncMid(state.result.mint, 6, 6)}`, infoX, infoY);
+ ctx.fillText(`pump.fun/coin/${truncMid(state.result.mint, 6, 6)}`, infoX, infoY + 30);
+ ctx.fillText(`solscan.io/tx/${truncMid(state.result.signature, 6, 6)}`, infoX, infoY + 60);
}
- return canvas.toDataURL('image/png');
+ // JPEG, not PNG: the screen-push API caps a frame at ~800 KB of base64, and a
+ // 1280×720 PNG with an embedded cover image blows past that and gets truncated
+ // into a corrupt frame. JPEG at 0.85 keeps the same HUD well under the cap.
+ return canvas.toDataURL('image/jpeg', 0.85);
}
function drawBadge(ctx, text, rightX, baselineY) {
@@ -359,6 +369,24 @@ function clip(ctx, text, maxW) {
return `${t}…`;
}
+// Greedy word-wrap into lines no wider than maxW.
+function wrapText(ctx, text, maxW) {
+ const words = String(text || '').split(/\s+/).filter(Boolean);
+ const lines = [];
+ let line = '';
+ for (const w of words) {
+ const candidate = line ? `${line} ${w}` : w;
+ if (ctx.measureText(candidate).width > maxW && line) {
+ lines.push(line);
+ line = w;
+ } else {
+ line = candidate;
+ }
+ }
+ if (line) lines.push(line);
+ return lines.length ? lines : [''];
+}
+
// Load an image without tainting the canvas. crossOrigin='anonymous' keeps
// toDataURL() working when the host serves CORS (IPFS/Arweave gateways do);
// otherwise we resolve null and the HUD draws its monogram fallback.
diff --git a/src/play/arena.js b/src/play/arena.js
index 8f11b7722..a08841588 100644
--- a/src/play/arena.js
+++ b/src/play/arena.js
@@ -129,19 +129,21 @@ function ingest(data) {
// 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.
+ // waypoint loop — driving the REAL camera/avatar — while narrating what's
+ // climbing three.ws's OWN launch feed (/api/pump/launches). tour-commentary.js
+ // owns the pure feed→line mapping; the caster passes the feed in and renders the
+ // result. No faked motion, no mocks. $THREE is the only coin the tour promotes.
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(
+ // Commentary for the stop the guide most recently reached, given the
+ // three.ws launch feed (/api/pump/launches) the caster fetched. Returns
+ // { line, badge, items, … }.
+ commentary: (launches) => tourCommentary(
world?.tourLocation?.() || 'lobby',
- Array.isArray(trending) ? trending : [],
+ Array.isArray(launches) ? launches : [],
),
};
diff --git a/src/shared/agent-screen-client.js b/src/shared/agent-screen-client.js
index 927cdecbe..27c04071d 100644
--- a/src/shared/agent-screen-client.js
+++ b/src/shared/agent-screen-client.js
@@ -10,6 +10,7 @@
// onLog(entries) — called with [{ ts, activity, type }] (backfill)
// onOpen(info) — called with { agentId, agentName }
// onDark() — called when the agent's stream goes dark
+// onReaction(payload) — called with { bursts: [{emoji, ts}], total } on viewer reactions
// onError(err) — called on connection error (non-fatal, will retry)
// });
// client.connect();
@@ -20,7 +21,7 @@ const STREAM_URL = (agentId) => `/api/agent-screen-stream?agentId=${encodeURICom
const RECONNECT_DELAYS = [500, 1000, 2000, 5000, 10000]; // ms
export function createAgentScreenClient(agentId, handlers = {}) {
- const { onFrame, onLog, onOpen, onDark, onError } = handlers;
+ const { onFrame, onLog, onOpen, onDark, onError, onReaction } = handlers;
let es = null;
let reconnectTimer = null;
@@ -64,6 +65,11 @@ export function createAgentScreenClient(agentId, handlers = {}) {
onDark?.();
});
+ // Live spectator reactions: { bursts: [{emoji, ts}], total }.
+ es.addEventListener('reaction', (e) => {
+ try { onReaction?.(JSON.parse(e.data)); } catch { /* malformed event */ }
+ });
+
es.addEventListener('ping', () => {
// keepalive — no action needed
});
diff --git a/src/shared/arena-rank.js b/src/shared/arena-rank.js
new file mode 100644
index 000000000..ee8419dd1
--- /dev/null
+++ b/src/shared/arena-rank.js
@@ -0,0 +1,88 @@
+// Reputation Arena — the pure ordering logic that turns the live agent wall into
+// a ranked arena.
+//
+// Every card on /agents-live carries the agent's REAL, server-computed wallet-
+// trust reputation (api/_lib/trust/wallet-reputation.js, surfaced compactly via
+// /api/agents/reputation-batch). This module is the single, side-effect-free
+// source of truth for HOW those scores order the wall, so the ordering can be
+// unit-tested in isolation and never drifts between the wall and any future
+// surface that wants the same "arena" sort.
+//
+// The honest ordering, highest first:
+// 1. RATED agents — by trust score (0..100), best on top.
+// 2. NEW agents — a real identity with no track record yet. They rank below
+// every rated agent (you can't out-rank earned trust by
+// being new) but above agents whose score hasn't loaded.
+// 3. UNKNOWN — reputation not loaded / unavailable. Always last, so a
+// slow or failed read sinks rather than jumps the queue.
+// Ties keep their original (incoming "popular") order — a stable sort — so the
+// wall only ever reorders for a real reputation difference.
+
+// Sentinel arena scores for the non-rated buckets. Kept below any real 0..100
+// trust score so a rated agent always outranks a new/unknown one.
+export const ARENA_SCORE_NEW = -1;
+export const ARENA_SCORE_UNKNOWN = -2;
+
+// Tier → rank, mirroring the server's tier ladder (api/_lib/trust/
+// wallet-reputation.js). Used only as a deterministic tie-breaker when two agents
+// share an identical rounded score but sit in different tiers; the score itself
+// is the primary signal.
+export const TIER_RANK = Object.freeze({
+ elite: 4,
+ trusted: 3,
+ established: 2,
+ emerging: 1,
+ new: 0,
+});
+
+/**
+ * Map a compact reputation record to a single comparable arena score.
+ * Higher sorts earlier. A brand-new agent and an agent with no loaded
+ * reputation fall to fixed sentinels below every real score.
+ *
+ * @param {{score?:number, isNew?:boolean}|null|undefined} rep
+ * @returns {number}
+ */
+export function arenaScore(rep) {
+ if (!rep) return ARENA_SCORE_UNKNOWN;
+ if (rep.isNew) return ARENA_SCORE_NEW;
+ const n = Number(rep.score);
+ return Number.isFinite(n) ? n : ARENA_SCORE_UNKNOWN;
+}
+
+/**
+ * Stable comparator for arena entries. Each entry is `{ rep, index }` where
+ * `index` is the agent's original position on the wall (used to keep ties in
+ * their incoming order). Sorts by arena score descending, then tier rank
+ * descending, then original index ascending.
+ *
+ * @param {{rep?:object, index?:number}} a
+ * @param {{rep?:object, index?:number}} b
+ * @returns {number}
+ */
+export function compareArenaEntries(a, b) {
+ const sa = arenaScore(a?.rep);
+ const sb = arenaScore(b?.rep);
+ if (sa !== sb) return sb - sa;
+
+ const ta = TIER_RANK[a?.rep?.tier] ?? -1;
+ const tb = TIER_RANK[b?.rep?.tier] ?? -1;
+ if (ta !== tb) return tb - ta;
+
+ return (a?.index ?? 0) - (b?.index ?? 0);
+}
+
+/**
+ * Order a list of `{ id, rep }` entries into their arena ranking, returning a new
+ * array of ids best-first. The input order is treated as the stable tie-break
+ * baseline (it is the wall's incoming "popular" order).
+ *
+ * @param {Array<{id:string, rep?:object}>} entries
+ * @returns {string[]} ids in ranked order
+ */
+export function rankArena(entries) {
+ return (entries || [])
+ .map((e, index) => ({ id: e.id, rep: e.rep, index }))
+ .sort(compareArenaEntries)
+ .map((e) => e.id);
+}
diff --git a/src/shared/mm-render.js b/src/shared/mm-render.js
index 68e7c0ef1..ee21e62fe 100644
--- a/src/shared/mm-render.js
+++ b/src/shared/mm-render.js
@@ -58,7 +58,7 @@ export function normalizeFloor({ floorSol, priceSol } = {}) {
export function fmtSizeSol(n) {
const v = finite(n);
if (v === 0) return '0';
- if (v >= 1) return v.toFixed(2);
+ if (v >= 0.1) return v.toFixed(2);
if (v >= 0.01) return v.toFixed(3);
return v.toFixed(4);
}
diff --git a/tests/a2a-hire-phases.test.js b/tests/a2a-hire-phases.test.js
new file mode 100644
index 000000000..a1bbc3e5e
--- /dev/null
+++ b/tests/a2a-hire-phases.test.js
@@ -0,0 +1,187 @@
+// Pure phase → render-payload mapping + cap math for the live a2a-hire visualizer.
+//
+// These are the load-bearing pure functions behind /api/agents/a2a-hire's screen
+// frames and the /agent-screen hire panel: get the cap math or the phase payload
+// wrong and the viewer sees a wrong price, a dead explorer link, or a coin that
+// fires before settlement. No I/O here — exactly what the unit tests pin.
+
+import { describe, it, expect } from 'vitest';
+import {
+ HIRE_PHASES,
+ HIRE_PHASE_INDEX,
+ HIRE_ERROR_PHASES,
+ explorerTxUrl,
+ fmtUsd,
+ hireCapMath,
+ hirePhaseFrame,
+} from '../api/_lib/a2a-hire-phases.js';
+
+describe('hireCapMath', () => {
+ it('is uncapped when no limits are set', () => {
+ const m = hireCapMath({ usd: 0.04 });
+ expect(m.overCap).toBe(false);
+ expect(m.perCallCap).toBe(null);
+ expect(m.dailyUsd).toBe(null);
+ expect(m.dailyRemainingBefore).toBe(null);
+ expect(m.dailyRemainingAfter).toBe(null);
+ expect(m.price).toBe(0.04);
+ });
+
+ it('flags over-cap when price exceeds the owner maxUsd', () => {
+ const m = hireCapMath({ usd: 0.12, maxUsd: 0.1 });
+ expect(m.overMax).toBe(true);
+ expect(m.overCap).toBe(true);
+ expect(m.perCallCap).toBe(0.1);
+ });
+
+ it('does not flag over-cap at exactly the cap (epsilon tolerant)', () => {
+ const m = hireCapMath({ usd: 0.1, maxUsd: 0.1 });
+ expect(m.overMax).toBe(false);
+ expect(m.overCap).toBe(false);
+ });
+
+ it('flags over per-tx limit independently of maxUsd', () => {
+ const m = hireCapMath({ usd: 0.5, perTxUsd: 0.25 });
+ expect(m.overPerTx).toBe(true);
+ expect(m.overCap).toBe(true);
+ expect(m.perCallCap).toBe(0.25);
+ });
+
+ it('uses the tighter of maxUsd and per-tx as the per-call cap', () => {
+ expect(hireCapMath({ usd: 0.01, maxUsd: 0.1, perTxUsd: 0.25 }).perCallCap).toBe(0.1);
+ expect(hireCapMath({ usd: 0.01, maxUsd: 0.5, perTxUsd: 0.25 }).perCallCap).toBe(0.25);
+ });
+
+ it('computes remaining daily headroom before and after the hire', () => {
+ const m = hireCapMath({ usd: 0.04, dailyUsd: 1.0, dailySpentUsd: 0.6 });
+ expect(m.dailyRemainingBefore).toBeCloseTo(0.4, 9);
+ expect(m.dailyRemainingAfter).toBeCloseTo(0.36, 9);
+ expect(m.overDaily).toBe(false);
+ });
+
+ it('flags over-daily when the hire would breach the rolling cap', () => {
+ const m = hireCapMath({ usd: 0.5, dailyUsd: 1.0, dailySpentUsd: 0.8 });
+ expect(m.overDaily).toBe(true);
+ expect(m.overCap).toBe(true);
+ // remaining never goes negative
+ expect(m.dailyRemainingAfter).toBe(0);
+ });
+
+ it('treats a non-finite price as zero rather than NaN', () => {
+ const m = hireCapMath({ usd: undefined, maxUsd: 0.1 });
+ expect(m.price).toBe(0);
+ expect(m.overCap).toBe(false);
+ });
+});
+
+describe('explorerTxUrl', () => {
+ it('builds a mainnet solscan link by default', () => {
+ expect(explorerTxUrl('SiG123')).toBe('https://solscan.io/tx/SiG123');
+ });
+ it('appends the devnet cluster when asked', () => {
+ expect(explorerTxUrl('SiG123', 'devnet')).toBe('https://solscan.io/tx/SiG123?cluster=devnet');
+ });
+ it('returns null for a missing signature so the UI shows pending', () => {
+ expect(explorerTxUrl(null)).toBe(null);
+ expect(explorerTxUrl('')).toBe(null);
+ expect(explorerTxUrl(undefined)).toBe(null);
+ });
+});
+
+describe('fmtUsd', () => {
+ it('renders whole-cent prices with two decimals', () => {
+ expect(fmtUsd(0.04)).toBe('0.04');
+ expect(fmtUsd(1)).toBe('1.00');
+ });
+ it('keeps sub-cent micro-prices from collapsing to 0.00', () => {
+ expect(fmtUsd(0.0004)).not.toBe('0.00');
+ });
+ it('is safe on non-finite input', () => {
+ expect(fmtUsd(undefined)).toBe('0.00');
+ expect(fmtUsd(NaN)).toBe('0.00');
+ });
+});
+
+describe('HIRE_PHASES ordering', () => {
+ it('orders running before settled (verify-then-settle: coin fires only on settle)', () => {
+ expect(HIRE_PHASE_INDEX.running).toBeLessThan(HIRE_PHASE_INDEX.settled);
+ });
+ it('ends at the on-chain receipt', () => {
+ expect(HIRE_PHASES[HIRE_PHASES.length - 1]).toBe('recorded');
+ });
+ it('keeps the client step list in sync (7 happy-path phases)', () => {
+ expect(HIRE_PHASES).toEqual(['discover', 'quote', 'reserved', 'running', 'settled', 'delivered', 'recorded']);
+ });
+});
+
+describe('hirePhaseFrame', () => {
+ const base = {
+ hireId: 'h1',
+ slug: 'forge_logo',
+ skill: 'Forge Logo',
+ providerName: 'AGENT-B',
+ providerId: 'p1',
+ hirerId: 'a1',
+ usd: 0.04,
+ maxUsd: 0.1,
+ network: 'mainnet',
+ };
+
+ it('tags every frame as an analysis frame carrying the a2a_hire sidecar', () => {
+ const f = hirePhaseFrame('quote', base);
+ expect(f.type).toBe('analysis');
+ expect(f.meta.kind).toBe('a2a_hire');
+ expect(f.meta.phase).toBe('quote');
+ expect(f.meta.phaseIndex).toBe(HIRE_PHASE_INDEX.quote);
+ expect(f.meta.ok).toBe(true);
+ expect(f.meta.usd).toBe(0.04);
+ expect(f.meta.maxUsd).toBe(0.1);
+ });
+
+ it('renders the quote line with provider, slug, price and cap', () => {
+ const f = hirePhaseFrame('quote', { ...base, cap: { perCallCap: 0.1 } });
+ expect(f.activity).toContain('AGENT-B');
+ expect(f.activity).toContain('forge_logo');
+ expect(f.activity).toContain('$0.04');
+ expect(f.activity).toContain('cap $0.10');
+ });
+
+ it('derives explorer links from real signatures only', () => {
+ const settled = hirePhaseFrame('settled', { ...base, txSig: 'PAYSIG' });
+ expect(settled.meta.txSig).toBe('PAYSIG');
+ expect(settled.meta.paymentExplorer).toBe('https://solscan.io/tx/PAYSIG');
+ // no invocation yet → no link
+ expect(settled.meta.invocationSig).toBe(null);
+ expect(settled.meta.invocationExplorer).toBe(null);
+
+ const recorded = hirePhaseFrame('recorded', { ...base, txSig: 'PAYSIG', invocationSig: 'INVSIG' });
+ expect(recorded.meta.invocationExplorer).toBe('https://solscan.io/tx/INVSIG');
+ expect(recorded.meta.paymentExplorer).toBe('https://solscan.io/tx/PAYSIG');
+ });
+
+ it('marks error phases not-ok and out of the happy-path index', () => {
+ expect(HIRE_ERROR_PHASES).toContain('over_cap');
+ const over = hirePhaseFrame('over_cap', { ...base, usd: 0.2, cap: { perCallCap: 0.1 } });
+ expect(over.meta.ok).toBe(false);
+ expect(over.meta.phaseIndex).toBe(-1);
+ expect(over.activity).toContain('exceed the cap');
+
+ const failed = hirePhaseFrame('failed', { ...base, error: 'upstream 500' });
+ expect(failed.meta.ok).toBe(false);
+ expect(failed.activity).toContain('no charge');
+ expect(failed.activity).toContain('upstream 500');
+ });
+
+ it('never charges narration on a settled coin without a real signature being present in meta', () => {
+ // The settled frame may be emitted before the sig propagates; meta keeps it
+ // null (renders "pending"), never a fabricated link.
+ const f = hirePhaseFrame('settled', { ...base, txSig: null });
+ expect(f.meta.paymentExplorer).toBe(null);
+ });
+
+ it('passes the cap object through to the badge payload', () => {
+ const cap = { perCallCap: 0.1, dailyUsd: 1, dailyRemaining: 0.6 };
+ const f = hirePhaseFrame('reserved', { ...base, cap });
+ expect(f.meta.cap).toEqual(cap);
+ });
+});
diff --git a/tests/a2a-hire-visualizer.test.js b/tests/a2a-hire-visualizer.test.js
new file mode 100644
index 000000000..802367d8d
--- /dev/null
+++ b/tests/a2a-hire-visualizer.test.js
@@ -0,0 +1,160 @@
+// @vitest-environment jsdom
+//
+// Render test for the live hire visualizer client (src/agent-screen-hire.js),
+// driven by the EXACT meta payloads the server emits (api/_lib/a2a-hire-phases.js
+// → hirePhaseFrame). This exercises the real client render path: quote card, the
+// cap badge, the step progression, the coin-transfer animation (which must fire
+// ONLY on a live settle), the provenance receipt with explorer links, the amber
+// over-cap card, and reconnect backfill re-sync without a coin re-fire.
+
+import { describe, it, expect, beforeEach } from 'vitest';
+import { createHireVisualizer } from '../src/agent-screen-hire.js';
+import { hirePhaseFrame } from '../api/_lib/a2a-hire-phases.js';
+
+const HIRE = {
+ hireId: 'h1',
+ slug: 'forge_logo',
+ skill: 'Forge Logo',
+ providerName: 'AGENT-B',
+ providerId: 'p1',
+ hirerId: 'a1',
+ hirerName: 'AGENT-A',
+ usd: 0.04,
+ maxUsd: 0.1,
+ network: 'mainnet',
+};
+
+// Server-side frame → the meta the client ingests.
+const metaFor = (phase, extra = {}) => hirePhaseFrame(phase, { ...HIRE, ...extra }).meta;
+
+let body;
+beforeEach(() => {
+ document.body.innerHTML = '<div id="host"></div>';
+ body = document.getElementById('host');
+});
+
+describe('createHireVisualizer', () => {
+ it('renders the idle empty state before any hire', () => {
+ createHireVisualizer(body);
+ const empty = body.querySelector('#asc-hire-empty');
+ expect(empty.hidden).toBe(false);
+ expect(empty.textContent).toMatch(/hires others/i);
+ });
+
+ it('renders the quote card with provider, slug, price and cap badge', () => {
+ const viz = createHireVisualizer(body);
+ viz.ingest(metaFor('quote', { cap: { perCallCap: 0.1, dailyUsd: 1, dailyRemaining: 1 } }));
+
+ expect(body.querySelector('#asc-hire-empty').hidden).toBe(true);
+ const quote = body.querySelector('.asc-hire-quote');
+ expect(quote).toBeTruthy();
+ expect(quote.textContent).toContain('AGENT-B');
+ expect(quote.textContent).toContain('forge_logo');
+ expect(quote.textContent).toContain('0.04');
+ // persistent cap badge
+ const cap = body.querySelector('#asc-hire-cap');
+ expect(cap.hidden).toBe(false);
+ expect(cap.textContent).toContain('0.10');
+ });
+
+ it('fires the coin animation only on a LIVE settle, once', () => {
+ const viz = createHireVisualizer(body);
+ viz.ingest(metaFor('quote'));
+ viz.ingest(metaFor('reserved', { cap: { perCallCap: 0.1, dailyUsd: 1, dailyRemaining: 0.96 } }));
+ viz.ingest(metaFor('running'));
+ // before settle: no flying coin
+ expect(body.querySelector('.asc-hire-coinrail.flying')).toBeFalsy();
+
+ viz.ingest(metaFor('settled', { txSig: 'PAYSIG' }), { live: true });
+ const rail = body.querySelector('.asc-hire-coinrail');
+ expect(rail.classList.contains('flying')).toBe(true);
+ expect(rail.classList.contains('settled')).toBe(true);
+ });
+
+ it('does NOT fire the coin on backfill (live: false) — that is history', () => {
+ const viz = createHireVisualizer(body);
+ // reconnect backfill replays straight to settled
+ viz.ingest(metaFor('settled', { txSig: 'PAYSIG' }), { live: false });
+ const rail = body.querySelector('.asc-hire-coinrail');
+ expect(rail.classList.contains('flying')).toBe(false);
+ // coin is parked at the provider instead
+ expect(rail.classList.contains('arrived')).toBe(true);
+ });
+
+ it('resolves the receipt with real explorer links to settlement + invocation', () => {
+ const viz = createHireVisualizer(body);
+ viz.ingest(metaFor('quote'));
+ viz.ingest(metaFor('settled', { txSig: 'PAYSIG' }), { live: true });
+ viz.ingest(metaFor('recorded', { txSig: 'PAYSIG', invocationSig: 'INVSIG', resultSummary: 'logo.svg ready' }));
+
+ const links = [...body.querySelectorAll('.asc-hire-receipt-links a')];
+ const hrefs = links.map((a) => a.getAttribute('href'));
+ expect(hrefs).toContain('https://solscan.io/tx/PAYSIG');
+ expect(hrefs).toContain('https://solscan.io/tx/INVSIG');
+ // external links open safely
+ links.forEach((a) => {
+ expect(a.getAttribute('target')).toBe('_blank');
+ expect(a.getAttribute('rel')).toBe('noopener');
+ });
+ expect(body.querySelector('.asc-hire-receipt').textContent).toContain('logo.svg ready');
+ });
+
+ it('shows the settlement link as pending when no signature is present', () => {
+ const viz = createHireVisualizer(body);
+ viz.ingest(metaFor('settled', { txSig: null }), { live: true });
+ const pending = body.querySelector('.asc-hire-link.pending');
+ expect(pending).toBeTruthy();
+ expect(pending.textContent.toLowerCase()).toContain('pending');
+ // no fabricated link
+ expect(body.querySelector('.asc-hire-receipt-links a[href*="solscan"]')).toBeFalsy();
+ });
+
+ it('renders an amber over-cap card instead of crashing or spending', () => {
+ const viz = createHireVisualizer(body);
+ viz.ingest(metaFor('over_cap', { usd: 0.2, cap: { perCallCap: 0.1 } }));
+ const amber = body.querySelector('.asc-hire-result.amber');
+ expect(amber).toBeTruthy();
+ expect(amber.textContent.toLowerCase()).toContain('cap');
+ // no coin rail in an over-cap render
+ expect(body.querySelector('.asc-hire-coinrail')).toBeFalsy();
+ });
+
+ it('renders a red no-charge card on a failed skill', () => {
+ const viz = createHireVisualizer(body);
+ viz.ingest(metaFor('quote'));
+ viz.ingest(metaFor('failed', { error: 'upstream 500' }));
+ const red = body.querySelector('.asc-hire-result.red');
+ expect(red).toBeTruthy();
+ expect(red.textContent.toLowerCase()).toContain('no charge');
+ });
+
+ it('calls onSettled once with the hire meta on a live settle', () => {
+ const seen = [];
+ const viz = createHireVisualizer(body, { onSettled: (m) => seen.push(m) });
+ viz.ingest(metaFor('quote'));
+ viz.ingest(metaFor('settled', { txSig: 'PAYSIG' }), { live: true });
+ expect(seen.length).toBe(1);
+ expect(seen[0].providerName).toBe('AGENT-B');
+ expect(seen[0].usd).toBe(0.04);
+ });
+
+ it('archives a finished hire into the history strip when a new hire starts', () => {
+ const viz = createHireVisualizer(body);
+ viz.ingest(metaFor('recorded', { txSig: 'P1', invocationSig: 'I1' }));
+ // a different hire begins
+ viz.ingest(metaFor('quote', { hireId: 'h2', providerName: 'AGENT-C', slug: 'transcribe' }));
+ const rows = body.querySelectorAll('.asc-hire-hrow');
+ expect(rows.length).toBe(1);
+ expect(rows[0].textContent).toContain('AGENT-B');
+ });
+
+ it('drops stale out-of-order happy-path frames for the active hire', () => {
+ const viz = createHireVisualizer(body);
+ viz.ingest(metaFor('recorded', { txSig: 'P1', invocationSig: 'I1' }));
+ // a late-arriving 'running' frame for the same hire must not regress the UI
+ viz.ingest(metaFor('running'));
+ // still shows the resolved receipt, not the running spinner
+ expect(body.querySelector('.asc-hire-receipt.resolved')).toBeTruthy();
+ expect(body.querySelector('.asc-hire-running')).toBeFalsy();
+ });
+});
diff --git a/tests/agent-memory-graph.test.js b/tests/agent-memory-graph.test.js
new file mode 100644
index 000000000..16ddcfb28
--- /dev/null
+++ b/tests/agent-memory-graph.test.js
@@ -0,0 +1,187 @@
+/**
+ * Agent Memory Diary — pure layout/ranking + digest-shaping unit tests.
+ *
+ * Covers the deterministic math behind the Diary's memory graph and the
+ * shaping the reflection digest relies on (counts, entity dedupe/ranking, link
+ * mapping). The canvas renderer (AgentMemoryGraph) is intentionally NOT
+ * constructed here — it needs a DOM; these tests exercise only the pure
+ * functions it and api/agent-reflect-digest.js share.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ rankByMentions,
+ entityHref,
+ shapeDigestEntities,
+ digestCounts,
+ layoutGraph,
+ ENTITY_KINDS,
+} from '../src/agent-memory-graph.js';
+
+describe('rankByMentions', () => {
+ it('orders by mentions desc, then salience, then label — deterministically', () => {
+ const nodes = [
+ { id: 'a', label: 'Bravo', mentions: 2, salience: 0.5 },
+ { id: 'b', label: 'Alpha', mentions: 5, salience: 0.2 },
+ { id: 'c', label: 'Charlie', mentions: 2, salience: 0.9 },
+ ];
+ const ranked = rankByMentions(nodes).map((n) => n.id);
+ // b (5) first; then the two 2-mention nodes by salience: c (0.9) > a (0.5).
+ expect(ranked).toEqual(['b', 'c', 'a']);
+ });
+
+ it('breaks full ties by label so the order is stable across renders', () => {
+ const nodes = [
+ { id: '1', label: 'Zeta', mentions: 3, salience: 0.5 },
+ { id: '2', label: 'Apple', mentions: 3, salience: 0.5 },
+ ];
+ expect(rankByMentions(nodes).map((n) => n.label)).toEqual(['Apple', 'Zeta']);
+ });
+
+ it('drops entries without an id and never mutates the input', () => {
+ const input = [{ id: 'x', mentions: 1 }, { mentions: 9 }, null];
+ const out = rankByMentions(input);
+ expect(out.map((n) => n.id)).toEqual(['x']);
+ expect(input.length).toBe(3); // untouched
+ });
+
+ it('handles empty / nullish input', () => {
+ expect(rankByMentions()).toEqual([]);
+ expect(rankByMentions(null)).toEqual([]);
+ });
+});
+
+describe('entityHref', () => {
+ it('maps a mint to its addressable launch page (URL-encoded)', () => {
+ const href = entityHref({ kind: 'mint', normalized: 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump' });
+ expect(href).toBe('/launches/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump');
+ });
+
+ it('falls back to the label when a mint has no normalized form', () => {
+ expect(entityHref({ kind: 'mint', label: 'So 11111' })).toBe('/launches/So%2011111');
+ });
+
+ it('resolves a person to an agent screen via a Map index', () => {
+ const idx = new Map([['kestrel', 'agent-123']]);
+ expect(entityHref({ kind: 'person', label: 'Kestrel' }, idx)).toBe('/agent-screen?agentId=agent-123');
+ });
+
+ it('resolves via a plain-object index too', () => {
+ expect(entityHref({ kind: 'agent', label: 'Nova' }, { nova: 'a-9' })).toBe('/agent-screen?agentId=a-9');
+ });
+
+ it('returns null for an unresolved person and for non-addressable kinds', () => {
+ expect(entityHref({ kind: 'person', label: 'Ghost' }, new Map())).toBeNull();
+ expect(entityHref({ kind: 'topic', label: 'settlement' })).toBeNull();
+ expect(entityHref({ kind: 'wallet', label: 'abc' })).toBeNull();
+ expect(entityHref(null)).toBeNull();
+ });
+});
+
+describe('shapeDigestEntities', () => {
+ it('ranks, dedupes by id, caps to topN, and attaches resolved hrefs', () => {
+ const nodes = [
+ { id: 'm1', kind: 'mint', normalized: 'MINT1', label: '$THREE', mentions: 9 },
+ { id: 'm1', kind: 'mint', normalized: 'MINT1', label: '$THREE', mentions: 9 }, // dup id
+ { id: 'p1', kind: 'person', label: 'Kestrel', mentions: 4 },
+ { id: 't1', kind: 'topic', label: 'liquidity', mentions: 1 },
+ ];
+ const out = shapeDigestEntities(nodes, { topN: 2, agentIndex: new Map([['kestrel', 'ag-1']]) });
+ expect(out).toHaveLength(2);
+ expect(out[0]).toMatchObject({ id: 'm1', mentions: 9, href: '/launches/MINT1' });
+ expect(out[1]).toMatchObject({ id: 'p1', href: '/agent-screen?agentId=ag-1' });
+ });
+
+ it('normalizes unknown kinds and truncates very long labels', () => {
+ const long = 'x'.repeat(200);
+ const [e] = shapeDigestEntities([{ id: 'z', kind: 'weird', label: long, mentions: 1 }]);
+ expect(ENTITY_KINDS.includes(e.kind) || e.kind === 'weird').toBe(true);
+ expect(e.label.length).toBeLessThanOrEqual(80);
+ expect(e.href).toBeNull();
+ });
+});
+
+describe('digestCounts', () => {
+ it('derives learned/decided/interacted strictly from the rows', () => {
+ const memories = [
+ { tags: ['decision'] },
+ { tags: [], context: { kind: 'decision' } },
+ { tags: ['note'] },
+ ];
+ const entities = [
+ { kind: 'person' }, { kind: 'agent' }, { kind: 'mint' }, { kind: 'topic' },
+ ];
+ expect(digestCounts(memories, entities)).toEqual({ learned: 3, decided: 2, interacted: 2 });
+ });
+
+ it('is honest about zero — no decisions, no people', () => {
+ expect(digestCounts([{ tags: [] }], [{ kind: 'mint' }])).toEqual({ learned: 1, decided: 0, interacted: 0 });
+ expect(digestCounts([], [])).toEqual({ learned: 0, decided: 0, interacted: 0 });
+ });
+
+ it('matches the "decided" tag case-insensitively', () => {
+ expect(digestCounts([{ tags: ['Decided'] }], []).decided).toBe(1);
+ });
+});
+
+describe('layoutGraph', () => {
+ const W = 320, H = 220;
+
+ it('returns nothing for an empty graph', () => {
+ expect(layoutGraph([], [], { width: W, height: H })).toEqual([]);
+ });
+
+ it('centres the single most-mentioned node and makes it the brightest', () => {
+ const nodes = [
+ { id: 'top', label: 'A', mentions: 10 },
+ { id: 'b', label: 'B', mentions: 1 },
+ { id: 'c', label: 'C', mentions: 1 },
+ ];
+ const out = layoutGraph(nodes, [], { width: W, height: H });
+ const top = out.find((n) => n.id === 'top');
+ expect(top.x).toBeCloseTo(W / 2, 5);
+ expect(top.y).toBeCloseTo(H / 2, 5);
+ expect(top.brightness).toBe(1);
+ // Brightest of all.
+ expect(Math.max(...out.map((n) => n.brightness))).toBe(top.brightness);
+ });
+
+ it('keeps every node inside the padded bounds', () => {
+ const nodes = Array.from({ length: 20 }, (_, i) => ({ id: `n${i}`, label: `n${i}`, mentions: 20 - i }));
+ const out = layoutGraph(nodes, [], { width: W, height: H, padding: 24 });
+ for (const n of out) {
+ expect(n.x).toBeGreaterThanOrEqual(24);
+ expect(n.x).toBeLessThanOrEqual(W - 24);
+ expect(n.y).toBeGreaterThanOrEqual(24);
+ expect(n.y).toBeLessThanOrEqual(H - 24);
+ }
+ });
+
+ it('caps the laid-out node count at maxNodes', () => {
+ const nodes = Array.from({ length: 100 }, (_, i) => ({ id: `n${i}`, label: `n${i}`, mentions: 100 - i }));
+ const out = layoutGraph(nodes, [], { width: W, height: H, maxNodes: 12 });
+ expect(out).toHaveLength(12);
+ });
+
+ it('is deterministic — identical input yields identical positions', () => {
+ const nodes = [
+ { id: 'a', label: 'A', mentions: 5 },
+ { id: 'b', label: 'B', mentions: 3 },
+ { id: 'c', label: 'C', mentions: 2 },
+ ];
+ const a = layoutGraph(nodes, [], { width: W, height: H });
+ const b = layoutGraph(nodes, [], { width: W, height: H });
+ expect(a).toEqual(b);
+ });
+
+ it('scales node radius with mention share', () => {
+ const nodes = [
+ { id: 'big', label: 'big', mentions: 10 },
+ { id: 'small', label: 'small', mentions: 1 },
+ ];
+ const out = layoutGraph(nodes, [], { width: W, height: H });
+ const big = out.find((n) => n.id === 'big');
+ const small = out.find((n) => n.id === 'small');
+ expect(big.r).toBeGreaterThan(small.r);
+ });
+});
diff --git a/tests/agent-mm-render.test.js b/tests/agent-mm-render.test.js
new file mode 100644
index 000000000..6da89345d
--- /dev/null
+++ b/tests/agent-mm-render.test.js
@@ -0,0 +1,174 @@
+import { describe, it, expect } from 'vitest';
+import {
+ mmActionType,
+ isFiredKind,
+ normalizeFloor,
+ fmtSizeSol,
+ fmtPriceSol,
+ mmSummary,
+ mmEventFromOutcome,
+ sanitizeMmEvent,
+ MM_ACTION_TYPES,
+} from '../src/shared/mm-render.js';
+
+describe('mmActionType — engine kind → screen action_type', () => {
+ it('maps every fired kind to its action_type', () => {
+ expect(mmActionType('seed')).toBe('mm_seed');
+ expect(mmActionType('defend_buy')).toBe('mm_defend');
+ expect(mmActionType('recycle_sell')).toBe('mm_recycle');
+ expect(mmActionType('rebalance_trim')).toBe('mm_rebalance');
+ expect(mmActionType('graduation_lp')).toBe('mm_graduate');
+ expect(mmActionType('graduation_distribute')).toBe('mm_graduate');
+ expect(mmActionType('graduation_hold')).toBe('mm_quote');
+ });
+
+ it('falls back to mm_quote for non-firing / unknown tags', () => {
+ for (const t of ['in_band', 'interval_guard', 'daily_budget', 'no_price', 'no_wallet', 'anything']) {
+ expect(mmActionType(t)).toBe('mm_quote');
+ }
+ });
+
+ it('only ever emits known action_types', () => {
+ const tags = ['seed', 'defend_buy', 'recycle_sell', 'rebalance_trim', 'graduation_lp', 'graduation_distribute', 'graduation_hold', 'in_band'];
+ for (const t of tags) expect(MM_ACTION_TYPES).toContain(mmActionType(t));
+ });
+});
+
+describe('isFiredKind — real fill vs quote/guard', () => {
+ it('treats real fills as fired', () => {
+ for (const k of ['seed', 'defend_buy', 'recycle_sell', 'rebalance_trim', 'graduation_lp', 'graduation_distribute']) {
+ expect(isFiredKind(k)).toBe(true);
+ }
+ });
+ it('treats quotes / holds / guards as not fired', () => {
+ for (const k of ['graduation_hold', 'in_band', 'interval_guard', 'no_price', 'no_wallet', undefined, null]) {
+ expect(isFiredKind(k)).toBe(false);
+ }
+ });
+});
+
+describe('normalizeFloor — render-safe SOL units', () => {
+ it('passes finite non-negative numbers through', () => {
+ expect(normalizeFloor({ floorSol: 0.0000142, priceSol: 0.0000151 })).toEqual({ floorSol: 0.0000142, priceSol: 0.0000151 });
+ });
+ it('clamps NaN / negative / missing / string to 0', () => {
+ expect(normalizeFloor({ floorSol: NaN, priceSol: -1 })).toEqual({ floorSol: 0, priceSol: 0 });
+ expect(normalizeFloor({})).toEqual({ floorSol: 0, priceSol: 0 });
+ expect(normalizeFloor()).toEqual({ floorSol: 0, priceSol: 0 });
+ expect(normalizeFloor({ floorSol: 'abc', priceSol: Infinity })).toEqual({ floorSol: 0, priceSol: 0 });
+ });
+ it('coerces numeric strings', () => {
+ expect(normalizeFloor({ floorSol: '0.5', priceSol: '0.75' })).toEqual({ floorSol: 0.5, priceSol: 0.75 });
+ });
+});
+
+describe('formatting', () => {
+ it('fmtSizeSol adapts precision by magnitude', () => {
+ expect(fmtSizeSol(0.4)).toBe('0.40');
+ expect(fmtSizeSol(1.5)).toBe('1.50');
+ expect(fmtSizeSol(0.024)).toBe('0.024');
+ expect(fmtSizeSol(0.0015)).toBe('0.0015');
+ expect(fmtSizeSol(0)).toBe('0');
+ expect(fmtSizeSol(NaN)).toBe('0');
+ });
+ it('fmtPriceSol keeps ~3 significant figures on tiny prices', () => {
+ expect(fmtPriceSol(0.0000142)).toBe('0.0000142');
+ expect(fmtPriceSol(0)).toBe('0');
+ expect(fmtPriceSol(1.42)).toBe('1.4200');
+ // no NaN / exponent leaks into a holder-facing string
+ expect(fmtPriceSol(-5)).toBe('0');
+ });
+});
+
+describe('mmSummary — holder-readable lines', () => {
+ it('writes the canonical defend line', () => {
+ expect(mmSummary({ actionType: 'mm_defend', sizeSol: 0.4, priceSol: 0.0000142 }))
+ .toBe('Defended floor: bought 0.40 SOL at 0.0000142');
+ });
+ it('tags simulate fills', () => {
+ expect(mmSummary({ actionType: 'mm_defend', sizeSol: 0.4, priceSol: 0.0000142, simulate: true }))
+ .toBe('Defended floor: bought 0.40 SOL at 0.0000142 (sim)');
+ });
+ it('covers every action_type', () => {
+ for (const t of MM_ACTION_TYPES) {
+ const s = mmSummary({ actionType: t, sizeSol: 0.4, priceSol: 0.00001, floorSol: 0.00001 });
+ expect(typeof s).toBe('string');
+ expect(s.length).toBeGreaterThan(0);
+ }
+ });
+});
+
+describe('mmEventFromOutcome — outcome → persisted/published event', () => {
+ const baseOutcome = {
+ tag: 'defend_buy',
+ mint: 'THREEsynthetic1111111111111111111111111111111',
+ floorSol: 0.0000142,
+ priceSol: 0.0000138,
+ sizeSol: 0.4,
+ sideBuy: true,
+ signature: 'sig_live_abc',
+ simulate: false,
+ };
+
+ it('builds the full event with normalized context', () => {
+ const ev = mmEventFromOutcome(baseOutcome);
+ expect(ev.actionType).toBe('mm_defend');
+ expect(ev.summary).toBe('Defended floor: bought 0.40 SOL at 0.0000138');
+ expect(ev.context).toEqual({
+ mint: 'THREEsynthetic1111111111111111111111111111111',
+ floorSol: 0.0000142,
+ priceSol: 0.0000138,
+ sizeSol: 0.4,
+ sideBuy: true,
+ simulate: false,
+ signature: 'sig_live_abc',
+ });
+ });
+
+ it('drops the SIMULATED sentinel signature and tags the summary', () => {
+ const ev = mmEventFromOutcome({ ...baseOutcome, signature: 'SIMULATED', simulate: true });
+ expect(ev.context.signature).toBeNull();
+ expect(ev.context.simulate).toBe(true);
+ expect(ev.summary.endsWith('(sim)')).toBe(true);
+ });
+
+ it('normalizes garbage numbers + non-string mint without throwing', () => {
+ const ev = mmEventFromOutcome({ tag: 'in_band', mint: 12345, floorSol: NaN, priceSol: -2, sizeSol: 'x' });
+ expect(ev.actionType).toBe('mm_quote');
+ expect(ev.context.mint).toBeNull();
+ expect(ev.context.floorSol).toBe(0);
+ expect(ev.context.priceSol).toBe(0);
+ expect(ev.context.sizeSol).toBe(0);
+ expect(ev.context.sideBuy).toBeNull();
+ });
+
+ it('handles an empty outcome', () => {
+ const ev = mmEventFromOutcome();
+ expect(ev.actionType).toBe('mm_quote');
+ expect(ev.context.floorSol).toBe(0);
+ });
+});
+
+describe('sanitizeMmEvent — inbound ride-along whitelist', () => {
+ it('round-trips a clean event', () => {
+ const out = sanitizeMmEvent({ type: 'mm_defend', floorSol: 0.01, priceSol: 0.009, sizeSol: 0.5, sideBuy: true, simulate: false, mint: 'm', signature: 's' });
+ expect(out).toEqual({ type: 'mm_defend', floorSol: 0.01, priceSol: 0.009, sizeSol: 0.5, sideBuy: true, simulate: false, mint: 'm', signature: 's' });
+ });
+ it('defaults an unknown type to mm_quote and clamps numbers', () => {
+ const out = sanitizeMmEvent({ type: 'evil', floorSol: -1, priceSol: NaN, sizeSol: 9 });
+ expect(out.type).toBe('mm_quote');
+ expect(out.floorSol).toBe(0);
+ expect(out.priceSol).toBe(0);
+ expect(out.sizeSol).toBe(9);
+ });
+ it('rejects unusable payloads', () => {
+ expect(sanitizeMmEvent(null)).toBeNull();
+ expect(sanitizeMmEvent('nope')).toBeNull();
+ expect(sanitizeMmEvent(42)).toBeNull();
+ });
+ it('bounds long strings', () => {
+ const out = sanitizeMmEvent({ type: 'mm_quote', mint: 'x'.repeat(200), signature: 'y'.repeat(200) });
+ expect(out.mint.length).toBe(64);
+ expect(out.signature.length).toBe(96);
+ });
+});
diff --git a/tests/agent-orchestrate.test.js b/tests/agent-orchestrate.test.js
index f94fddc0c..f91b450b7 100644
--- a/tests/agent-orchestrate.test.js
+++ b/tests/agent-orchestrate.test.js
@@ -155,7 +155,7 @@ describe('narrateNode', () => {
const line = narrateNode({ kind: 'hire', title: 'sentiment scan', status: 'done', costUsd: 0.02, signature: '5xRabcdefghijk' });
expect(line).toMatch(/Hired/);
expect(line).toMatch(/\$0\.02/);
- expect(line).toMatch(/5xRabcde/);
+ expect(line).toMatch(/5xRabcd/);
});
it('narrates a failed hire with the reason', () => {
diff --git a/tests/agent-team-boot.test.js b/tests/agent-team-boot.test.js
new file mode 100644
index 000000000..e08fea9d9
--- /dev/null
+++ b/tests/agent-team-boot.test.js
@@ -0,0 +1,33 @@
+// @vitest-environment jsdom
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+describe('agent-team.js boot wiring', () => {
+ beforeEach(() => {
+ vi.resetModules();
+ document.head.innerHTML = '';
+ document.body.innerHTML = '';
+ });
+
+ it('injects the Team Task launcher into the live-wall hero', async () => {
+ document.body.innerHTML = `<main><div class="al-hero"><h1>Watch agents work</h1></div><div id="al-grid"></div></main>`;
+ await import('../src/agent-team.js');
+ const btn = document.querySelector('.al-hero .tt-launch');
+ expect(btn).toBeTruthy();
+ expect(btn.textContent).toMatch(/Team Task/);
+ expect(document.getElementById('tt-styles')).toBeTruthy();
+ });
+
+ it('adds a Team toggle to the agent-screen task bar', async () => {
+ // agent-screen reads ?agentId from the URL.
+ const url = new URL('http://localhost/agent-screen?agentId=abc-123');
+ history.replaceState({}, '', url.pathname + url.search);
+ document.body.innerHTML = `
+ <form id="asc-task-form"><input id="asc-task-input" placeholder="task…"><button id="asc-task-send" type="submit">go</button></form>`;
+ await import('../src/agent-team.js');
+ const toggle = document.querySelector('.tt-toggle');
+ expect(toggle).toBeTruthy();
+ expect(toggle.getAttribute('aria-pressed')).toBe('false');
+ toggle.click();
+ expect(toggle.getAttribute('aria-pressed')).toBe('true');
+ });
+});
diff --git a/tests/arena-rank.test.js b/tests/arena-rank.test.js
new file mode 100644
index 000000000..2021dbfcf
--- /dev/null
+++ b/tests/arena-rank.test.js
@@ -0,0 +1,90 @@
+/**
+ * Reputation Arena ordering — unit tests for src/shared/arena-rank.js.
+ *
+ * The wall's ranked order is a pure function of each agent's compact reputation,
+ * so it can be proven here without a browser: rated agents outrank new ones,
+ * new outrank unknown, higher scores win, and equal scores keep their incoming
+ * (popular) order via a stable tie-break.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ arenaScore,
+ compareArenaEntries,
+ rankArena,
+ ARENA_SCORE_NEW,
+ ARENA_SCORE_UNKNOWN,
+ TIER_RANK,
+} from '../src/shared/arena-rank.js';
+
+describe('arenaScore', () => {
+ it('returns the trust score for a rated agent', () => {
+ expect(arenaScore({ score: 72, tier: 'trusted' })).toBe(72);
+ expect(arenaScore({ score: 0, tier: 'emerging' })).toBe(0);
+ });
+
+ it('sinks a brand-new agent below every real score', () => {
+ expect(arenaScore({ isNew: true, score: 0 })).toBe(ARENA_SCORE_NEW);
+ expect(ARENA_SCORE_NEW).toBeLessThan(0);
+ });
+
+ it('sinks an agent with no loaded reputation to the bottom', () => {
+ expect(arenaScore(null)).toBe(ARENA_SCORE_UNKNOWN);
+ expect(arenaScore(undefined)).toBe(ARENA_SCORE_UNKNOWN);
+ expect(arenaScore({})).toBe(ARENA_SCORE_UNKNOWN); // no score, not new
+ });
+
+ it('new ranks above unknown', () => {
+ expect(ARENA_SCORE_NEW).toBeGreaterThan(ARENA_SCORE_UNKNOWN);
+ });
+
+ it('treats a non-finite score as unknown, not zero', () => {
+ expect(arenaScore({ score: NaN })).toBe(ARENA_SCORE_UNKNOWN);
+ expect(arenaScore({ score: 'oops' })).toBe(ARENA_SCORE_UNKNOWN);
+ });
+});
+
+describe('compareArenaEntries', () => {
+ it('orders by score, highest first', () => {
+ const a = { rep: { score: 40 }, index: 0 };
+ const b = { rep: { score: 90 }, index: 1 };
+ expect(compareArenaEntries(a, b)).toBeGreaterThan(0); // b before a
+ expect(compareArenaEntries(b, a)).toBeLessThan(0);
+ });
+
+ it('breaks an exact score tie by tier rank, then original order', () => {
+ const elite = { rep: { score: 60, tier: 'elite' }, index: 5 };
+ const established = { rep: { score: 60, tier: 'established' }, index: 1 };
+ expect(compareArenaEntries(elite, established)).toBeLessThan(0); // elite first
+ expect(TIER_RANK.elite).toBeGreaterThan(TIER_RANK.established);
+ });
+
+ it('keeps incoming order when score and tier match (stable)', () => {
+ const first = { rep: { score: 50, tier: 'emerging' }, index: 2 };
+ const second = { rep: { score: 50, tier: 'emerging' }, index: 7 };
+ expect(compareArenaEntries(first, second)).toBeLessThan(0); // lower index first
+ });
+});
+
+describe('rankArena', () => {
+ it('produces the full honest ordering: rated → new → unknown', () => {
+ const entries = [
+ { id: 'unknown', rep: null },
+ { id: 'new', rep: { isNew: true } },
+ { id: 'mid', rep: { score: 55, tier: 'trusted' } },
+ { id: 'top', rep: { score: 91, tier: 'elite' } },
+ { id: 'low', rep: { score: 12, tier: 'emerging' } },
+ ];
+ expect(rankArena(entries)).toEqual(['top', 'mid', 'low', 'new', 'unknown']);
+ });
+
+ it('is stable for an all-equal wall (no spurious reorder)', () => {
+ const entries = ['a', 'b', 'c', 'd'].map((id) => ({ id, rep: { score: 50, tier: 'emerging' } }));
+ expect(rankArena(entries)).toEqual(['a', 'b', 'c', 'd']);
+ });
+
+ it('handles an empty wall', () => {
+ expect(rankArena([])).toEqual([]);
+ expect(rankArena(undefined)).toEqual([]);
+ });
+});
diff --git a/tests/pnl-snapshot.test.js b/tests/pnl-snapshot.test.js
new file mode 100644
index 000000000..5669b3d2b
--- /dev/null
+++ b/tests/pnl-snapshot.test.js
@@ -0,0 +1,287 @@
+import { describe, it, expect } from 'vitest';
+import {
+ toPnlSnapshot,
+ emptyPnlSnapshot,
+ mergePortfolioOver,
+ buildSparkline,
+ formatPnl,
+ formatUsd,
+ formatSol,
+ formatAmount,
+ THREE_MINT,
+ THREE_COIN_URL,
+} from '../src/shared/pnl-snapshot.js';
+
+// ── fixtures ──────────────────────────────────────────────────────────────────
+// A balances entry: net worth $1000, SOL $400 @ $200/SOL, $THREE $250 (NOT in
+// topHoldings, to prove it still gets pinned), plus two other SPL holdings.
+const BALANCES = {
+ agentId: 'a1',
+ address: 'Wa11etAddr1111111111111111111111111111111',
+ isOwner: false,
+ usd: 1000,
+ sol: { amount: 2, usd: 400, price: 200 },
+ usdc: { amount: 100, usd: 100 },
+ three: { amount: 5_000_000, usd: 250, price: 0.00005 },
+ tokenCount: 4,
+ topHoldings: [
+ { mint: 'MintAAA', symbol: 'AAA', amount: 1000, usd: 200, price: 0.2, logo: 'http://x/a.png' },
+ { mint: 'MintBBB', symbol: 'BBB', amount: 500, usd: 150, price: 0.3, logo: null },
+ ],
+ pnl: { sparkline: [900, 950, 1000], changePct: 11.11, changeUsd: 100, windowHours: 24 },
+};
+
+// A balances entry where $THREE DID rank into topHoldings — must not duplicate.
+const BALANCES_THREE_RANKED = {
+ agentId: 'a2',
+ address: 'Wa11etAddr2222222222222222222222222222222',
+ isOwner: true,
+ usd: 500,
+ sol: { amount: 1, usd: 200, price: 200 },
+ usdc: { amount: 0, usd: 0 },
+ three: { amount: 9_000_000, usd: 300, price: 0.0000333 },
+ tokenCount: 2,
+ topHoldings: [
+ { mint: THREE_MINT, symbol: '$THREE', amount: 9_000_000, usd: 300, price: 0.0000333, logo: null },
+ ],
+ pnl: { sparkline: [], changePct: null, changeUsd: null, windowHours: null },
+};
+
+// An owner portfolio snapshot (different shape: net_worth + holdings + is_three).
+const PORTFOLIO = {
+ agent: { wallet: 'Wa11etAddr1111111111111111111111111111111' },
+ sol_usd: 200,
+ net_worth: { sol: 5, usd: 1000, realized_pnl_usd: 12 },
+ holdings: [
+ { isNative: true, symbol: 'SOL', amount: 2, usd: 400, usd_value: 400 },
+ { mint: THREE_MINT, symbol: '$THREE', amount: 5_000_000, usd_value: 250, is_three: true, unrealized_pct: 18.5 },
+ { mint: 'MintAAA', symbol: 'AAA', amount: 1000, usd_value: 350, unrealized_pct: -4.2 },
+ ],
+};
+
+describe('toPnlSnapshot — balances shape', () => {
+ const snap = toPnlSnapshot(BALANCES);
+
+ it('marks it priced from the balances source', () => {
+ expect(snap.priced).toBe(true);
+ expect(snap.source).toBe('balances');
+ expect(snap.address).toBe(BALANCES.address);
+ });
+
+ it('reports net worth in USD and derives SOL via the SOL price', () => {
+ expect(snap.netWorthUsd).toBe(1000);
+ expect(snap.netWorthSol).toBeCloseTo(5, 6); // 1000 / 200
+ });
+
+ it('carries the real 24h change + sparkline', () => {
+ expect(snap.change24hPct).toBeCloseTo(11.11, 2);
+ expect(snap.change24hUsd).toBe(100);
+ expect(snap.windowHours).toBe(24);
+ expect(snap.sparkline).toEqual([900, 950, 1000]);
+ });
+
+ it('pins $THREE first even when it is absent from topHoldings', () => {
+ expect(snap.hasThree).toBe(true);
+ expect(snap.holdings[0].isThree).toBe(true);
+ expect(snap.holdings[0].mint).toBe(THREE_MINT);
+ // Only one $THREE row.
+ expect(snap.holdings.filter((h) => h.isThree)).toHaveLength(1);
+ });
+
+ it('ranks the remaining holdings by USD value, $THREE excluded from that order', () => {
+ const after = snap.holdings.filter((h) => !h.isThree).map((h) => h.symbol);
+ // SOL ($400) > AAA ($200) > BBB ($150)
+ expect(after).toEqual(['SOL', 'AAA', 'BBB']);
+ });
+
+ it('computes each holding share of net worth', () => {
+ const three = snap.holdings.find((h) => h.isThree);
+ expect(three.pct).toBeCloseTo(25, 1); // 250 / 1000
+ const sol = snap.holdings.find((h) => h.symbol === 'SOL');
+ expect(sol.pct).toBeCloseTo(40, 1);
+ });
+});
+
+describe('toPnlSnapshot — $THREE already ranked', () => {
+ it('does not duplicate $THREE when it is in topHoldings', () => {
+ const snap = toPnlSnapshot(BALANCES_THREE_RANKED);
+ expect(snap.holdings.filter((h) => h.isThree)).toHaveLength(1);
+ expect(snap.holdings[0].isThree).toBe(true);
+ expect(snap.isOwner).toBe(true);
+ });
+});
+
+describe('toPnlSnapshot — portfolio shape', () => {
+ const snap = toPnlSnapshot(PORTFOLIO);
+
+ it('detects the portfolio source and is owner by construction', () => {
+ expect(snap.source).toBe('portfolio');
+ expect(snap.isOwner).toBe(true);
+ expect(snap.priced).toBe(true);
+ });
+
+ it('takes net worth straight from net_worth', () => {
+ expect(snap.netWorthUsd).toBe(1000);
+ expect(snap.netWorthSol).toBe(5);
+ });
+
+ it('has no 24h change or sparkline (the stream does not carry them)', () => {
+ expect(snap.change24hPct).toBeNull();
+ expect(snap.sparkline).toEqual([]);
+ });
+
+ it('pins $THREE and surfaces per-holding unrealized P&L', () => {
+ expect(snap.holdings[0].isThree).toBe(true);
+ expect(snap.holdings[0].unrealizedPct).toBe(18.5);
+ const aaa = snap.holdings.find((h) => h.symbol === 'AAA');
+ expect(aaa.unrealizedPct).toBe(-4.2);
+ });
+});
+
+describe('toPnlSnapshot — misses & junk', () => {
+ it('maps the explicit unpriced miss to an empty snapshot keeping the address', () => {
+ const snap = toPnlSnapshot({ agentId: 'x', address: 'AddrX', isOwner: true, usd: null, priced: false });
+ expect(snap.priced).toBe(false);
+ expect(snap.address).toBe('AddrX');
+ expect(snap.isOwner).toBe(true);
+ expect(snap.holdings).toEqual([]);
+ });
+
+ it('returns an empty snapshot for null / non-object input rather than throwing', () => {
+ expect(toPnlSnapshot(null).priced).toBe(false);
+ expect(toPnlSnapshot(undefined).priced).toBe(false);
+ expect(toPnlSnapshot(42).priced).toBe(false);
+ });
+
+ it('emptyPnlSnapshot is a stable un-priced shape', () => {
+ const e = emptyPnlSnapshot();
+ expect(e.priced).toBe(false);
+ expect(e.sparkline).toEqual([]);
+ expect(e.holdings).toEqual([]);
+ expect(e.hasThree).toBe(false);
+ });
+});
+
+describe('mergePortfolioOver', () => {
+ it('keeps the balances 24h + sparkline but takes the fresher portfolio body', () => {
+ const base = toPnlSnapshot(BALANCES); // has 24h + sparkline
+ const live = toPnlSnapshot({ ...PORTFOLIO, net_worth: { sol: 6, usd: 1200 } });
+ const merged = mergePortfolioOver(base, live);
+ expect(merged.netWorthUsd).toBe(1200); // fresher
+ expect(merged.change24hPct).toBeCloseTo(11.11, 2); // preserved from balances
+ expect(merged.sparkline).toEqual([900, 950, 1000]);
+ expect(merged.source).toBe('portfolio');
+ });
+
+ it('falls back to whichever side is priced', () => {
+ const base = toPnlSnapshot(BALANCES);
+ expect(mergePortfolioOver(base, emptyPnlSnapshot())).toBe(base);
+ expect(mergePortfolioOver(emptyPnlSnapshot(), base)).toBe(base);
+ });
+});
+
+describe('buildSparkline — edge cases', () => {
+ it('0 points → empty (UI draws the "tracking starts now" baseline)', () => {
+ const g = buildSparkline([]);
+ expect(g.empty).toBe(true);
+ expect(g.single).toBe(false);
+ expect(g.points).toEqual([]);
+ expect(g.last).toBeNull();
+ });
+
+ it('1 point → a single centered dot, no misleading line', () => {
+ const g = buildSparkline([42], { width: 200, height: 48 });
+ expect(g.empty).toBe(false);
+ expect(g.single).toBe(true);
+ expect(g.points).toHaveLength(1);
+ expect(g.last).toEqual({ x: 100, y: 24 });
+ });
+
+ it('N points → a normalized polyline within the padded box', () => {
+ const g = buildSparkline([0, 5, 10], { width: 220, height: 48, pad: 4 });
+ expect(g.empty).toBe(false);
+ expect(g.single).toBe(false);
+ expect(g.points).toHaveLength(3);
+ expect(g.min).toBe(0);
+ expect(g.max).toBe(10);
+ // first x at pad, last x at width-pad; highest value sits at the top (min y).
+ expect(g.points[0].x).toBeCloseTo(4, 5);
+ expect(g.points[2].x).toBeCloseTo(216, 5);
+ expect(g.points[2].y).toBeCloseTo(4, 5); // value 10 (max) → top
+ expect(g.points[0].y).toBeCloseTo(44, 5); // value 0 (min) → bottom
+ expect(g.polyline.split(' ')).toHaveLength(3);
+ });
+
+ it('flat series (all equal) does not divide by zero', () => {
+ const g = buildSparkline([7, 7, 7]);
+ expect(g.points.every((p) => Number.isFinite(p.y))).toBe(true);
+ });
+
+ it('drops NaN / Infinity from the series', () => {
+ const g = buildSparkline([1, NaN, 3, Infinity]);
+ expect(g.points).toHaveLength(2);
+ });
+});
+
+describe('formatPnl', () => {
+ it('signs and tones a positive change', () => {
+ const r = formatPnl(12.4);
+ expect(r.tone).toBe('up');
+ expect(r.text).toBe('+12.4%');
+ expect(r.arrow).toBe('▲');
+ });
+
+ it('signs and tones a negative change with a minus glyph', () => {
+ const r = formatPnl(-3.05);
+ expect(r.tone).toBe('down');
+ expect(r.text).toBe('−3.05%');
+ expect(r.arrow).toBe('▼');
+ });
+
+ it('treats a tiny change as flat (dead band)', () => {
+ expect(formatPnl(0.01).tone).toBe('flat');
+ expect(formatPnl(0).tone).toBe('flat');
+ });
+
+ it('returns a none tone for null / non-finite', () => {
+ expect(formatPnl(null).tone).toBe('none');
+ expect(formatPnl(NaN).tone).toBe('none');
+ });
+
+ it('drops decimals for large magnitudes', () => {
+ expect(formatPnl(150).text).toBe('+150%');
+ });
+});
+
+describe('formatUsd / formatSol / formatAmount', () => {
+ it('formats compact USD', () => {
+ expect(formatUsd(1_500_000)).toBe('$1.50M');
+ expect(formatUsd(12_345)).toBe('$12.3k');
+ expect(formatUsd(1234)).toBe('$1,234');
+ expect(formatUsd(12.5)).toBe('$12.50');
+ expect(formatUsd(0)).toBe('$0.00');
+ expect(formatUsd(null)).toBe('—');
+ });
+
+ it('formats a tiny but real holding truthfully (no rounding to zero)', () => {
+ expect(formatUsd(0.0001)).toBe('$0.0001');
+ });
+
+ it('formats SOL with trailing-zero trim', () => {
+ expect(formatSol(5)).toBe('5 SOL');
+ expect(formatSol(1.2300)).toBe('1.23 SOL');
+ expect(formatSol(null)).toBe('—');
+ });
+
+ it('formats compact token amounts', () => {
+ expect(formatAmount(412_000)).toBe('412K');
+ expect(formatAmount(1_240_000)).toBe('1.24M');
+ });
+});
+
+describe('$THREE constants', () => {
+ it('exposes the canonical mint and a live 3D coin link', () => {
+ expect(THREE_MINT).toBe('FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump');
+ expect(THREE_COIN_URL).toBe(`/coin3d?mint=${THREE_MINT}`);
+ });
+});
diff --git a/tests/reaction-overlay.test.js b/tests/reaction-overlay.test.js
new file mode 100644
index 000000000..2d9010d33
--- /dev/null
+++ b/tests/reaction-overlay.test.js
@@ -0,0 +1,133 @@
+// Pure-logic coverage for the floating-emoji reaction overlay simulation core.
+// No DOM is touched — only the deterministic spawn/advance/cap/burst math and the
+// ReactionField that the canvas mount drives.
+
+import { describe, it, expect } from 'vitest';
+import {
+ spawnParticle,
+ advanceParticle,
+ particleOpacity,
+ alive,
+ burstCount,
+ capParticles,
+ ReactionField,
+ REACTION_EMOJI,
+} from '../src/reaction-overlay.js';
+
+describe('spawnParticle', () => {
+ it('is deterministic for a given seed', () => {
+ const a = spawnParticle('🔥', 5);
+ const b = spawnParticle('🔥', 5);
+ expect(a).toEqual(b);
+ });
+
+ it('launches near the lower centre, fully transparent, at the bottom', () => {
+ const p = spawnParticle('🚀', 3);
+ expect(p.emoji).toBe('🚀');
+ expect(p.y).toBe(0);
+ expect(p.opacity).toBe(0);
+ expect(p.x0).toBeGreaterThanOrEqual(0.28);
+ expect(p.x0).toBeLessThanOrEqual(0.72);
+ expect(p.ttl).toBeGreaterThan(0);
+ });
+
+ it('spreads particles across seeds so a burst does not stack exactly', () => {
+ const xs = new Set([0, 1, 2, 3, 4].map((s) => spawnParticle('❤️', s).x0));
+ expect(xs.size).toBeGreaterThan(1);
+ });
+});
+
+describe('particleOpacity', () => {
+ it('is zero at the endpoints and full in the middle', () => {
+ expect(particleOpacity(0)).toBe(0);
+ expect(particleOpacity(1)).toBe(0);
+ expect(particleOpacity(0.5)).toBe(1);
+ });
+
+ it('fades in then out', () => {
+ expect(particleOpacity(0.06)).toBeGreaterThan(0);
+ expect(particleOpacity(0.06)).toBeLessThan(1);
+ expect(particleOpacity(0.9)).toBeGreaterThan(0);
+ expect(particleOpacity(0.9)).toBeLessThan(1);
+ });
+});
+
+describe('advanceParticle', () => {
+ it('rises monotonically and dies after its ttl', () => {
+ const p = spawnParticle('👏', 1);
+ const ttl = p.ttl;
+ advanceParticle(p, ttl * 0.25);
+ const y1 = p.y;
+ advanceParticle(p, ttl * 0.25);
+ expect(p.y).toBeGreaterThan(y1);
+ expect(alive(p)).toBe(true);
+ advanceParticle(p, ttl); // push well past end of life
+ expect(alive(p)).toBe(false);
+ });
+
+ it('keeps a particle visible partway through its life', () => {
+ const p = spawnParticle('😂', 2);
+ advanceParticle(p, p.ttl * 0.5);
+ expect(p.opacity).toBeGreaterThan(0);
+ expect(p.size).toBeGreaterThan(0.6);
+ });
+});
+
+describe('burstCount', () => {
+ it('clamps to the per-burst cap and never drops below one', () => {
+ expect(burstCount(1, 12)).toBe(1);
+ expect(burstCount(50, 12)).toBe(12);
+ expect(burstCount(0, 12)).toBe(1);
+ expect(burstCount(7, 12)).toBe(7);
+ });
+});
+
+describe('capParticles', () => {
+ it('evicts the oldest, keeping the newest up to max', () => {
+ const list = [{ id: 0 }, { id: 1 }, { id: 2 }, { id: 3 }, { id: 4 }];
+ capParticles(list, 3);
+ expect(list.map((p) => p.id)).toEqual([2, 3, 4]);
+ });
+
+ it('leaves a short list untouched', () => {
+ const list = [{ id: 0 }, { id: 1 }];
+ capParticles(list, 8);
+ expect(list).toHaveLength(2);
+ });
+});
+
+describe('ReactionField', () => {
+ it('spawns a clamped burst and reports the count', () => {
+ const field = new ReactionField({ max: 64, perBurst: 5 });
+ const spawned = field.add('🔥', 100);
+ expect(spawned).toBe(5);
+ expect(field.count).toBe(5);
+ });
+
+ it('never exceeds the field cap across many bursts', () => {
+ const field = new ReactionField({ max: 10, perBurst: 6 });
+ for (let i = 0; i < 20; i++) field.add('🚀', 6);
+ expect(field.count).toBeLessThanOrEqual(10);
+ });
+
+ it('drops dead particles on step', () => {
+ const field = new ReactionField({ max: 32, perBurst: 4 });
+ field.add('❤️', 4);
+ expect(field.count).toBe(4);
+ field.step(10_000); // longer than any ttl
+ expect(field.count).toBe(0);
+ });
+
+ it('ignores an empty emoji', () => {
+ const field = new ReactionField();
+ expect(field.add('', 3)).toBe(0);
+ expect(field.count).toBe(0);
+ });
+});
+
+describe('REACTION_EMOJI', () => {
+ it('is the curated, frozen client allowlist', () => {
+ expect(REACTION_EMOJI).toEqual(['🔥', '❤️', '👏', '🚀', '😂']);
+ expect(Object.isFrozen(REACTION_EMOJI)).toBe(true);
+ });
+});
diff --git a/tests/sentiment-heatmap-data.test.js b/tests/sentiment-heatmap-data.test.js
new file mode 100644
index 000000000..7afb728c6
--- /dev/null
+++ b/tests/sentiment-heatmap-data.test.js
@@ -0,0 +1,235 @@
+/**
+ * Sentiment heatmap data layer — unit tests.
+ *
+ * Covers the pure transforms behind the 3D field: token normalisation
+ * (momentum + magnitude), the momentum→colour ramp, glow intensity, the
+ * poll-to-poll spike diff, mover ranking, and the narration-context builder.
+ * No DOM, no network — every function under test is pure.
+ */
+
+import { describe, it, expect } from 'vitest';
+import {
+ normalizeToken,
+ normalizeField,
+ momentumColor,
+ glowIntensity,
+ diffSpikes,
+ rankMovers,
+ buildNarrationContext,
+ MOMENTUM_FULL_SCALE_PCT,
+} from '../src/sentiment-heatmap-data.js';
+
+describe('normalizeToken', () => {
+ it('maps 24h change to momentum in [-1, 1] at full scale', () => {
+ const up = normalizeToken({ id: 'a', symbol: 'A', change24h: MOMENTUM_FULL_SCALE_PCT });
+ const down = normalizeToken({ id: 'b', symbol: 'B', change24h: -MOMENTUM_FULL_SCALE_PCT });
+ expect(up.momentum).toBe(1);
+ expect(down.momentum).toBe(-1);
+ });
+
+ it('clamps momentum beyond full scale', () => {
+ const t = normalizeToken({ id: 'a', change24h: MOMENTUM_FULL_SCALE_PCT * 5 });
+ expect(t.momentum).toBe(1);
+ const t2 = normalizeToken({ id: 'a', change24h: -MOMENTUM_FULL_SCALE_PCT * 5 });
+ expect(t2.momentum).toBe(-1);
+ });
+
+ it('treats missing change as flat (zero) momentum', () => {
+ const t = normalizeToken({ id: 'a' });
+ expect(t.momentum).toBe(0);
+ });
+
+ it('log-normalises volume to magnitude in [0, 1] against the field max', () => {
+ const loud = normalizeToken({ id: 'a', volume24h: 1e7 }, { maxLogVolume: 7 });
+ const quiet = normalizeToken({ id: 'b', volume24h: 10 }, { maxLogVolume: 7 });
+ expect(loud.magnitude).toBeCloseTo(1, 5);
+ expect(quiet.magnitude).toBeGreaterThan(0);
+ expect(quiet.magnitude).toBeLessThan(loud.magnitude);
+ });
+
+ it('zero / negative volume yields zero magnitude', () => {
+ expect(normalizeToken({ id: 'a', volume24h: 0 }).magnitude).toBe(0);
+ expect(normalizeToken({ id: 'a', volume24h: -5 }).magnitude).toBe(0);
+ });
+
+ it('derives a label and preserves featured + sentiment', () => {
+ const t = normalizeToken({ id: 'mintmintmint', featured: true, sentiment: { score: 0.4, posPct: 60 } });
+ expect(t.label).toBe('mint…');
+ expect(t.featured).toBe(true);
+ expect(t.sentiment.posPct).toBe(60);
+ });
+});
+
+describe('normalizeField', () => {
+ it('scales magnitude relative to the loudest token in the field', () => {
+ const field = normalizeField([
+ { id: 'a', volume24h: 1e6 },
+ { id: 'b', volume24h: 1e3 },
+ ]);
+ const a = field.find((t) => t.id === 'a');
+ const b = field.find((t) => t.id === 'b');
+ expect(a.magnitude).toBeCloseTo(1, 5); // loudest → full
+ expect(b.magnitude).toBeLessThan(a.magnitude);
+ });
+
+ it('handles an empty field without throwing', () => {
+ expect(normalizeField([])).toEqual([]);
+ expect(normalizeField(null)).toEqual([]);
+ });
+});
+
+describe('momentumColor', () => {
+ it('is cold blue at -1, slate at 0, green-hot at +1', () => {
+ const cold = momentumColor(-1);
+ const neutral = momentumColor(0);
+ const hot = momentumColor(1);
+ // cold: blue dominant
+ expect(cold.b).toBeGreaterThan(cold.r);
+ expect(cold.b).toBeGreaterThan(cold.g);
+ // hot: green dominant
+ expect(hot.g).toBeGreaterThan(hot.r);
+ expect(hot.g).toBeGreaterThan(hot.b);
+ // neutral: desaturated, no channel blown out
+ expect(neutral.r).toBeLessThan(0.5);
+ expect(neutral.g).toBeLessThan(0.5);
+ });
+
+ it('returns channels within [0, 1] and clamps out-of-range momentum', () => {
+ for (const m of [-5, -1, -0.3, 0, 0.7, 1, 9]) {
+ const c = momentumColor(m);
+ for (const ch of ['r', 'g', 'b']) {
+ expect(c[ch]).toBeGreaterThanOrEqual(0);
+ expect(c[ch]).toBeLessThanOrEqual(1);
+ }
+ }
+ });
+
+ it('is monotonic toward green as momentum rises on the positive side', () => {
+ expect(momentumColor(1).g).toBeGreaterThan(momentumColor(0.5).g);
+ expect(momentumColor(0.5).g).toBeGreaterThan(momentumColor(0).g);
+ });
+});
+
+describe('glowIntensity', () => {
+ it('is low for a flat, quiet tile and high for a loud mover', () => {
+ const calm = glowIntensity(0, 0);
+ const blazing = glowIntensity(1, 1);
+ expect(calm).toBeLessThan(0.2);
+ expect(blazing).toBeGreaterThan(calm);
+ });
+
+ it('treats a strong dump as bright as a strong pump (uses |momentum|)', () => {
+ expect(glowIntensity(-1, 0.5)).toBeCloseTo(glowIntensity(1, 0.5), 10);
+ });
+});
+
+describe('diffSpikes', () => {
+ const prev = [
+ { id: 'a', label: 'A', momentum: 0.1, change24h: 2 },
+ { id: 'b', label: 'B', momentum: -0.1, change24h: -2 },
+ ];
+
+ it('flags a token whose momentum jumped beyond the threshold', () => {
+ const next = [
+ { id: 'a', label: 'A', momentum: 0.5, change24h: 12 }, // +0.4 jump
+ { id: 'b', label: 'B', momentum: -0.1, change24h: -2 }, // flat
+ ];
+ const spikes = diffSpikes(prev, next, 0.18);
+ expect(spikes).toHaveLength(1);
+ expect(spikes[0].id).toBe('a');
+ expect(spikes[0].direction).toBe('heating');
+ });
+
+ it('does not flag sub-threshold drift', () => {
+ const next = [
+ { id: 'a', label: 'A', momentum: 0.2, change24h: 5 }, // +0.1 only
+ { id: 'b', label: 'B', momentum: -0.1, change24h: -2 },
+ ];
+ expect(diffSpikes(prev, next, 0.18)).toHaveLength(0);
+ });
+
+ it('tags a sharp drop as cooling', () => {
+ const next = [
+ { id: 'a', label: 'A', momentum: 0.1, change24h: 2 },
+ { id: 'b', label: 'B', momentum: -0.6, change24h: -15 }, // -0.5 jump
+ ];
+ const spikes = diffSpikes(prev, next, 0.18);
+ expect(spikes[0].id).toBe('b');
+ expect(spikes[0].direction).toBe('cooling');
+ });
+
+ it('treats a freshly-arrived hot token as a spike, a fresh calm one not', () => {
+ const next = [
+ ...prev,
+ { id: 'c', label: 'C', momentum: 0.8, change24h: 20 }, // new + hot
+ { id: 'd', label: 'D', momentum: 0.1, change24h: 2 }, // new + calm
+ ];
+ const spikes = diffSpikes(prev, next, 0.18);
+ const ids = spikes.map((s) => s.id);
+ expect(ids).toContain('c');
+ expect(ids).not.toContain('d');
+ expect(spikes.find((s) => s.id === 'c').fresh).toBe(true);
+ });
+
+ it('sorts movers by absolute delta, biggest first', () => {
+ const next = [
+ { id: 'a', label: 'A', momentum: 0.5, change24h: 12 }, // +0.4
+ { id: 'b', label: 'B', momentum: -0.9, change24h: -22 }, // -0.8
+ ];
+ const spikes = diffSpikes(prev, next, 0.18);
+ expect(spikes[0].id).toBe('b');
+ expect(spikes[1].id).toBe('a');
+ });
+
+ it('handles an empty previous snapshot (first poll)', () => {
+ const next = [{ id: 'x', label: 'X', momentum: 0.9, change24h: 25 }];
+ const spikes = diffSpikes([], next, 0.18);
+ expect(spikes.map((s) => s.id)).toContain('x');
+ });
+});
+
+describe('rankMovers', () => {
+ const tokens = [
+ { id: 't', label: 'THREE', featured: true, momentum: 0.2, change24h: 5 },
+ { id: 'a', label: 'A', momentum: 0.6, change24h: 15 },
+ { id: 'b', label: 'B', momentum: -0.4, change24h: -10 },
+ { id: 'c', label: 'C', momentum: 0.1, change24h: 2 },
+ ];
+
+ it('separates gainers from losers and finds the anchor', () => {
+ const m = rankMovers(tokens, { count: 2 });
+ expect(m.gainers[0].label).toBe('A'); // biggest gainer first
+ expect(m.losers[0].label).toBe('B');
+ expect(m.anchor.label).toBe('THREE');
+ expect(m.total).toBe(4);
+ });
+
+ it('computes an average momentum across the field', () => {
+ const m = rankMovers(tokens);
+ expect(m.avgMomentum).toBeCloseTo((0.2 + 0.6 - 0.4 + 0.1) / 4, 6);
+ });
+});
+
+describe('buildNarrationContext', () => {
+ it('always names $THREE for the anchor and folds in its sentiment', () => {
+ const movers = {
+ anchor: { label: 'THREE', featured: true, change24h: 8, sentiment: { score: 0.4, posPct: 62, count: 30 } },
+ gainers: [{ label: 'A', change24h: 15 }],
+ losers: [{ label: 'B', change24h: -10 }],
+ avgMomentum: 0.2,
+ total: 4,
+ };
+ const ctx = buildNarrationContext({ spikes: [], movers });
+ expect(ctx).toMatch(/\$THREE/);
+ expect(ctx).toMatch(/Heating across the board/);
+ expect(ctx).toMatch(/62% bullish/);
+ });
+
+ it('describes a cooling tape and a fresh spike', () => {
+ const movers = { anchor: null, gainers: [], losers: [{ label: 'B', change24h: -12 }], avgMomentum: -0.3, total: 3 };
+ const spikes = [{ label: 'B', change24h: -12, direction: 'cooling' }];
+ const ctx = buildNarrationContext({ spikes, movers });
+ expect(ctx).toMatch(/Cooling across the board/);
+ expect(ctx).toMatch(/Just cooling: B/);
+ });
+});
diff --git a/tests/vanity-grind-director.test.js b/tests/vanity-grind-director.test.js
new file mode 100644
index 000000000..d52d48627
--- /dev/null
+++ b/tests/vanity-grind-director.test.js
@@ -0,0 +1,39 @@
+import { describe, it, expect } from 'vitest';
+import { parseGrindCommand } from '../src/vanity-grind-director.js';
+
+describe('parseGrindCommand', () => {
+ it('extracts a prefix from the bare "grind <token>" form', () => {
+ expect(parseGrindCommand('grind pump')).toMatchObject({ prefix: 'pump', suffix: null, ignoreCase: true });
+ });
+
+ it('parses "starting with" / "ending with" phrasing', () => {
+ expect(parseGrindCommand('grind a wallet starting with pump')).toMatchObject({ prefix: 'pump' });
+ expect(parseGrindCommand('vanity ending with 42')).toMatchObject({ prefix: '', suffix: '42' });
+ });
+
+ it('parses explicit prefix + suffix together', () => {
+ expect(parseGrindCommand('grind prefix nova suffix xyz')).toMatchObject({ prefix: 'nova', suffix: 'xyz' });
+ });
+
+ it('caps the pattern at 6 base58 chars', () => {
+ expect(parseGrindCommand('grind abcdefghij').prefix).toBe('abcdef');
+ });
+
+ it('honours an explicit case-sensitive request', () => {
+ expect(parseGrindCommand('grind Pump case-sensitive')).toMatchObject({ prefix: 'Pump', ignoreCase: false });
+ });
+
+ it('rejects non-base58 tokens (0 O I l) by finding no pattern', () => {
+ // "lOl" is all non-base58 chars → no usable token → not a grind command.
+ expect(parseGrindCommand('grind lOl')).toBeNull();
+ });
+
+ it('returns null when there is no grind trigger', () => {
+ expect(parseGrindCommand('research the latest solana news')).toBeNull();
+ expect(parseGrindCommand('launch a coin named Foo')).toBeNull();
+ });
+
+ it('ignores filler words after the trigger', () => {
+ expect(parseGrindCommand('grind a wallet for me')).toBeNull();
+ });
+});
diff --git a/tests/watch-intent-reactions.test.js b/tests/watch-intent-reactions.test.js
new file mode 100644
index 000000000..1ddacaa81
--- /dev/null
+++ b/tests/watch-intent-reactions.test.js
@@ -0,0 +1,84 @@
+// Validation + throttle decisioning for spectator reactions on watch-intent.
+// These are the pure rules the endpoint enforces; testing them here keeps the
+// allowlist and throttle math honest without booting the serverless handler.
+
+import { describe, it, expect } from 'vitest';
+import {
+ REACTION_EMOJI,
+ normalizeReaction,
+ isAllowedReaction,
+ shouldThrottleReaction,
+ REACTION_THROTTLE_MS,
+ reactionsRecentKey,
+ reactionsTotalKey,
+ reactionThrottleKey,
+} from '../api/_lib/reaction-rules.js';
+
+describe('normalizeReaction', () => {
+ it('accepts every allowlisted emoji as itself', () => {
+ for (const e of REACTION_EMOJI) expect(normalizeReaction(e)).toBe(e);
+ });
+
+ it('trims surrounding whitespace', () => {
+ expect(normalizeReaction(' 🔥 ')).toBe('🔥');
+ });
+
+ it('reconciles the bare heart without its variation selector', () => {
+ expect(normalizeReaction('❤')).toBe('❤️');
+ });
+
+ it('rejects anything off the allowlist', () => {
+ expect(normalizeReaction('💀')).toBeNull();
+ expect(normalizeReaction('🔥🔥')).toBeNull();
+ expect(normalizeReaction('not-an-emoji')).toBeNull();
+ });
+
+ it('rejects non-strings and empty input', () => {
+ expect(normalizeReaction(null)).toBeNull();
+ expect(normalizeReaction(undefined)).toBeNull();
+ expect(normalizeReaction(42)).toBeNull();
+ expect(normalizeReaction('')).toBeNull();
+ expect(normalizeReaction(' ')).toBeNull();
+ });
+});
+
+describe('isAllowedReaction', () => {
+ it('mirrors normalizeReaction as a boolean', () => {
+ expect(isAllowedReaction('🚀')).toBe(true);
+ expect(isAllowedReaction('💩')).toBe(false);
+ });
+});
+
+describe('shouldThrottleReaction', () => {
+ const now = 1_000_000;
+
+ it('allows the first reaction (no prior timestamp)', () => {
+ expect(shouldThrottleReaction(null, now)).toBe(false);
+ expect(shouldThrottleReaction(0, now)).toBe(false);
+ expect(shouldThrottleReaction(undefined, now)).toBe(false);
+ });
+
+ it('throttles a reaction inside the window', () => {
+ expect(shouldThrottleReaction(now - 100, now)).toBe(true);
+ });
+
+ it('allows a reaction once the window has elapsed', () => {
+ expect(shouldThrottleReaction(now - REACTION_THROTTLE_MS, now)).toBe(false);
+ expect(shouldThrottleReaction(now - REACTION_THROTTLE_MS - 1, now)).toBe(false);
+ });
+
+ it('honours a custom window', () => {
+ expect(shouldThrottleReaction(now - 500, now, 1000)).toBe(true);
+ expect(shouldThrottleReaction(now - 1500, now, 1000)).toBe(false);
+ });
+});
+
+describe('redis key helpers', () => {
+ const agentId = '550e8400-e29b-41d4-a716-446655440000';
+
+ it('namespace per agent and per IP', () => {
+ expect(reactionsRecentKey(agentId)).toBe(`agent:screen:${agentId}:reactions`);
+ expect(reactionsTotalKey(agentId)).toBe(`agent:screen:${agentId}:rtotal`);
+ expect(reactionThrottleKey(agentId, '1.2.3.4')).toBe(`screen:react:t:${agentId}:1.2.3.4`);
+ });
+});
diff --git a/workers/agent-anchor/index.js b/workers/agent-anchor/index.js
index 5654558bd..8897b4e84 100644
--- a/workers/agent-anchor/index.js
+++ b/workers/agent-anchor/index.js
@@ -23,9 +23,13 @@ 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();
+// One JSON line per event to stdout/stderr — matches workers/agent-sniper/log.js
+// so the worker's output drops straight into log search without a parser, and
+// without tripping the no-console lint rule.
function log(level, msg, meta) {
- const line = { t: new Date().toISOString(), level, msg, ...(meta || {}) };
- (level === 'error' ? console.error : console.log)(JSON.stringify(line));
+ const line = { t: new Date().toISOString(), level, tag: 'agent-anchor', msg, ...(meta || {}) };
+ const out = level === 'error' ? process.stderr : process.stdout;
+ out.write(JSON.stringify(line) + '\n');
}
// Run one full bulletin: gather → script → split → publish → push. Each stage