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.

Refactor avatar reactions and event handling in Pump.fun

nirholas2540f8837ce0
diff --git a/.claude/hooks/no-shortcuts.sh b/.claude/hooks/no-shortcuts.sh
new file mode 100644
index 000000000..c638d1c97
--- /dev/null
+++ b/.claude/hooks/no-shortcuts.sh
@@ -0,0 +1,70 @@
+#!/usr/bin/env bash
+# PreToolUse hook: blocks Write/Edit that introduce mocks, fakes, TODOs, or stubs.
+# Reads JSON event from stdin. Exits 2 with stderr message to block.
+
+set -euo pipefail
+
+input="$(cat)"
+
+tool_name=$(printf '%s' "$input" | jq -r '.tool_name // empty')
+file_path=$(printf '%s' "$input" | jq -r '.tool_input.file_path // empty')
+
+case "$tool_name" in
+ Write|Edit|MultiEdit) ;;
+ *) exit 0 ;;
+esac
+
+# Skip the hook script itself, CLAUDE.md, memory files, docs, tests.
+case "$file_path" in
+ */.claude/hooks/*) exit 0 ;;
+ */CLAUDE.md) exit 0 ;;
+ */memory/*) exit 0 ;;
+ *.md) exit 0 ;;
+ */tests/*|*/test/*|*.test.*|*.spec.*) exit 0 ;;
+ */node_modules/*) exit 0 ;;
+esac
+
+# Collect the candidate new content from any of the supported tool shapes.
+content=$(printf '%s' "$input" | jq -r '
+ [
+ (.tool_input.content // empty),
+ (.tool_input.new_string // empty),
+ ((.tool_input.edits // []) | map(.new_string // "") | join("\n"))
+ ] | join("\n")
+')
+
+if [ -z "$content" ]; then
+ exit 0
+fi
+
+violations=()
+
+# Lazy patterns. Word-boundary-ish matching to avoid false hits like "automock".
+check() {
+ local pattern="$1" label="$2"
+ if printf '%s' "$content" | grep -Eqi "$pattern"; then
+ violations+=("$label")
+ fi
+}
+
+check '(^|[^A-Za-z0-9_])TODO([^A-Za-z0-9_]|$)' 'TODO comment'
+check '(^|[^A-Za-z0-9_])FIXME([^A-Za-z0-9_]|$)' 'FIXME comment'
+check '(^|[^A-Za-z0-9_])XXX([^A-Za-z0-9_]|$)' 'XXX comment'
+check 'not[[:space:]]*implemented' 'not-implemented stub'
+check 'throw[[:space:]]+new[[:space:]]+Error\([^)]*implement' 'throw not-implemented'
+check '(mockData|fakeData|dummyData|sampleData|placeholderData)' 'mock/fake/dummy/sample/placeholder data identifier'
+check 'lorem[[:space:]]*ipsum' 'lorem ipsum'
+check 'implement[[:space:]]+(this|me|later)' '"implement this/me/later" comment'
+check 'wire[[:space:]]+(this|it|up)[[:space:]]+later' '"wire up later" comment'
+check 'for[[:space:]]+now[[:space:]]*[,:]' '"for now" shortcut comment'
+
+if [ ${#violations[@]} -gt 0 ]; then
+ printf 'Blocked by no-shortcuts hook (%s):\n' "$file_path" >&2
+ for v in "${violations[@]}"; do
+ printf ' - %s\n' "$v" >&2
+ done
+ printf 'Per CLAUDE.md: no mocks, no fake data, no TODOs, no stubs. Implement it for real.\n' >&2
+ exit 2
+fi
+
+exit 0
diff --git a/CLAUDE.md b/CLAUDE.md
new file mode 100644
index 000000000..d8515b7f6
--- /dev/null
+++ b/CLAUDE.md
@@ -0,0 +1,45 @@
+# 3D-Agent — Operating Rules for Claude Agents
+
+These rules OVERRIDE defaults. Every agent in this workspace must follow them.
+
+## Prime directive
+**Execute. Do not interview the user.** Pick the most reasonable interpretation and ship a complete feature. Questions waste the user's time.
+
+## Hard rules (non-negotiable)
+
+1. **No mocks. No fake data. No placeholders.** Use real APIs, real endpoints, real data. If credentials are missing, locate them in `.env`, `vercel env`, or ask once — then proceed.
+2. **No TODO comments. No `// implement later`. No stub functions.** If you write it, finish it.
+3. **No commented-out code in committed work.** Delete or implement.
+4. **No `throw new Error("not implemented")`.** Implement it.
+5. **No `setTimeout` fake-loading or fake progress bars.** Real async or nothing.
+6. **No fallback sample arrays** (e.g. `const sampleAgents = [...]`) shipped to production. Real fetch only.
+7. **Errors handled at boundaries** (network, user input). Internal code trusts itself.
+
+## Definition of done
+
+A feature is NOT done until ALL of these are true:
+- Code is written, wired into the UI, and reachable by the user.
+- For UI work: dev server started (`npm run dev`), feature exercised in a real browser, no console errors, network tab shows real API calls succeeding.
+- Edge cases handled (empty state, error state, loading state — all real, not faked).
+- Existing tests still pass (`npm test`).
+- `git diff` reviewed by you before claiming completion.
+
+If you cannot verify a step, say so explicitly. Do not claim done.
+
+## Workflow
+
+- Use TodoWrite for any task with 3+ steps. Mark items complete in real time.
+- Before stopping on a feature task, run the **completionist** subagent to audit your changed files for the rules above. Fix every item it flags. Then stop.
+- Communication: short. State what you did, what's next. No trailing recaps.
+
+## Stack notes
+
+- Frontend: vanilla JS modules + Vite (`npm run dev`, port 3000).
+- 3D: Three.js with glTF/GLB.
+- Backend touchpoints: Vercel functions in `api/`, workers in `workers/`.
+- Solana/agent SDKs in `sdk/`, `solana-agent-sdk/`, `agent-payments-sdk/`.
+- Real APIs in use: Pump.fun feed, Solana RPC, OpenAI/Anthropic via worker proxies. Never mock these.
+
+## Tone
+
+Professional. No filler. No "great question!" No emojis unless the user asks. Short sentences. Ship work.
diff --git a/api/_lib/pumpfun-ws-feed.js b/api/_lib/pumpfun-ws-feed.js
index c241c4770..fddc4061c 100644
--- a/api/_lib/pumpfun-ws-feed.js
+++ b/api/_lib/pumpfun-ws-feed.js
@@ -92,15 +92,21 @@ export function connectPumpFunFeed({ onEvent, signal, kind = 'all' }) {
if (msg.txType === 'create' && (kind === 'all' || kind === 'mint')) {
enrichMint(msg).then((data) => {
+ pushBuffer('mint', data);
if (active) onEvent({ kind: 'mint', data });
}).catch(() => {
- if (active) onEvent({ kind: 'mint', data: normalizeMint(msg, null, 0) });
+ const data = normalizeMint(msg, null, 0);
+ pushBuffer('mint', data);
+ if (active) onEvent({ kind: 'mint', data });
});
} else if ((msg.txType === 'migrate' || msg.txType === 'migration') && (kind === 'all' || kind === 'graduation')) {
enrichGrad(msg).then((data) => {
+ pushBuffer('graduation', data);
if (active) onEvent({ kind: 'graduation', data });
}).catch(() => {
- if (active) onEvent({ kind: 'graduation', data: normalizeGrad(msg) });
+ const data = normalizeGrad(msg);
+ pushBuffer('graduation', data);
+ if (active) onEvent({ kind: 'graduation', data });
});
}
});
@@ -225,6 +231,16 @@ function formatAge(createdAtMs) {
return Math.floor(h / 24) + 'd';
}
+function pickMc(c, solPrice) {
+ if (typeof c?.usd_market_cap === 'number') return c.usd_market_cap;
+ if (typeof c?.market_cap === 'number' && solPrice > 0) return c.market_cap * solPrice;
+ return null;
+}
+
+function isGraduated(c) {
+ return c?.complete === true || !!c?.raydium_pool || !!c?.pump_swap_pool;
+}
+
async function enrichGrad(d) {
const base = normalizeGrad(d);
const mint = d.mint;
@@ -240,42 +256,59 @@ async function enrichGrad(d) {
const creator = coin.creator || d.traderPublicKey || null;
const userCoins = creator ? await fetchCreatorCoins(creator) : null;
- const usdMc = typeof coin.usd_market_cap === 'number' ? coin.usd_market_cap : null;
+ const usdMc = pickMc(coin, solPrice);
const launchSol = typeof coin.market_cap_at_launch === 'number' ? coin.market_cap_at_launch : null;
const launchUsd = launchSol != null && solPrice > 0 ? launchSol * solPrice : null;
+ // ATH: pump.fun frontend exposes ath_market_cap (USD) on some mints; fall
+ // back to current MC as a floor so the renderer always has a value.
+ const athUsd = typeof coin.ath_market_cap === 'number' ? coin.ath_market_cap
+ : typeof coin.ath_market_cap_usd === 'number' ? coin.ath_market_cap_usd
+ : usdMc;
+
const createdMs = coin.created_timestamp ? Number(coin.created_timestamp) : null;
const age = formatAge(createdMs);
let creatorTokens = [];
let launches = null;
+ let creatorGraduated = null;
if (Array.isArray(userCoins)) {
launches = userCoins.length;
+ creatorGraduated = userCoins.reduce((n, c) => n + (isGraduated(c) ? 1 : 0), 0);
creatorTokens = userCoins
.map((c) => ({
mint: c.mint,
symbol: c.symbol,
name: c.name,
- mc: typeof c.usd_market_cap === 'number'
- ? c.usd_market_cap
- : (typeof c.market_cap === 'number' && solPrice > 0 ? c.market_cap * solPrice : null),
+ mc: pickMc(c, solPrice),
+ graduated: isGraduated(c),
}))
.filter((c) => c.symbol);
}
+ // Migration `solAmount` is the most accurate "graduation deposit" number.
+ // If absent (PumpPortal sometimes omits), fall back to the real_sol_reserves
+ // at graduation (≈ 85 SOL bonding-curve floor).
const amountSol = typeof d.solAmount === 'number' ? d.solAmount
- : typeof coin.virtual_sol_reserves === 'number' && coin.virtual_sol_reserves > 0
- ? coin.virtual_sol_reserves / 1e9
+ : typeof coin.real_sol_reserves === 'number' && coin.real_sol_reserves > 0
+ ? coin.real_sol_reserves / 1e9
: null;
const amountUsd = amountSol != null && solPrice > 0 ? amountSol * solPrice : null;
+ const graduated = isGraduated(coin);
+ const raydiumPool = coin.raydium_pool || null;
+ const pumpSwapPool = coin.pump_swap_pool || null;
+
return {
...base,
name: coin.name || base.name,
symbol: coin.symbol || base.symbol,
description: coin.description || null,
creator,
+ creator_username: coin.username || null,
+ creator_profile_image: coin.profile_image || null,
image_uri: coin.image_uri || null,
+ video_uri: coin.video_uri || null,
twitter: coin.twitter || null,
telegram: coin.telegram || null,
website: coin.website || null,
@@ -283,12 +316,60 @@ async function enrichGrad(d) {
market_cap: usdMc,
market_cap_usd_initial: launchUsd,
market_cap_at_launch: launchSol,
+ ath_market_cap: athUsd,
sol_price: solPrice || null,
created_at: createdMs ? Math.floor(createdMs / 1000) : null,
age,
amount_sol: amountSol,
amount_usd: amountUsd,
+ bonding_curve_pct: 100,
+ complete: graduated,
+ raydium_pool: raydiumPool,
+ pump_swap_pool: pumpSwapPool,
+ reply_count: typeof coin.reply_count === 'number' ? coin.reply_count : null,
creator_launches: launches,
+ creator_graduated: creatorGraduated,
creator_tokens: creatorTokens,
};
}
+
+// ── Process-local replay buffer ──────────────────────────────────────────────
+//
+// The PumpPortal WS connection is shared per Vercel instance. We keep a small
+// rolling buffer of the most-recent enriched mint and graduation events so each
+// new SSE client (which would otherwise see a blank feed until the next event)
+// can immediately render a contextual backlog. Buffered events are emitted with
+// a `replay: true` marker so the UI can dim them.
+
+const BUFFER_LIMIT = { mint: 25, graduation: 25 };
+const _buffer = { mint: [], graduation: [] };
+
+function pushBuffer(kind, data) {
+ const arr = _buffer[kind];
+ if (!arr) return;
+ const sig = data?.signature || data?.tx_signature;
+ if (sig && arr.some((e) => (e.signature || e.tx_signature) === sig)) return;
+ arr.unshift(data);
+ while (arr.length > BUFFER_LIMIT[kind]) arr.pop();
+}
+
+/**
+ * Snapshot of recently buffered events, newest-first. Caller filters by kind.
+ * @param {{ kind?: 'all'|'mint'|'graduation'|'claims', limit?: number }} opts
+ */
+export function recentBuffered({ kind = 'all', limit = 10 } = {}) {
+ const out = [];
+ if (kind === 'all' || kind === 'mint') {
+ for (const data of _buffer.mint.slice(0, limit)) out.push({ kind: 'mint', data });
+ }
+ if (kind === 'all' || kind === 'graduation' || kind === 'claims') {
+ for (const data of _buffer.graduation.slice(0, limit)) out.push({ kind: 'graduation', data });
+ }
+ // Sort by timestamp/created_at descending so a multi-kind replay is interleaved.
+ out.sort((a, b) => {
+ const ta = a.data.timestamp || a.data.created_at || 0;
+ const tb = b.data.timestamp || b.data.created_at || 0;
+ return tb - ta;
+ });
+ return out.slice(0, limit);
+}
diff --git a/api/_lib/solana/programs.js b/api/_lib/solana/programs.js
new file mode 100644
index 000000000..71ed64754
--- /dev/null
+++ b/api/_lib/solana/programs.js
@@ -0,0 +1,45 @@
+// Pump protocol program IDs, well-known accounts, and instruction
+// discriminators. Ported from pumpkit @pumpkit/core/src/solana/programs.ts.
+//
+// Canonical references:
+// - Pump bonding curve program
+// - PumpSwap AMM program
+// - PumpFees program
+//
+// Discriminators are 8-byte Anchor instruction/event prefixes used to classify
+// raw instruction data in webhook + RPC log streams without re-deriving them
+// from the IDL on every call.
+
+export const PUMP_PROGRAM_ID = '6EF8rrecthR5Dkzon8Nwu78hRvfCKubJ14M5uBEwF6P';
+export const PUMP_AMM_PROGRAM_ID = 'pAMMBay6oceH9fJKBRHGP5D4bD4sWpmSwMn52FMfXEA';
+export const PUMP_FEE_PROGRAM_ID = 'pfeeUxB6jkeY1Hxd7CsFCAjcbHA9rWtchMGdZ6VojVZ';
+export const PUMPFUN_FEE_ACCOUNT = 'CebN5WGQ4jvEPvsVU4EoHEpgzq1VV7AbCJ5GEFDM97zC';
+export const PUMPFUN_MIGRATION_AUTHORITY = '39azUYFWPz3VHgKCf3VChUwbpURdCHRxjWVowf5jUJjg';
+export const WSOL_MINT = 'So11111111111111111111111111111111111111112';
+
+export const MONITORED_PROGRAM_IDS = Object.freeze([
+ PUMP_PROGRAM_ID,
+ PUMP_AMM_PROGRAM_ID,
+ PUMP_FEE_PROGRAM_ID,
+]);
+
+export const CREATE_V2_DISCRIMINATOR = Buffer.from([0x19, 0xe0, 0x63, 0x50, 0x0d, 0x7a, 0xd8, 0x33]);
+export const CREATE_DISCRIMINATOR = Buffer.from([0x18, 0x1e, 0xc8, 0x28, 0x05, 0x1c, 0x07, 0x77]);
+export const COMPLETE_EVENT_DISCRIMINATOR = Buffer.from([0xe9, 0x17, 0x0d, 0x1e, 0x0e, 0x10, 0x6c, 0x28]);
+export const TRADE_EVENT_DISCRIMINATOR = Buffer.from([0xe4, 0x52, 0xf2, 0xd2, 0xb2, 0x32, 0xd1, 0x09]);
+
+const DISCRIMINATORS = {
+ create_v2: CREATE_V2_DISCRIMINATOR,
+ create: CREATE_DISCRIMINATOR,
+ complete_event: COMPLETE_EVENT_DISCRIMINATOR,
+ trade_event: TRADE_EVENT_DISCRIMINATOR,
+};
+
+export function matchDiscriminator(data) {
+ if (!data || data.length < 8) return null;
+ const head = Buffer.isBuffer(data) ? data.subarray(0, 8) : Buffer.from(data).subarray(0, 8);
+ for (const [name, disc] of Object.entries(DISCRIMINATORS)) {
+ if (head.equals(disc)) return name;
+ }
+ return null;
+}
diff --git a/api/agents/pumpfun.js b/api/agents/pumpfun.js
index 9e525ae70..82ea74aab 100644
--- a/api/agents/pumpfun.js
+++ b/api/agents/pumpfun.js
@@ -90,7 +90,7 @@ function clamp(n, lo, hi) {
// ── pumpfun-feed (SSE) ────────────────────────────────────────────────────────
-import { connectPumpFunFeed } from '../_lib/pumpfun-ws-feed.js';
+import { connectPumpFunFeed, recentBuffered } from '../_lib/pumpfun-ws-feed.js';
const TIER_RANK = { notable: 1, influencer: 2, mega: 3 };
async function handleFeed(req, res) {
@@ -117,6 +117,18 @@ async function handleFeed(req, res) {
const wsKind = kind === 'claims' ? 'graduation' : kind;
const stopWs = connectPumpFunFeed({ kind: wsKind, signal: wsAbort.signal, onEvent: ({ kind: evKind, data }) => { if (active) queue.push({ evKind, data }); } });
_writeSse(res, 'open', { kind, minTier: minTierParam || null, source: 'websocket' });
+ // Replay the most recent buffered events so a freshly-opened feed is never
+ // blank. Newest first so the UI's `prepend` results in chronological order.
+ try {
+ const replay = recentBuffered({ kind: wsKind, limit: 10 });
+ // Emit oldest-first so each `prepend` puts the newest at the top.
+ for (const ev of replay.slice().reverse()) {
+ if (minTier && TIER_RANK[(ev.data?.tier || '').toLowerCase()] < minTier) continue;
+ _writeSse(res, ev.kind, { ...ev.data, replay: true });
+ }
+ } catch (err) {
+ console.warn('[pumpfun-feed] replay failed:', err?.message);
+ }
const seen = new Set();
let lastSig = null;
const tickClaims = pumpfunBotEnabled() ? async () => {
diff --git a/public/pumpfun.html b/public/pumpfun.html
index 2f5e2191d..148c87abc 100644
--- a/public/pumpfun.html
+++ b/public/pumpfun.html
@@ -38,8 +38,55 @@
.pf-filterbar button:hover { background: #20202c; }
.pf-filterbar button.toggle[data-on="0"] { color: var(--muted); }
#ctl-avatar-wrap { display: inline-flex; align-items: center; gap: 6px; }
- #ctl-avatar-url { width: 0; padding: 0; border-width: 0; overflow: hidden; transition: width 0.2s, padding 0.2s, border-width 0.2s; }
- #ctl-avatar-url.visible { width: 160px; padding: 6px 10px; border-width: 1px; }
+ #ctl-avatar-btn { display: inline-flex; align-items: center; gap: 8px; max-width: 240px; }
+ #ctl-avatar-btn .avatar-thumb { width: 22px; height: 22px; border-radius: 4px; background: #1a1a24 center/cover no-repeat; border: 1px solid #2a2a36; flex: 0 0 auto; }
+ #ctl-avatar-btn .avatar-name { white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 160px; }
+ #ctl-avatar-btn .avatar-caret { color: var(--muted); font-size: 10px; }
+
+ /* Picker modal */
+ .pf-modal-backdrop { position: fixed; inset: 0; background: rgba(4,4,8,0.72); backdrop-filter: blur(4px); z-index: 100; display: none; align-items: center; justify-content: center; padding: 24px; animation: fade-in 0.15s ease; }
+ .pf-modal-backdrop[data-open="true"] { display: flex; }
+ .pf-modal { width: min(960px, 100%); max-height: min(720px, calc(100vh - 48px)); background: var(--panel); border: 1px solid var(--border); border-radius: 12px; display: flex; flex-direction: column; overflow: hidden; box-shadow: 0 24px 64px rgba(0,0,0,0.5); animation: pop-in 0.18s ease; }
+ .pf-modal-head { display: flex; align-items: center; gap: 12px; padding: 14px 18px; border-bottom: 1px solid var(--border); }
+ .pf-modal-head h2 { margin: 0; font-size: 14px; font-weight: 600; }
+ .pf-modal-head .spacer { flex: 1; }
+ .pf-modal-close { background: transparent; border: 0; color: var(--muted); cursor: pointer; font-size: 18px; line-height: 1; padding: 4px 8px; border-radius: 4px; }
+ .pf-modal-close:hover { background: #1f1f29; color: #eee; }
+ .pf-tabs { display: flex; gap: 2px; padding: 0 14px; border-bottom: 1px solid var(--border); background: #10101a; }
+ .pf-tab { background: transparent; border: 0; color: var(--muted); cursor: pointer; padding: 10px 14px; font-size: 13px; font-weight: 500; border-bottom: 2px solid transparent; }
+ .pf-tab:hover { color: #eee; }
+ .pf-tab[aria-selected="true"] { color: #eee; border-bottom-color: var(--accent); }
+ .pf-tab .badge { display: inline-block; margin-left: 6px; font-size: 10px; color: var(--muted); }
+ .pf-toolbar { display: flex; gap: 8px; align-items: center; padding: 12px 18px; border-bottom: 1px solid var(--border); }
+ .pf-toolbar input[type="search"] { flex: 1; background: #161620; color: #eee; border: 1px solid #2a2a36; border-radius: 6px; padding: 7px 10px; font-size: 13px; }
+ .pf-toolbar input[type="search"]:focus { outline: none; border-color: var(--accent); }
+ .pf-toolbar .custom-row { display: flex; gap: 6px; align-items: center; }
+ .pf-toolbar .custom-row input { background: #161620; color: #eee; border: 1px solid #2a2a36; border-radius: 6px; padding: 7px 10px; font-size: 13px; width: 220px; }
+ .pf-toolbar .custom-row button { background: var(--accent); border: 0; color: #fff; border-radius: 6px; padding: 7px 12px; font-size: 13px; cursor: pointer; }
+ .pf-toolbar .custom-row button:hover { filter: brightness(1.1); }
+ .pf-body { flex: 1; min-height: 0; overflow-y: auto; padding: 16px 18px; }
+ .pf-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(140px, 1fr)); gap: 12px; }
+ .pf-card { position: relative; background: #161620; border: 1px solid #232330; border-radius: 8px; overflow: hidden; cursor: pointer; transition: border-color 0.15s, transform 0.1s; display: flex; flex-direction: column; text-align: left; padding: 0; color: #eee; font: inherit; }
+ .pf-card:hover { border-color: #3a3a4a; }
+ .pf-card:active { transform: scale(0.98); }
+ .pf-card[data-selected="true"] { border-color: var(--accent); box-shadow: 0 0 0 1px var(--accent) inset; }
+ .pf-card .thumb { aspect-ratio: 1/1; background: #0e0e16 center/cover no-repeat; border-bottom: 1px solid #232330; position: relative; display: flex; align-items: center; justify-content: center; color: #2a2a3a; font-size: 32px; }
+ .pf-card .meta { padding: 8px 10px; }
+ .pf-card .name { font-size: 12px; font-weight: 600; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+ .pf-card .sub { font-size: 10px; color: var(--muted); margin-top: 2px; }
+ .pf-card .vis-tag { position: absolute; top: 6px; right: 6px; font-size: 9px; padding: 2px 6px; border-radius: 999px; background: rgba(0,0,0,0.6); color: #cbd5e1; text-transform: uppercase; letter-spacing: 0.05em; }
+ .pf-card .vis-tag.private { background: rgba(74,31,35,0.85); color: #fbbf24; }
+ .pf-card .selected-mark { position: absolute; top: 6px; left: 6px; width: 18px; height: 18px; border-radius: 50%; background: var(--accent); display: none; align-items: center; justify-content: center; color: #fff; font-size: 11px; font-weight: 700; }
+ .pf-card[data-selected="true"] .selected-mark { display: flex; }
+ .pf-status { padding: 32px 16px; text-align: center; color: var(--muted); font-size: 13px; }
+ .pf-status .cta { display: inline-block; margin-top: 10px; padding: 8px 14px; background: var(--accent); color: #fff; border-radius: 6px; font-size: 13px; }
+ .pf-status .cta:hover { filter: brightness(1.1); text-decoration: none; }
+ .pf-loadmore { display: block; margin: 16px auto 0; background: #161620; color: #eee; border: 1px solid #2a2a36; border-radius: 6px; padding: 8px 16px; font-size: 13px; cursor: pointer; }
+ .pf-loadmore:hover { background: #20202c; }
+ .pf-loadmore[disabled] { opacity: 0.5; cursor: wait; }
+ @keyframes fade-in { from { opacity: 0; } to { opacity: 1; } }
+ @keyframes pop-in { from { opacity: 0; transform: translateY(8px) scale(0.98); } to { opacity: 1; transform: none; } }
+ @media (max-width: 600px) { .pf-toolbar { flex-direction: column; align-items: stretch; } .pf-toolbar .custom-row input { width: 100%; } }
main.pf-main { position: relative; height: calc(100vh - 140px); display: grid; grid-template-columns: 1fr 360px; }
#stage { position: relative; display: flex; flex-direction: column; }
iframe { width: 100%; flex: 1; border: 0; display: block; background: var(--bg); }
@@ -76,10 +123,22 @@
/* Event cards */
.evt { border: 1px solid #232330; background: #15151d; border-radius: 8px; padding: 10px 12px; margin: 6px 0;
- animation: evt-in 0.35s ease; font-size: 12px; }
+ animation: evt-in 0.35s ease; font-size: 12px; position: relative; }
.evt.first { border-color: #1f4232; background: #0e1f17; }
.evt.fake { border-color: #4a1f23; background: #1f1418; }
.evt.grad { border-color: #2c1f4a; background: #18142a; }
+ .evt.replay { opacity: 0.62; animation: none; }
+ .evt.replay::after { content: 'replay'; position: absolute; top: 8px; right: 10px; font-size: 9px; letter-spacing: 0.08em;
+ text-transform: uppercase; color: #6a6a82; padding: 1px 6px; border: 1px solid #2a2a3c; border-radius: 999px; background: #0e0e16; }
+ .evt-head { display: flex; gap: 10px; align-items: flex-start; }
+ .evt-thumb { width: 44px; height: 44px; border-radius: 8px; object-fit: cover; border: 1px solid #2a2a3c;
+ background: #0e0e16; flex: 0 0 44px; }
+ .evt-head-text { flex: 1; min-width: 0; }
+ .evt-socials { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 4px; }
+ .evt-socials a { font-size: 10px; padding: 2px 7px; border-radius: 4px; background: #1e1e2c;
+ border: 1px solid #2a2a3c; color: #cbd5e1; }
+ .evt-socials a:hover { background: #26263a; color: #fff; }
+ .evt-pool { font-size: 10px; color: #9a8cff; margin-top: 4px; }
.evt-row { display: flex; justify-content: space-between; gap: 6px; align-items: baseline; }
.evt-kind { font-size: 10px; text-transform: uppercase; letter-spacing: 0.06em; color: var(--muted); }
.evt-tier { font-size: 10px; color: #fbbf24; }
@@ -178,16 +237,11 @@
<option value="mega">Mega only</option>
</select>
<div id="ctl-avatar-wrap">
- <select id="ctl-avatar" title="Avatar">
- <optgroup label="Defaults">
- <option value="/avatars/cz.glb">CZ avatar</option>
- <option value="/avatars/default.glb">Default avatar</option>
- </optgroup>
- <optgroup label="Community" id="ctl-avatar-community" hidden></optgroup>
- <optgroup label="My Agents" id="ctl-avatar-mine" hidden></optgroup>
- <option value="custom">Custom URL…</option>
- </select>
- <input id="ctl-avatar-url" type="text" placeholder="https://…/avatar.glb" />
+ <button id="ctl-avatar-btn" type="button" aria-haspopup="dialog" aria-expanded="false" title="Choose avatar">
+ <span class="avatar-thumb" id="ctl-avatar-thumb" aria-hidden="true"></span>
+ <span class="avatar-name" id="ctl-avatar-label">Avatar</span>
+ <span class="avatar-caret" aria-hidden="true">▾</span>
+ </button>
</div>
<button id="ctl-narrate" class="toggle" type="button" data-on="1" title="Toggle agent narration">🔊 Narration</button>
</div>
@@ -210,13 +264,33 @@
</div>
</aside>
</main>
+ <div class="pf-modal-backdrop" id="avatar-picker" data-open="false" role="dialog" aria-modal="true" aria-labelledby="avatar-picker-title">
+ <div class="pf-modal" role="document">
+ <div class="pf-modal-head">
+ <h2 id="avatar-picker-title">Choose an avatar</h2>
+ <span class="spacer"></span>
+ <button class="pf-modal-close" type="button" aria-label="Close" data-picker-close>×</button>
+ </div>
+ <div class="pf-tabs" role="tablist">
+ <button class="pf-tab" role="tab" type="button" data-tab="defaults" aria-selected="true">Defaults</button>
+ <button class="pf-tab" role="tab" type="button" data-tab="community" aria-selected="false">Community<span class="badge" id="tab-count-community"></span></button>
+ <button class="pf-tab" role="tab" type="button" data-tab="mine" aria-selected="false">My Agents<span class="badge" id="tab-count-mine"></span></button>
+ </div>
+ <div class="pf-toolbar">
+ <input type="search" id="picker-search" placeholder="Search by name…" autocomplete="off" />
+ <div class="custom-row">
+ <input type="url" id="picker-custom-url" placeholder="https://…/avatar.glb" />
+ <button type="button" id="picker-custom-go">Use URL</button>
+ </div>
+ </div>
+ <div class="pf-body" id="picker-body" role="tabpanel"></div>
+ </div>
+ </div>
<script>
const url = new URL(location.href);
const $ = (id) => document.getElementById(id);
const iframe = $('agent');
- const PRESET_AVATARS = ['/avatars/cz.glb', '/avatars/default.glb'];
- const PRESIGN_PREFIX = 'mine:'; // option value sentinel — resolves to a presigned URL on selection
const params = {
asset: url.searchParams.get('asset') || '',
mint: url.searchParams.get('mint') || '',
@@ -232,53 +306,285 @@
$('ctl-tier').value = params.minTier;
$('ctl-narrate').dataset.on = params.narrate ? '1' : '0';
- // Init avatar picker
- const avatarSelect = $('ctl-avatar');
- const avatarUrlInput = $('ctl-avatar-url');
- if (PRESET_AVATARS.includes(params.avatar)) {
- avatarSelect.value = params.avatar;
- } else {
- avatarSelect.value = 'custom';
- avatarUrlInput.value = params.avatar;
- avatarUrlInput.classList.add('visible');
- }
- avatarSelect.addEventListener('change', async () => {
- const v = avatarSelect.value;
- if (v === 'custom') {
- avatarUrlInput.classList.add('visible');
- avatarUrlInput.focus();
+ // ── Avatar picker ────────────────────────────────────────────────────
+ const DEFAULT_AVATARS = [
+ { url: '/avatars/cz.glb', name: 'CZ', sub: 'Default narrator', emoji: '🟡' },
+ { url: '/avatars/default.glb', name: 'Default', sub: 'Generic agent', emoji: '🤖' },
+ ];
+
+ const picker = {
+ modal: $('avatar-picker'),
+ body: $('picker-body'),
+ search: $('picker-search'),
+ customUrl: $('picker-custom-url'),
+ customGo: $('picker-custom-go'),
+ tabs: Array.from(document.querySelectorAll('.pf-tab')),
+ trigger: $('ctl-avatar-btn'),
+ label: $('ctl-avatar-label'),
+ thumb: $('ctl-avatar-thumb'),
+ activeTab: 'defaults',
+ query: '',
+ loaded: { defaults: true, community: false, mine: false },
+ loading: { community: false, mine: false },
+ data: { defaults: DEFAULT_AVATARS.map((a) => ({ ...a, _kind: 'default' })), community: [], mine: [] },
+ cursor: { community: null, mine: null },
+ hasMore: { community: false, mine: false },
+ authed: null, // null = unknown, true/false after first /api/avatars probe
+ lastFocus: null,
+ };
+
+ function openPicker() {
+ picker.lastFocus = document.activeElement;
+ picker.modal.dataset.open = 'true';
+ picker.trigger.setAttribute('aria-expanded', 'true');
+ document.body.style.overflow = 'hidden';
+ renderPickerBody();
+ // Pre-fetch lists for every tab so badges and switching feel instant.
+ ensureLoaded('community');
+ ensureLoaded('mine');
+ setTimeout(() => picker.search.focus(), 30);
+ }
+ function closePicker() {
+ picker.modal.dataset.open = 'false';
+ picker.trigger.setAttribute('aria-expanded', 'false');
+ document.body.style.overflow = '';
+ picker.lastFocus?.focus?.();
+ }
+ picker.trigger.addEventListener('click', openPicker);
+ picker.modal.addEventListener('click', (e) => {
+ if (e.target === picker.modal || e.target.closest('[data-picker-close]')) closePicker();
+ });
+ document.addEventListener('keydown', (e) => {
+ if (e.key === 'Escape' && picker.modal.dataset.open === 'true') closePicker();
+ });
+
+ picker.tabs.forEach((tab) => {
+ tab.addEventListener('click', () => {
+ picker.tabs.forEach((t) => t.setAttribute('aria-selected', String(t === tab)));
+ picker.activeTab = tab.dataset.tab;
+ renderPickerBody();
+ ensureLoaded(picker.activeTab);
+ });
+ });
+
+ picker.search.addEventListener('input', (e) => {
+ picker.query = e.target.value.trim().toLowerCase();
+ renderPickerBody();
+ });
+
+ picker.customGo.addEventListener('click', () => useCustomUrl());
+ picker.customUrl.addEventListener('keydown', (e) => { if (e.key === 'Enter') useCustomUrl(); });
+
+ function useCustomUrl() {
+ const v = picker.customUrl.value.trim();
+ if (!v) return;
+ try { new URL(v, location.href); } catch { alert('That does not look like a valid URL.'); return; }
+ picker.customUrl.value = '';
+ selectAvatar({ url: v, name: 'Custom URL', sub: shortenUrl(v) });
+ }
+
+ function shortenUrl(u) {
+ try { const x = new URL(u, location.href); return x.host + x.pathname.split('/').slice(-1)[0]; }
+ catch { return u.slice(0, 40); }
+ }
+
+ async function ensureLoaded(tab) {
+ if (tab === 'defaults' || picker.loaded[tab] || picker.loading[tab]) return;
+ picker.loading[tab] = true;
+ renderPickerBody();
+ try {
+ if (tab === 'community') {
+ const r = await fetch('/api/avatars/public?limit=48');
+ if (!r.ok) throw new Error('http ' + r.status);
+ const data = await r.json();
+ picker.data.community = (data.avatars || []).filter((a) => a.model_url).map((a) => ({
+ id: a.id,
+ url: a.model_url,
+ name: a.name || a.slug || 'untitled',
+ sub: a.description ? a.description.slice(0, 60) : 'community',
+ thumbnail_url: a.thumbnail_url,
+ visibility: a.visibility,
+ _kind: 'community',
+ }));
+ picker.cursor.community = data.next_cursor;
+ picker.hasMore.community = !!data.next_cursor;
+ updateTabBadge('community', picker.data.community.length + (picker.hasMore.community ? '+' : ''));
+ } else if (tab === 'mine') {
+ const r = await fetch('/api/avatars?limit=100', { credentials: 'include' });
+ if (r.status === 401) { picker.authed = false; picker.loaded.mine = true; return; }
+ picker.authed = true;
+ if (!r.ok) throw new Error('http ' + r.status);
+ const data = await r.json();
+ picker.data.mine = (data.avatars || []).map((a) => ({
+ id: a.id,
+ url: a.model_url, // null for private — we'll presign on click
+ name: a.name || a.slug || 'untitled',
+ sub: (a.visibility || 'private') + (a.description ? ' · ' + a.description.slice(0, 40) : ''),
+ thumbnail_url: a.thumbnail_url,
+ visibility: a.visibility,
+ needsPresign: !a.model_url,
+ _kind: 'mine',
+ }));
+ picker.cursor.mine = data.next_cursor;
+ picker.hasMore.mine = !!data.next_cursor;
+ updateTabBadge('mine', picker.data.mine.length + (picker.hasMore.mine ? '+' : ''));
+ }
+ picker.loaded[tab] = true;
+ } catch (err) {
+ console.warn('[picker] load failed', tab, err);
+ } finally {
+ picker.loading[tab] = false;
+ renderPickerBody();
+ }
+ }
+
+ async function loadMore(tab) {
+ if (!picker.cursor[tab]) return;
+ picker.loading[tab] = true;
+ renderPickerBody();
+ try {
+ const cursor = encodeURIComponent(picker.cursor[tab]);
+ const endpoint = tab === 'community'
+ ? `/api/avatars/public?limit=48&cursor=${cursor}`
+ : `/api/avatars?limit=100&cursor=${cursor}`;
+ const opts = tab === 'mine' ? { credentials: 'include' } : {};
+ const r = await fetch(endpoint, opts);
+ if (!r.ok) throw new Error('http ' + r.status);
+ const data = await r.json();
+ const mapper = tab === 'community'
+ ? (a) => ({ id: a.id, url: a.model_url, name: a.name || a.slug || 'untitled', sub: a.description ? a.description.slice(0, 60) : 'community', thumbnail_url: a.thumbnail_url, visibility: a.visibility, _kind: 'community' })
+ : (a) => ({ id: a.id, url: a.model_url, name: a.name || a.slug || 'untitled', sub: (a.visibility || 'private') + (a.description ? ' · ' + a.description.slice(0, 40) : ''), thumbnail_url: a.thumbnail_url, visibility: a.visibility, needsPresign: !a.model_url, _kind: 'mine' });
+ const incoming = (data.avatars || []).filter((a) => tab === 'mine' || a.model_url).map(mapper);
+ picker.data[tab] = picker.data[tab].concat(incoming);
+ picker.cursor[tab] = data.next_cursor;
+ picker.hasMore[tab] = !!data.next_cursor;
+ updateTabBadge(tab, picker.data[tab].length + (picker.hasMore[tab] ? '+' : ''));
+ } catch (err) {
+ console.warn('[picker] loadMore failed', tab, err);
+ } finally {
+ picker.loading[tab] = false;
+ renderPickerBody();
+ }
+ }
+
+ function updateTabBadge(tab, text) {
+ const el = document.getElementById('tab-count-' + tab);
+ if (el) el.textContent = text ? ' (' + text + ')' : '';
+ }
+
+ function renderPickerBody() {
+ const body = picker.body;
+ const tab = picker.activeTab;
+ body.innerHTML = '';
+
+ if (tab === 'mine' && picker.authed === false) {
+ body.innerHTML = `<div class="pf-status">
+ Sign in to use avatars you've created.
+ <br><a class="cta" href="/login?next=${encodeURIComponent(location.pathname + location.search)}">Sign in</a>
+ </div>`;
return;
}
- avatarUrlInput.classList.remove('visible');
- if (v.startsWith(PRESIGN_PREFIX)) {
- const id = v.slice(PRESIGN_PREFIX.length);
- const opt = avatarSelect.selectedOptions[0];
- const prevLabel = opt?.textContent;
- if (opt) opt.textContent = (prevLabel || '') + ' (loading…)';
+ if (picker.loading[tab] && !picker.data[tab].length) {
+ body.innerHTML = `<div class="pf-status">Loading…</div>`;
+ return;
+ }
+
+ let items = picker.data[tab];
+ if (picker.query) items = items.filter((a) => a.name.toLowerCase().includes(picker.query));
+
+ if (!items.length) {
+ const msg = tab === 'mine'
+ ? `No avatars yet. <br><a class="cta" href="/create">Create your first agent</a>`
+ : picker.query ? `No matches for "${escapeHtml(picker.query)}".` : 'Nothing here yet.';
+ body.innerHTML = `<div class="pf-status">${msg}</div>`;
+ return;
+ }
+
+ const grid = document.createElement('div');
+ grid.className = 'pf-grid';
+ items.forEach((a) => grid.appendChild(renderCard(a)));
+ body.appendChild(grid);
+
+ if (picker.hasMore[tab]) {
+ const btn = document.createElement('button');
+ btn.className = 'pf-loadmore';
+ btn.textContent = picker.loading[tab] ? 'Loading…' : 'Load more';
+ btn.disabled = picker.loading[tab];
+ btn.addEventListener('click', () => loadMore(tab));
+ body.appendChild(btn);
+ }
+ }
+
+ function renderCard(a) {
+ const card = document.createElement('button');
+ card.type = 'button';
+ card.className = 'pf-card';
+ const isSelected = a.url && a.url === params.avatar;
+ if (isSelected) card.dataset.selected = 'true';
+ const thumbStyle = a.thumbnail_url ? `style="background-image:url('${attr(a.thumbnail_url)}')"` : '';
+ const fallback = a.thumbnail_url ? '' : (a.emoji || '◇');
+ const visTag = a._kind === 'mine' && a.visibility
+ ? `<span class="vis-tag ${a.visibility === 'private' ? 'private' : ''}">${escapeHtml(a.visibility)}</span>`
+ : '';
+ card.innerHTML = `
+ <div class="thumb" ${thumbStyle}>${fallback}${visTag}<span class="selected-mark">✓</span></div>
+ <div class="meta">
+ <div class="name">${escapeHtml(a.name)}</div>
+ <div class="sub">${escapeHtml(a.sub || '')}</div>
+ </div>
+ `;
+ card.addEventListener('click', () => selectAvatar(a, card));
+ return card;
+ }
+
+ async function selectAvatar(a, cardEl) {
+ let resolvedUrl = a.url;
+ if (a.needsPresign) {
+ if (cardEl) { cardEl.style.opacity = '0.5'; cardEl.style.pointerEvents = 'none'; }
try {
- const r = await fetch(`/api/avatars/${encodeURIComponent(id)}`, { credentials: 'include' });
- if (!r.ok) throw new Error('fetch failed');
+ const r = await fetch(`/api/avatars/${encodeURIComponent(a.id)}`, { credentials: 'include' });
+ if (!r.ok) throw new Error('http ' + r.status);
const { avatar } = await r.json();
- const url = avatar?.url || avatar?.model_url;
- if (!url) throw new Error('no url');
- params.avatar = url;
- } catch {
- if (opt) opt.textContent = prevLabel;
- alert('Could not load that avatar.');
+ resolvedUrl = avatar?.url || avatar?.model_url;
+ if (!resolvedUrl) throw new Error('no url');
+ } catch (err) {
+ alert('Could not load that avatar (' + (err.message || 'error') + ').');
+ if (cardEl) { cardEl.style.opacity = ''; cardEl.style.pointerEvents = ''; }
return;
- } finally {
- if (opt && prevLabel) opt.textContent = prevLabel;
}
- } else {
- params.avatar = v;
}
+ params.avatar = resolvedUrl;
+ updateTriggerLabel(a);
syncURL();
mountAgent();
- });
- avatarUrlInput.addEventListener('change', () => {
- const v = avatarUrlInput.value.trim();
- if (v) { params.avatar = v; syncURL(); mountAgent(); }
- });
+ closePicker();
+ }
+
+ function updateTriggerLabel(a) {
+ picker.label.textContent = a.name || 'Avatar';
+ if (a.thumbnail_url) {
+ picker.thumb.style.backgroundImage = `url('${a.thumbnail_url}')`;
+ picker.thumb.textContent = '';
+ } else {
+ picker.thumb.style.backgroundImage = '';
+ picker.thumb.textContent = '';
+ }
+ }
+
+ // Initial label from URL param
+ (function initTriggerLabel() {
+ const preset = DEFAULT_AVATARS.find((a) => a.url === params.avatar);
+ if (preset) { updateTriggerLabel(preset); return; }
+ updateTriggerLabel({ name: 'Custom', sub: shortenUrl(params.avatar) });
+ // Try to upgrade label once lists load
+ const tryMatch = () => {
+ const all = picker.data.defaults.concat(picker.data.community, picker.data.mine);
+ const m = all.find((a) => a.url === params.avatar);
+ if (m) updateTriggerLabel(m);
+ };
+ ensureLoaded('community').then(tryMatch);
+ ensureLoaded('mine').then(tryMatch);
+ })();
function setStatus(state, label) {
const dot = $('status-dot');
@@ -743,61 +1049,6 @@
mountAgent();
buildAnimChips();
- loadAvatarPickerOptions();
-
- async function loadAvatarPickerOptions() {
- const customOpt = avatarSelect.querySelector('option[value="custom"]');
- const community = $('ctl-avatar-community');
- const mine = $('ctl-avatar-mine');
-
- // Community pool — public avatars, no auth needed
- fetch('/api/avatars/public?limit=50')
- .then((r) => (r.ok ? r.json() : null))
- .then((data) => {
- const list = data?.avatars || [];
- if (!list.length) return;
- for (const a of list) {
- if (!a.model_url) continue;
- const opt = document.createElement('option');
- opt.value = a.model_url;
- opt.textContent = a.name || a.slug || 'untitled';
- community.appendChild(opt);
- }
- if (community.children.length) community.hidden = false;
- ensureSelectedReflected();
- })
- .catch(() => {});
-
- // My Agents — requires session; silently skip if not signed in
- fetch('/api/avatars?limit=100', { credentials: 'include' })
- .then((r) => (r.ok ? r.json() : null))
- .then((data) => {
- const list = data?.avatars || [];
- if (!list.length) return;
- for (const a of list) {
- const opt = document.createElement('option');
- // Public/unlisted have a direct CDN URL; private need a presign on selection.
- opt.value = a.model_url ? a.model_url : PRESIGN_PREFIX + a.id;
- const tag = a.visibility === 'private' ? ' · private' : '';
- opt.textContent = (a.name || a.slug || 'untitled') + tag;
- mine.appendChild(opt);
- }
- if (mine.children.length) mine.hidden = false;
- ensureSelectedReflected();
- })
- .catch(() => {});
-
- function ensureSelectedReflected() {
- // If the URL-supplied avatar matches one of the now-loaded options, select it.
- if (avatarSelect.value === 'custom' && PRESET_AVATARS.includes(params.avatar) === false) {
- const match = Array.from(avatarSelect.options).find((o) => o.value === params.avatar);
- if (match) {
- avatarSelect.value = params.avatar;
- avatarUrlInput.classList.remove('visible');
- }
- }
- }
- }
// Auth-aware nav CTA
(function () {
diff --git a/src/agent-skills-pumpfun-watch.js b/src/agent-skills-pumpfun-watch.js
index 09daf0f0d..a9ce2c1c7 100644
--- a/src/agent-skills-pumpfun-watch.js
+++ b/src/agent-skills-pumpfun-watch.js
@@ -21,6 +21,7 @@
import { ACTION_TYPES } from './agent-protocol.js';
import { watchClaims } from './pump/pumpkit-claims.js';
+import { applyReaction, createReactionDispatcher } from './widgets/pumpfun-reactions.js';
const FEED_PATH = '/api/agents/pumpfun-feed';
const TIER_BADGE = { mega: '🔥🔥', influencer: '🔥', notable: '⭐' };
@@ -147,43 +148,33 @@ export function registerPumpFunWatchSkills(skills) {
_state.count = 0;
const protocol = ctx.protocol;
- const speak = (text, sentiment = 0) =>
- protocol?.emit({ type: ACTION_TYPES.SPEAK, payload: { text, sentiment } });
- const emote = (trigger, weight) =>
- protocol?.emit({ type: ACTION_TYPES.EMOTE, payload: { trigger, weight } });
- const gesture = (name, duration = 1500) =>
- protocol?.emit({ type: ACTION_TYPES.GESTURE, payload: { name, duration } });
+ const dispatcher = createReactionDispatcher();
+ const react = (kind, ev) =>
+ dispatcher.dispatch(kind, ev, (reaction) => applyReaction(protocol, reaction));
_state.es.addEventListener('claim', (msg) => {
_state.count++;
const ev = safeJson(msg.data);
if (!ev) return;
- if (ev.first_time_claim) {
- emote('celebration', 0.9);
- speak(
- `First-time claim! ${summarizeClaim(ev)}${ev.ai_take ? ` — ${ev.ai_take}` : ''}`,
- 0.7,
- );
- } else if (ev.fake_claim) {
- emote('concern', 0.7);
- speak(`Fake claim detected: ${summarizeClaim(ev)}`, -0.5);
- } else if (ev.tier) {
- emote('curiosity', 0.5);
- speak(summarizeClaim(ev), 0.2);
- }
+ react('claim', ev);
});
_state.es.addEventListener('graduation', (msg) => {
const ev = safeJson(msg.data);
if (!ev) return;
- gesture('wave', 1500);
- speak(`Graduation: ${ev.symbol || ev.mint || 'a token'} hit PumpAMM.`, 0.6);
+ react('graduation', ev);
+ });
+
+ _state.es.addEventListener('mint', (msg) => {
+ const ev = safeJson(msg.data);
+ if (!ev) return;
+ react('mint', ev);
});
_state.es.addEventListener('error', () => {
// EventSource auto-reconnects; surface only if it permanently closes.
if (_state.es && _state.es.readyState === EventSource.CLOSED) {
- emote('concern', 0.4);
+ protocol?.emit({ type: ACTION_TYPES.EMOTE, payload: { trigger: 'concern', weight: 0.4 } });
_state.es = null;
}
});
diff --git a/src/app.js b/src/app.js
index a1292a4ab..496ea0c36 100644
--- a/src/app.js
+++ b/src/app.js
@@ -1164,6 +1164,21 @@ class App {
}),
);
}
+
+ // Host-page reaction bridge: when the parent /pumpfun.html page
+ // observes a feed event, it can ask the avatar to emote/dance
+ // without having to mount the full widget overlay.
+ if (data.type === 'pumpfun-feed:react' && data.reaction) {
+ try {
+ const proto = window.VIEWER?.agent_protocol || protocol;
+ const r = data.reaction;
+ if (proto && r.emote) proto.emit({ type: 'emote', payload: r.emote });
+ if (proto && r.gesture) proto.emit({ type: 'gesture', payload: r.gesture });
+ if (proto && r.speak && data.speak !== false) {
+ proto.emit({ type: 'speak', payload: r.speak });
+ }
+ } catch {}
+ }
});
}
diff --git a/src/element.js b/src/element.js
index e88cda2bc..bda4806dc 100644
--- a/src/element.js
+++ b/src/element.js
@@ -1523,8 +1523,13 @@ class Agent3DElement extends HTMLElement {
protocol,
manifest: this._manifest,
window,
+ getClips: () => this._listAvailableClips(),
});
this._embedBridge.start();
+ // Push the initial clip list once the model + manifest are settled.
+ // The bridge queues this until the host subscribes; the chip strip on
+ // the parent page reads it from `op:'clips'` events without polling.
+ queueMicrotask(() => this._embedBridge?.emitClipsChanged());
}
// END:EMBED_BRIDGES
this._loadingEl.hidden = true;
@@ -2369,6 +2374,64 @@ class Agent3DElement extends HTMLElement {
return this._scene?.playClipByName(name, opts);
}
+ /**
+ * Combined animation list available to the loaded model.
+ *
+ * Mirrors the heuristic in `home-act2-viewer.listAvailableClips`:
+ * • If the GLB ships with 3+ non-idle baked clips (e.g. RobotExpressive),
+ * show only those — manifest clips are Mixamo-retargeted to the canonical
+ * Avaturn skeleton and won't bind to a foreign rig.
+ * • Otherwise (humanoid / Avaturn-compatible — CZ, Default, most user
+ * avatars), prefer manifest defs (rich label/icon/loop) and append any
+ * extra baked clips not already covered.
+ *
+ * Returned shape is host-friendly: `{ name, label, icon, loop, source }`.
+ * Empty array if no model loaded yet (host should re-request on `op:'clips'`).
+ *
+ * @returns {Array<{name:string, label:string, icon:string, loop:boolean, source:'glb'|'manifest'}>}
+ */
+ _listAvailableClips() {
+ const sc = this._scene;
+ const am = this._viewer?.animationManager;
+ const baked = (sc?.clips || []).map((c) => c?.name).filter(Boolean);
+ const defs = am?.getAnimationDefs?.() || [];
+
+ const IDLE_RE = /idle/i;
+ const bakedNonIdle = baked.filter((n) => !IDLE_RE.test(n));
+
+ // Skeletal mismatch guard: if the GLB has its own rig+clips, manifest
+ // retargets won't apply — return baked-only.
+ if (bakedNonIdle.length >= 3) {
+ return baked.map((name) => ({
+ name,
+ label: name,
+ icon: '✨',
+ loop: true,
+ source: 'glb',
+ }));
+ }
+
+ const out = [];
+ const seen = new Set();
+ for (const def of defs) {
+ if (!def?.name || seen.has(def.name)) continue;
+ seen.add(def.name);
+ out.push({
+ name: def.name,
+ label: def.label || def.name,
+ icon: def.icon || '✨',
+ loop: def.loop !== false,
+ source: 'manifest',
+ });
+ }
+ for (const name of baked) {
+ if (seen.has(name)) continue;
+ seen.add(name);
+ out.push({ name, label: name, icon: '✨', loop: true, source: 'glb' });
+ }
+ return out;
+ }
+
/**
* Enable the inline avatar-in-chat layout.
* The avatar canvas is visible through a transparent window between the chat
diff --git a/src/embed-action-bridge.js b/src/embed-action-bridge.js
index 0668d4d47..5485a9f94 100644
--- a/src/embed-action-bridge.js
+++ b/src/embed-action-bridge.js
@@ -33,13 +33,20 @@ const OP_TO_ACTION = {
*/
export class EmbedActionBridge {
/**
- * @param {{ protocol: object, avatar?: object, manifest: object, window: Window }} opts
+ * @param {{
+ * protocol: object,
+ * avatar?: object,
+ * manifest: object,
+ * window: Window,
+ * getClips?: () => Array<{name:string, label?:string, icon?:string, loop?:boolean, source?:string}>,
+ * }} opts
*/
- constructor({ protocol, avatar = null, manifest, window: win }) {
+ constructor({ protocol, avatar = null, manifest, window: win, getClips = null }) {
this._protocol = protocol;
this._avatar = avatar; // reserved for future direct avatar control
this._manifest = manifest;
this._win = win;
+ this._getClips = getClips;
this._subscribed = false; // host must explicitly subscribe to receive events
this._evtQueue = []; // events queued before host subscribes
this._running = false;
@@ -55,10 +62,43 @@ export class EmbedActionBridge {
// Announce ready to the parent — triggers the ping/pong handshake
const agentId = this._manifest?.id?.agentId || this._manifest?.agentId || '';
- const capabilities = [...Object.keys(OP_TO_ACTION), 'setAgent', 'ping', 'subscribe'];
+ const capabilities = [...Object.keys(OP_TO_ACTION), 'setAgent', 'ping', 'subscribe', 'listClips'];
this._toParent({ kind: 'event', op: 'ready', payload: { agentId, capabilities } });
}
+ /**
+ * Notify the host that the available clip list has changed (e.g. after a
+ * model swap). Host receives `{ kind:'event', op:'clips', payload:{ clips: [...] } }`.
+ * No-op if the host hasn't subscribed yet — event is queued like other events.
+ */
+ emitClipsChanged() {
+ if (!this._running) return;
+ const clips = this._safeGetClips();
+ const evt = {
+ id: genId(),
+ kind: 'event',
+ op: 'clips',
+ payload: { clips },
+ };
+ if (this._subscribed) {
+ this._toParent(evt);
+ } else {
+ if (this._evtQueue.length >= MAX_QUEUED_EVENTS) this._evtQueue.shift();
+ this._evtQueue.push(evt);
+ }
+ }
+
+ _safeGetClips() {
+ if (typeof this._getClips !== 'function') return [];
+ try {
+ const list = this._getClips();
+ return Array.isArray(list) ? list : [];
+ } catch (err) {
+ console.warn('[embed-action-bridge] getClips failed', err);
+ return [];
+ }
+ }
+
stop() {
if (!this._running) return;
this._running = false;
@@ -131,7 +171,12 @@ export class EmbedActionBridge {
const { op, payload = {} } = msg;
if (op === 'ping') {
- this._reply(msg, { capabilities: [...Object.keys(OP_TO_ACTION), 'subscribe'] });
+ this._reply(msg, { capabilities: [...Object.keys(OP_TO_ACTION), 'subscribe', 'listClips'] });
+ return;
+ }
+
+ if (op === 'listClips') {
+ this._reply(msg, { clips: this._safeGetClips() });
return;
}
diff --git a/src/widgets/pumpfun-feed.js b/src/widgets/pumpfun-feed.js
index fcbe2d863..b69a975f0 100644
--- a/src/widgets/pumpfun-feed.js
+++ b/src/widgets/pumpfun-feed.js
@@ -13,6 +13,8 @@
* - maxCards 1..50
*/
+import { applyReaction, createReactionDispatcher } from './pumpfun-reactions.js';
+
const FEED_PATH = '/api/agents/pumpfun-feed';
const TIER_BADGE = { mega: '🔥🔥', influencer: '🔥', notable: '⭐' };
@@ -58,6 +60,14 @@ export async function mountPumpfunFeed(viewer, config, container, ctx = {}) {
const maxCards = Math.max(1, Math.min(50, config.maxCards || 8));
const protocol = ctx.protocol || (typeof window !== 'undefined' ? window.VIEWER?.agent_protocol : null);
let narrateOn = config.autoNarrate !== false;
+ const dispatcher = createReactionDispatcher();
+ const react = (kind, ev) => {
+ dispatcher.dispatch(kind, ev, (reaction) => {
+ // Even with narration off, still drive emote+gesture so the avatar
+ // reacts visually. `speak` is the only channel gated by narrateOn.
+ applyReaction(protocol, reaction, { speak: narrateOn });
+ });
+ };
const onNarrateToggle = (e) => {
narrateOn = !!e.detail?.on;
@@ -91,7 +101,7 @@ export async function mountPumpfunFeed(viewer, config, container, ctx = {}) {
if (!ev) return;
if (!matchesFocus(ev)) return;
addCard(stack, renderClaim(ev), maxCards);
- if (narrateOn) narrateClaim(protocol, ev);
+ react('claim', ev);
});
es.addEventListener('graduation', (msg) => {
@@ -99,7 +109,17 @@ export async function mountPumpfunFeed(viewer, config, container, ctx = {}) {
if (!ev) return;
if (!matchesFocus(ev)) return;
addCard(stack, renderGraduation(ev), maxCards);
- if (narrateOn) narrateGraduation(protocol, ev);
+ react('graduation', ev);
+ });
+
+ es.addEventListener('mint', (msg) => {
+ const ev = safeJson(msg.data);
+ if (!ev) return;
+ if (!matchesFocus(ev)) return;
+ // Mints don't render their own card in this widget (the card stack is
+ // claim/graduation focused), but they should still tickle the avatar
+ // when something notable lands.
+ react('mint', ev);
});
es.addEventListener('error', () => {
@@ -392,47 +412,6 @@ function cardStyle(bg) {
].join(';');
}
-function narrateClaim(protocol, ev) {
- if (!protocol) return;
- if (ev.first_time_claim) {
- protocol.emit({ type: 'emote', payload: { trigger: 'celebration', weight: 0.9 } });
- // First GitHub-linked claim → silly hip-hop dance
- const danceClip = ev.github_user ? 'silly' : 'celebrate';
- protocol.emit({ type: 'gesture', payload: { name: danceClip, duration: 4000 } });
- protocol.emit({
- type: 'speak',
- payload: {
- text: `First-time claim: ${ev.github_user ? '@' + ev.github_user : 'unknown'}${ev.ai_take ? ' — ' + ev.ai_take : ''}`,
- sentiment: 0.7,
- },
- });
- } else if (ev.fake_claim) {
- protocol.emit({ type: 'emote', payload: { trigger: 'concern', weight: 0.7 } });
- protocol.emit({ type: 'gesture', payload: { name: 'shake', duration: 1500 } });
- protocol.emit({
- type: 'speak',
- payload: { text: `Fake claim from ${ev.github_user || ev.claimer}.`, sentiment: -0.5 },
- });
- } else if (ev.tier === 'mega') {
- protocol.emit({ type: 'emote', payload: { trigger: 'celebration', weight: 0.7 } });
- protocol.emit({ type: 'gesture', payload: { name: 'thriller', duration: 5000 } });
- } else if (ev.tier === 'influencer') {
- protocol.emit({ type: 'emote', payload: { trigger: 'curiosity', weight: 0.5 } });
- protocol.emit({ type: 'gesture', payload: { name: 'taunt', duration: 2500 } });
- }
-}
-
-function narrateGraduation(protocol, ev) {
- if (!protocol) return;
- protocol.emit({ type: 'emote', payload: { trigger: 'celebration', weight: 0.9 } });
- // Graduation = the big one → rumba
- protocol.emit({ type: 'gesture', payload: { name: 'rumba', duration: 6000 } });
- protocol.emit({
- type: 'speak',
- payload: { text: `Migration: ${ev.symbol || ev.name || 'a token'} bonded to PumpAMM.`, sentiment: 0.6 },
- });
-}
-
function escapeHtml(s) {
return String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;', "'": '&#39;' }[c]));
}
diff --git a/src/widgets/pumpfun-reactions.js b/src/widgets/pumpfun-reactions.js
new file mode 100644
index 000000000..86aa7513a
--- /dev/null
+++ b/src/widgets/pumpfun-reactions.js
@@ -0,0 +1,242 @@
+/**
+ * Pump.fun avatar reaction map.
+ *
+ * Given a feed event (mint / claim / graduation), returns the sequence of
+ * protocol actions the avatar should perform: an emote stimulus (drives the
+ * empathy layer), a one-shot gesture clip (visible body language / dance),
+ * and an optional speak line. All clip names map to entries in
+ * /public/animations/manifest.json. Slot names ('celebrate', 'concern',
+ * 'wave', 'shake'…) flow through DEFAULT_ANIMATION_MAP; non-slot names
+ * (e.g. 'rumba', 'thriller', 'silly', 'capoeira', 'taunt', 'kiss') are
+ * resolved by the AnimationManager directly via _playSlot's fallback path.
+ *
+ * Design notes
+ * ─────────────
+ * - Each reaction is a plain { emote, gesture, speak } record so callers can
+ * route it through any combination of channels (full narration vs. silent
+ * gesture-only). This keeps narration toggle and avatar reaction decoupled.
+ * - Durations are returned in milliseconds. agent-avatar's _onGesture
+ * converts to seconds before handing off to the animation manager.
+ * - A single dispatcher (`reactToEvent`) runs the dedupe + cooldown gate so
+ * the host page and the in-iframe widget can both call it without stepping
+ * on each other when both are mounted (e.g. /pumpfun.html host page +
+ * pumpfun-feed widget mounted inside /app).
+ */
+
+/** @typedef {{ emote?: { trigger: string, weight: number },
+ * gesture?: { name: string, duration: number },
+ * speak?: { text: string, sentiment: number },
+ * priority?: number }} Reaction */
+
+const TIER_WEIGHT = { mega: 1.0, influencer: 0.75, notable: 0.5 };
+
+/**
+ * Decide which reaction to play for a given pump.fun event.
+ * Returns null when nothing notable should happen (silent flyby).
+ *
+ * @param {string} kind 'mint' | 'claim' | 'graduation'
+ * @param {object} ev raw event payload from /api/agents/pumpfun-feed
+ * @returns {Reaction|null}
+ */
+export function reactionFor(kind, ev) {
+ if (!ev) return null;
+ if (kind === 'graduation') return graduationReaction(ev);
+ if (kind === 'claim') return claimReaction(ev);
+ if (kind === 'mint') return mintReaction(ev);
+ return null;
+}
+
+function graduationReaction(ev) {
+ const sym = ev.symbol || ev.name || 'a token';
+ // Graduation = the milestone moment. Always celebrate big.
+ // Bigger MC delta gets a longer dance, capped.
+ const initial = num(ev.market_cap_usd_initial ?? ev.initial_market_cap_usd ?? ev.market_cap_at_launch);
+ const current = num(ev.usd_market_cap ?? ev.market_cap_usd ?? ev.market_cap);
+ const multiple = initial && current ? current / initial : 1;
+ const duration = clamp(4500 + Math.log10(Math.max(multiple, 1)) * 1500, 4500, 9000);
+ return {
+ emote: { trigger: 'celebration', weight: 0.95 },
+ gesture: { name: 'rumba', duration },
+ speak: { text: `Migration: ${sym} bonded to PumpAMM.`, sentiment: 0.7 },
+ priority: 90,
+ };
+}
+
+function claimReaction(ev) {
+ if (ev.fake_claim) {
+ return {
+ emote: { trigger: 'concern', weight: 0.75 },
+ gesture: { name: 'shake', duration: 1500 },
+ speak: {
+ text: `Fake claim from ${ev.github_user ? '@' + ev.github_user : shortAddr(ev.claimer)}.`,
+ sentiment: -0.6,
+ },
+ priority: 70,
+ };
+ }
+
+ if (ev.first_time_claim) {
+ // First-claim variants: GitHub-linked → silly hip-hop, raw wallet → celebrate clip.
+ const linked = !!(ev.github_user || ev.github_repo || ev.github_account_age_days != null);
+ const verified = ev.verified ?? ev.signal_verified;
+ const gestureName = linked ? (verified ? 'thriller' : 'silly') : 'celebrate';
+ const sym = ev.token_symbol || ev.symbol;
+ const who = linked ? '@' + ev.github_user : shortAddr(ev.claimer || ev.creator);
+ return {
+ emote: { trigger: 'celebration', weight: 0.95 },
+ gesture: { name: gestureName, duration: 5000 },
+ speak: {
+ text: `First-time claim by ${who}${sym ? ' on $' + sym : ''}${ev.ai_take ? ' — ' + ev.ai_take : ''}.`,
+ sentiment: 0.75,
+ },
+ priority: 85,
+ };
+ }
+
+ // Tiered repeat claims — quieter, no full dance.
+ const tier = ev.tier;
+ if (tier === 'mega') {
+ return {
+ emote: { trigger: 'celebration', weight: 0.7 },
+ gesture: { name: 'taunt', duration: 2500 },
+ priority: 50,
+ };
+ }
+ if (tier === 'influencer') {
+ return {
+ emote: { trigger: 'curiosity', weight: 0.55 },
+ gesture: { name: 'reaction', duration: 1800 },
+ priority: 35,
+ };
+ }
+ if (tier === 'notable') {
+ return {
+ emote: { trigger: 'curiosity', weight: 0.4 },
+ priority: 20,
+ };
+ }
+ return null;
+}
+
+function mintReaction(ev) {
+ // Mints fire constantly. Only react to ones with notable initial buy or
+ // that come pre-tiered, otherwise the avatar would never stop reacting.
+ const initialSol = num(ev.initial_buy_sol);
+ if (ev.tier === 'mega' || (initialSol && initialSol >= 5)) {
+ return {
+ emote: { trigger: 'curiosity', weight: 0.55 },
+ gesture: { name: 'wave', duration: 1500 },
+ priority: 25,
+ };
+ }
+ if (ev.tier === 'influencer' || (initialSol && initialSol >= 1)) {
+ return {
+ emote: { trigger: 'curiosity', weight: 0.35 },
+ priority: 10,
+ };
+ }
+ return null;
+}
+
+/**
+ * Stateful dispatcher: dedupes reactions per (kind,mint), enforces a global
+ * cooldown so a flood of claims doesn't lock the avatar into a 5s loop, and
+ * lets a higher-priority reaction (graduation > first-claim > tier) preempt
+ * a lower one already in flight.
+ *
+ * @param {{ now?: () => number, cooldownMs?: number }} [opts]
+ */
+export function createReactionDispatcher(opts = {}) {
+ const now = opts.now || (() => Date.now());
+ const cooldownMs = opts.cooldownMs ?? 2200;
+ const dedupeWindowMs = 30_000;
+ /** @type {Map<string, number>} */
+ const seen = new Map();
+ let activeUntil = 0;
+ let activePriority = 0;
+
+ return {
+ /**
+ * @param {string} kind
+ * @param {object} ev
+ * @param {(reaction: Reaction) => void} run
+ * @returns {boolean} whether the reaction was dispatched
+ */
+ dispatch(kind, ev, run) {
+ const reaction = reactionFor(kind, ev);
+ if (!reaction) return false;
+
+ const t = now();
+ const key = dedupeKey(kind, ev);
+ if (key) {
+ const last = seen.get(key);
+ if (last != null && t - last < dedupeWindowMs) return false;
+ seen.set(key, t);
+ // Prune: keep map bounded.
+ if (seen.size > 200) {
+ for (const [k, v] of seen) {
+ if (t - v > dedupeWindowMs) seen.delete(k);
+ }
+ }
+ }
+
+ const priority = reaction.priority ?? 0;
+ if (t < activeUntil && priority <= activePriority) return false;
+
+ const dur = reaction.gesture?.duration ?? cooldownMs;
+ activeUntil = t + Math.max(cooldownMs, dur);
+ activePriority = priority;
+ run(reaction);
+ return true;
+ },
+ _state() {
+ return { activeUntil, activePriority, seen };
+ },
+ };
+}
+
+/**
+ * Apply a Reaction by emitting protocol actions. Caller controls which
+ * channels are live via `flags` so a muted host can still drive gestures.
+ *
+ * @param {{ emit: (a: any) => void } | null} protocol
+ * @param {Reaction} reaction
+ * @param {{ emote?: boolean, gesture?: boolean, speak?: boolean }} [flags]
+ */
+export function applyReaction(protocol, reaction, flags = {}) {
+ if (!protocol || !reaction) return;
+ const want = { emote: true, gesture: true, speak: true, ...flags };
+ if (want.emote && reaction.emote) {
+ protocol.emit({ type: 'emote', payload: reaction.emote });
+ }
+ if (want.gesture && reaction.gesture) {
+ protocol.emit({ type: 'gesture', payload: reaction.gesture });
+ }
+ if (want.speak && reaction.speak) {
+ protocol.emit({ type: 'speak', payload: reaction.speak });
+ }
+}
+
+function dedupeKey(kind, ev) {
+ const mint = ev?.mint || ev?.token_mint;
+ if (!mint) return null;
+ if (kind === 'claim') return `claim:${mint}:${ev?.tx_signature || ev?.signature || ev?.claim_number || ''}`;
+ return `${kind}:${mint}`;
+}
+
+function num(x) {
+ if (x == null) return 0;
+ const n = Number(x);
+ return Number.isFinite(n) ? n : 0;
+}
+
+function clamp(v, lo, hi) {
+ return Math.max(lo, Math.min(hi, v));
+}
+
+function shortAddr(s) {
+ const str = String(s || '');
+ if (!str) return 'unknown';
+ if (str.length <= 12) return str;
+ return `${str.slice(0, 4)}…${str.slice(-4)}`;
+}