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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
Wire up the avatar studio Pose tab; add agent-sniper worker scaffolding
nirholasa31b43e6ce18
diff --git a/api/_lib/migrations/20260615020000_agent_sniper.sql b/api/_lib/migrations/20260615020000_agent_sniper.sqlnew file mode 100644index 000000000..d12695d53--- /dev/null+++ b/api/_lib/migrations/20260615020000_agent_sniper.sql@@ -0,0 +1,112 @@+-- Migration: autonomous pump.fun sniper — per-agent strategy + position ledger.+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260615020000_agent_sniper.sql+-- Idempotent.+--+-- The agent-sniper worker (workers/agent-sniper) watches the live PumpPortal+-- feed, scores new mints against a per-agent strategy, and trades from the+-- agent's OWN encrypted Solana wallet. These two tables are the canonical store:+--+-- agent_sniper_strategies — the owner-armed policy (caps, filters, exits, kill).+-- agent_sniper_positions — every open/closed position. This is the sniper's+-- own trade ledger; it is NOT pump_agent_trades, whose mint_id is NOT NULL+-- and FKs to pump_agent_mints — a row sniped mints (launched by strangers)+-- will never have.+--+-- All SOL amounts are stored as lamports (numeric(40,0)) to avoid float drift.++begin;++create table if not exists agent_sniper_strategies (+ id uuid primary key default gen_random_uuid(),+ agent_id uuid not null references agent_identities(id) on delete cascade,+ user_id uuid not null references users(id) on delete cascade,+ enabled boolean not null default false,+ kill_switch boolean not null default false, -- per-agent emergency stop+ network text not null default 'mainnet' check (network in ('mainnet','devnet')),++ -- budget / sizing (lamports)+ daily_budget_lamports numeric(40, 0) not null default 0, -- 0 = nothing armed+ per_trade_lamports numeric(40, 0) not null default 0, -- buy size per snipe+ max_concurrent_positions int not null default 1,+ slippage_bps int not null default 500,+ max_price_impact_pct numeric not null default 10, -- circuit breaker on entry quote++ -- entry filters (null = ignore)+ min_market_cap_usd numeric,+ max_market_cap_usd numeric,+ min_creator_graduated int, -- creator must have >= N graduated coins+ max_creator_launches int, -- reject serial ruggers (too many launches)+ require_socials boolean not null default false,+ require_sol_quote boolean not null default true, -- reject USDC/OTHER-paired coins++ -- exits+ take_profit_pct numeric, -- null = no TP+ stop_loss_pct numeric not null default 30, -- MANDATORY, enforced not-null+ trailing_stop_pct numeric, -- null = no trailing stop+ max_hold_seconds int not null default 1800, -- timeout exit++ created_at timestamptz not null default now(),+ updated_at timestamptz not null default now(),+ unique (agent_id, network),+ constraint agent_sniper_stop_loss_positive check (stop_loss_pct > 0)+);++create index if not exists agent_sniper_strategies_active+ on agent_sniper_strategies (enabled, kill_switch)+ where enabled = true and kill_switch = false;+create index if not exists agent_sniper_strategies_user+ on agent_sniper_strategies (user_id);++create table if not exists agent_sniper_positions (+ id uuid primary key default gen_random_uuid(),+ strategy_id uuid not null references agent_sniper_strategies(id) on delete cascade,+ agent_id uuid not null,+ user_id uuid not null,+ wallet text not null, -- agent solana address+ network text not null default 'mainnet' check (network in ('mainnet','devnet')),+ mint text not null,+ symbol text,+ name text,++ status text not null default 'opening'+ check (status in ('opening','open','closing','closed','failed')),+ exit_reason text+ check (exit_reason in+ ('take_profit','stop_loss','trailing_stop','timeout',+ 'manual','kill_switch','graduated','error')),++ -- entry+ buy_sig text,+ entry_quote_lamports numeric(40, 0), -- SOL spent+ base_amount numeric(40, 0), -- token base units bought+ entry_price_lamports_per_token numeric,+ entry_price_impact_pct numeric,++ -- live tracking+ peak_value_lamports numeric(40, 0), -- high-water mark for trailing stop+ last_value_lamports numeric(40, 0), -- last quoteForSell expectedQuoteOut+ last_quoted_at timestamptz,++ -- exit+ sell_sig text,+ exit_quote_lamports numeric(40, 0), -- SOL received+ realized_pnl_lamports numeric(40, 0), -- exit - entry (signed)+ realized_pnl_pct numeric,++ error text,+ opened_at timestamptz not null default now(),+ closed_at timestamptz,+ -- idempotency: at most one position per mint per agent per network.+ unique (agent_id, mint, network)+);++create index if not exists agent_sniper_positions_open+ on agent_sniper_positions (network, status)+ where status in ('opening','open','closing');+create index if not exists agent_sniper_positions_agent+ on agent_sniper_positions (agent_id, network, opened_at desc);+-- Powers the SSE diff cursor: rows touched since a timestamp, newest first.+create index if not exists agent_sniper_positions_changed+ on agent_sniper_positions (greatest(opened_at, coalesce(closed_at, opened_at), coalesce(last_quoted_at, opened_at)) desc);++commit;diff --git a/pages/avatar-page.html b/pages/avatar-page.htmlindex 59a993e59..d2cb9ff83 100644--- a/pages/avatar-page.html+++ b/pages/avatar-page.html@@ -176,6 +176,209 @@pointer-events: none;}+ /* ── Pose stage (live Three.js scene) ──────────────── */+ /* The Pose tab swaps model-viewer for a real WebGL canvas that fills+ the stage. Toggled by [data-pose] on .av-stage from avatar-page.js. */+ .av-pose-canvas {+ position: absolute;+ inset: 0;+ width: 100% !important;+ height: 100% !important;+ display: block;+ border-radius: inherit;+ touch-action: none;+ }+ .av-stage[data-pose='1'] model-viewer { visibility: hidden; }+ .av-stage:not([data-pose='1']) .av-pose-canvas { display: none; }++ /* ── Pose panel (clip library + transport) ─────────── */+ .av-pose { display: flex; flex-direction: column; gap: 12px; }+ .av-pose-loading {+ color: var(--text-3);+ font-size: 13px;+ line-height: 1.5;+ padding: 8px 2px;+ }+ .av-pose-body { display: flex; flex-direction: column; gap: 12px; }+ .av-pose-transport {+ display: flex;+ align-items: center;+ justify-content: space-between;+ gap: 12px;+ flex-wrap: wrap;+ }+ .av-pose-now { font-size: 13px; font-weight: 600; color: var(--text); }+ .av-pose-controls { display: flex; align-items: center; gap: 12px; flex-wrap: wrap; }+ .av-pose-speed {+ display: flex;+ align-items: center;+ gap: 8px;+ font-size: 12px;+ color: var(--text-2);+ }+ .av-pose-speed input[type='range'] {+ width: 110px;+ accent-color: var(--accent, #7c5cff);+ cursor: pointer;+ }+ .av-pose-speed-val {+ min-width: 40px;+ font-variant-numeric: tabular-nums;+ color: var(--text);+ }+ .av-pose-reset {+ padding: 6px 12px;+ border-radius: 8px;+ border: 1px solid var(--border);+ background: transparent;+ color: var(--text-2);+ font-size: 12px;+ font-weight: 500;+ cursor: pointer;+ transition: background 0.15s ease, color 0.15s ease, border-color 0.15s ease;+ }+ .av-pose-reset:hover { background: var(--hover, rgba(255, 255, 255, 0.06)); color: var(--text); }+ .av-pose-reset:focus-visible { outline: 2px solid var(--accent, #7c5cff); outline-offset: 2px; }+ .av-pose-search {+ width: 100%;+ padding: 9px 12px;+ border-radius: 10px;+ border: 1px solid var(--border);+ background: var(--panel-2, rgba(255, 255, 255, 0.03));+ color: var(--text);+ font-size: 13px;+ }+ .av-pose-search::placeholder { color: var(--text-3); }+ .av-pose-search:focus { outline: none; border-color: var(--accent, #7c5cff); }+ .av-pose-grid {+ display: grid;+ grid-template-columns: repeat(auto-fill, minmax(96px, 1fr));+ gap: 8px;+ }+ .av-pose-clip {+ display: flex;+ flex-direction: column;+ align-items: center;+ gap: 6px;+ padding: 12px 8px;+ border-radius: 12px;+ border: 1px solid var(--border);+ background: var(--panel-2, rgba(255, 255, 255, 0.02));+ color: var(--text-2);+ cursor: pointer;+ transition: background 0.15s ease, color 0.15s ease, border-color 0.15s ease, transform 0.12s ease;+ }+ .av-pose-clip:hover {+ background: var(--hover, rgba(255, 255, 255, 0.06));+ color: var(--text);+ transform: translateY(-1px);+ }+ .av-pose-clip:focus-visible { outline: 2px solid var(--accent, #7c5cff); outline-offset: 2px; }+ .av-pose-clip.is-active {+ border-color: var(--accent, #7c5cff);+ background: color-mix(in srgb, var(--accent, #7c5cff) 16%, transparent);+ color: var(--text);+ }+ .av-pose-clip-icon { font-size: 22px; line-height: 1; }+ .av-pose-clip-label { font-size: 11px; font-weight: 500; text-align: center; }+ @media (prefers-reduced-motion: reduce) {+ .av-pose-clip:hover { transform: none; }+ }++ /* ── Animation control bar ─────────────────────────── */+ .av-anim-bar {+ position: absolute;+ left: 50%;+ bottom: 18px;+ transform: translateX(-50%) translateY(6px);+ display: flex;+ align-items: center;+ gap: 8px;+ max-width: calc(100% - 32px);+ padding: 6px 8px 6px 6px;+ border: 1px solid var(--border);+ border-radius: 999px;+ background: color-mix(in srgb, var(--panel) 78%, transparent);+ backdrop-filter: blur(14px) saturate(1.4);+ -webkit-backdrop-filter: blur(14px) saturate(1.4);+ box-shadow: 0 10px 30px -12px rgba(0, 0, 0, 0.55);+ opacity: 0;+ pointer-events: none;+ transition: opacity 0.25s ease, transform 0.25s ease;+ z-index: 4;+ }+ .av-anim-bar[data-visible='1'] {+ opacity: 1;+ pointer-events: auto;+ transform: translateX(-50%) translateY(0);+ }+ .av-anim-toggle {+ flex: 0 0 auto;+ display: inline-flex;+ align-items: center;+ justify-content: center;+ width: 34px;+ height: 34px;+ border-radius: 50%;+ border: none;+ background: var(--text);+ color: var(--bg);+ cursor: pointer;+ transition: transform 0.15s ease, opacity 0.15s ease;+ }+ .av-anim-toggle:hover { transform: scale(1.06); }+ .av-anim-toggle:active { transform: scale(0.96); }+ .av-anim-toggle:focus-visible {+ outline: 2px solid var(--accent, #7c5cff);+ outline-offset: 2px;+ }+ .av-anim-toggle svg { width: 15px; height: 15px; display: block; }+ .av-anim-clips {+ display: flex;+ align-items: center;+ gap: 4px;+ overflow-x: auto;+ scrollbar-width: none;+ -webkit-overflow-scrolling: touch;+ padding-right: 4px;+ }+ .av-anim-clips::-webkit-scrollbar { display: none; }+ .av-anim-clip {+ flex: 0 0 auto;+ padding: 6px 13px;+ border-radius: 999px;+ border: 1px solid transparent;+ background: transparent;+ color: var(--text-2);+ font-size: 12px;+ font-weight: 500;+ white-space: nowrap;+ cursor: pointer;+ transition: background 0.15s ease, color 0.15s ease, border-color 0.15s ease;+ }+ .av-anim-clip:hover { background: var(--hover, rgba(255, 255, 255, 0.06)); color: var(--text); }+ .av-anim-clip:focus-visible {+ outline: 2px solid var(--accent, #7c5cff);+ outline-offset: 1px;+ }+ .av-anim-clip.is-active {+ background: var(--text);+ color: var(--bg);+ }+ .av-anim-label {+ flex: 0 0 auto;+ padding: 0 10px 0 4px;+ font-size: 12px;+ font-weight: 500;+ color: var(--text-2);+ letter-spacing: 0.01em;+ white-space: nowrap;+ }+ @media (prefers-reduced-motion: reduce) {+ .av-anim-bar { transition: none; }+ .av-anim-toggle:hover { transform: none; }+ }+.av-meta-strip {display: flex;gap: 18px;diff --git a/public/gallery/gallery.css b/public/gallery/gallery.cssindex 0f68d0394..70915c515 100644--- a/public/gallery/gallery.css+++ b/public/gallery/gallery.css@@ -431,11 +431,6 @@ body.gallery-page {--progress-bar-color: rgba(255, 255, 255, 0.4);--progress-bar-height: 2px;}-.gallery-card-views {- font-size: 11px;- color: rgba(255, 255, 255, 0.5);- font-variant-numeric: tabular-nums;-}.gallery-card-body {display: flex;flex-direction: column;diff --git a/public/gallery/gallery.js b/public/gallery/gallery.jsindex 50ac274c1..5b97e11f7 100644--- a/public/gallery/gallery.js+++ b/public/gallery/gallery.js@@ -270,13 +270,6 @@ function updateStats() {state.total != null ? state.total.toLocaleString() : state.totalLoaded.toLocaleString();}-function formatCompact(n) {- if (n < 1000) return String(n);- if (n < 1_000_000) return (n / 1000).toFixed(n < 10_000 ? 1 : 0).replace(/\.0$/, '') + 'k';- if (n < 1_000_000_000) return (n / 1_000_000).toFixed(1).replace(/\.0$/, '') + 'M';- return (n / 1_000_000_000).toFixed(1).replace(/\.0$/, '') + 'B';-}-function renderTags() {const tags = [...state.loadedTags].sort((a, b) => a.localeCompare(b));if (!tags.length && !state.tag) {@@ -307,7 +300,6 @@ function renderCard(a) {const thumbSrc = a.thumbnail_url || `/api/avatars/${encodeURIComponent(a.id)}/og`;const altText = a.alt_text || a.name || 'Avatar';- const views = a.view_count != null ? Number(a.view_count) : 0;const created = formatRelative(a.created_at);const thumbContent = glbUrl@@ -336,8 +328,6 @@ function renderCard(a) {.map((t) => `<span class="gallery-card-tag">${escapeHtml(t)}</span>`).join('');- const viewsLabel = views >= 1 ? `${formatCompact(views)} view${views === 1 ? '' : 's'}` : '';-const onchainBadge = window.twsOnchainBadge?.onchainBadgeHTML? window.twsOnchainBadge.onchainBadgeHTML(a, { link: false, showChain: true, size: 'sm' }): '';@@ -355,7 +345,6 @@ function renderCard(a) {${tagChips ? `<div class="gallery-card-tags">${tagChips}</div>` : ''}<div class="gallery-card-foot"><span class="gallery-card-meta">- ${viewsLabel ? `<span class="gallery-card-views">${escapeHtml(viewsLabel)}</span>` : ''}<span title="${escapeAttr(new Date(a.created_at || Date.now()).toLocaleString())}">${escapeHtml(created)}</span></span><div class="gallery-card-actions">diff --git a/src/avatar-page.js b/src/avatar-page.jsindex 98c051e88..97ca39752 100644--- a/src/avatar-page.js+++ b/src/avatar-page.js@@ -13,6 +13,7 @@ import { fbxFromUrl } from './remesh-convert.js';import { log } from './shared/log.js';import { emptyStateHTML, errorStateHTML } from './shared/state-kit.js';import { mountViewSwitcher } from './view-switcher.js';+import { PoseStage, loadPoseManifest } from './avatar-pose.js';const ATTACHED_KEY_PREFIX = 'avatar_attached_v1:';@@ -311,6 +312,7 @@ function renderShell(glbUrl) {<nav class="av-tabs" role="tablist"><button class="av-tab active" data-tab="overview" role="tab">Overview</button><button class="av-tab" data-tab="chat" role="tab">Chat</button>+ <button class="av-tab" data-tab="pose" role="tab">Pose</button><button class="av-tab" data-tab="skills" role="tab">Skills</button><button class="av-tab" data-tab="plugins" role="tab">Plugins</button><button class="av-tab" data-tab="embed" role="tab">Embed</button>@@ -351,6 +353,26 @@ function renderShell(glbUrl) {</form></div></div>+ <div class="av-panel" data-panel="pose">+ <div class="av-pose" id="av-pose">+ <div class="av-pose-loading" id="av-pose-loading">Open this tab to load the pose stage.</div>+ <div class="av-pose-body" id="av-pose-body" hidden>+ <div class="av-pose-transport" id="av-pose-transport">+ <span class="av-pose-now" id="av-pose-now">Idle</span>+ <div class="av-pose-controls">+ <label class="av-pose-speed">+ <span>Speed</span>+ <input type="range" id="av-pose-speed" min="0.25" max="2" step="0.05" value="1" aria-label="Playback speed" />+ <span class="av-pose-speed-val" id="av-pose-speed-val">1.0×</span>+ </label>+ <button type="button" class="av-pose-reset" id="av-pose-reset">Reset</button>+ </div>+ </div>+ <input type="search" class="av-pose-search" id="av-pose-search" placeholder="Search poses…" autocomplete="off" aria-label="Search poses" />+ <div class="av-pose-grid" id="av-pose-grid"></div>+ </div>+ </div>+ </div><div class="av-panel" data-panel="skills"><div class="av-list" id="av-skills-list"><div class="av-list-loading">Loading skills…</div>@@ -612,9 +634,176 @@ function activateTab(tab) {document.querySelectorAll('.av-panel').forEach((p) => {p.classList.toggle('active', p.dataset.panel === tab);});+ // The Pose tab swaps the model-viewer stage for a live Three.js scene; every+ // other tab restores it. Driven from here so deep-links and the view switcher+ // enter/leave pose mode correctly too.+ if (tab === 'pose') enterPoseMode();+ else leavePoseMode();return true;}+// ── Pose stage ────────────────────────────────────────────────────────+//+// The Pose tab replaces the model-viewer stage with a live Three.js scene+// (PoseStage) so the avatar can be driven through the shared clip library,+// which model-viewer can't play (most avatar GLBs ship no embedded clips).+// The stage mounts lazily on first open and only renders while visible, so+// the page pays zero GPU cost until someone actually opens the tab.++let poseStage = null;+let poseMode = false;+let poseDefs = null;+let poseControlsBound = false;++async function enterPoseMode() {+ if (poseMode) return;+ poseMode = true;+ const stageEl = $('av-stage');+ if (!stageEl) return;+ stageEl.dataset.pose = '1';++ if (!poseStage) {+ const glbUrl = avatar.model_url || avatar.url;+ if (!glbUrl) {+ showPoseMessage('No 3D model is available for this avatar.');+ return;+ }+ poseStage = new PoseStage(stageEl, { glbUrl });+ poseStage.onChange = (name) => reflectPoseState(name);+ try {+ const { supported } = await poseStage.mount();+ if (!poseMode) {+ // User switched away while the model was still loading.+ poseStage.stop();+ return;+ }+ if (!supported) {+ showPoseMessage(+ 'This avatar’s rig can’t be driven by the motion library — pose playback needs a rigged humanoid skeleton.',+ );+ } else {+ revealPosePanel();+ }+ } catch (err) {+ log.warn('[pose] stage failed to mount', err?.message);+ showPoseMessage('The pose stage could not be loaded. Reload the page to try again.');+ return;+ }+ }+ poseStage.start();+}++function leavePoseMode() {+ if (!poseMode) return;+ poseMode = false;+ poseStage?.stop();+ const stageEl = $('av-stage');+ if (stageEl) delete stageEl.dataset.pose;+}++function showPoseMessage(msg) {+ const loadingEl = $('av-pose-loading');+ if (loadingEl) {+ loadingEl.hidden = false;+ loadingEl.textContent = msg;+ }+ $('av-pose-body')?.setAttribute('hidden', '');+}++function revealPosePanel() {+ const loadingEl = $('av-pose-loading');+ const bodyEl = $('av-pose-body');+ if (loadingEl) loadingEl.hidden = true;+ if (bodyEl) bodyEl.hidden = false;+ renderPoseGrid();+ wirePoseControls();+}++async function renderPoseGrid() {+ const grid = $('av-pose-grid');+ if (!grid) return;+ poseDefs = await loadPoseManifest();+ if (!poseDefs.length) {+ grid.innerHTML = emptyStateHTML({+ compact: true,+ icon: '🎭',+ title: 'No poses available',+ body: 'The motion library could not be loaded. Check your connection and reopen this tab.',+ });+ return;+ }+ grid.innerHTML = poseDefs+ .map(+ (d) => `+ <button type="button" class="av-pose-clip" data-clip="${esc(d.name)}" title="${esc(d.label)}">+ <span class="av-pose-clip-icon" aria-hidden="true">${esc(d.icon || '🎬')}</span>+ <span class="av-pose-clip-label">${esc(d.label)}</span>+ </button>`,+ )+ .join('');+ grid.querySelectorAll('[data-clip]').forEach((btn) => {+ btn.addEventListener('click', () => selectPose(btn.dataset.clip));+ });+ reflectPoseState('idle');+}++async function selectPose(name) {+ if (!poseStage) return;+ try {+ await poseStage.play(name);+ } catch (err) {+ log.warn('[pose] clip failed to play', err?.message);+ }+}++function reflectPoseState(name) {+ $('av-pose-grid')+ ?.querySelectorAll('.av-pose-clip')+ .forEach((b) => b.classList.toggle('is-active', b.dataset.clip === name));+ const now = $('av-pose-now');+ if (now) {+ const def = poseDefs?.find((d) => d.name === name);+ now.textContent = def ? def.label : name || 'Idle';+ }+}++function wirePoseControls() {+ if (poseControlsBound) return;+ poseControlsBound = true;++ const speed = $('av-pose-speed');+ const speedVal = $('av-pose-speed-val');+ const fmtSpeed = (v) => `${v % 1 === 0 ? v.toFixed(1) : String(v)}×`;+ speed?.addEventListener('input', () => {+ const v = Number(speed.value);+ poseStage?.setSpeed(v);+ if (speedVal) speedVal.textContent = fmtSpeed(v);+ });++ $('av-pose-reset')?.addEventListener('click', async () => {+ if (speed) speed.value = '1';+ if (speedVal) speedVal.textContent = '1.0×';+ poseStage?.setSpeed(1);+ try {+ await poseStage?.reset();+ } catch (err) {+ log.warn('[pose] reset failed', err?.message);+ }+ });++ const search = $('av-pose-search');+ search?.addEventListener('input', () => {+ const q = search.value.trim().toLowerCase();+ $('av-pose-grid')+ ?.querySelectorAll('.av-pose-clip')+ .forEach((b) => {+ const def = poseDefs?.find((d) => d.name === b.dataset.clip);+ const hay = `${def?.label || ''} ${def?.name || ''}`.toLowerCase();+ b.style.display = !q || hay.includes(q) ? '' : 'none';+ });+ });+}+function bindTabs() {document.querySelectorAll('.av-tab').forEach((btn) => {btn.addEventListener('click', () => activateTab(btn.dataset.tab));diff --git a/src/avatar-pose.js b/src/avatar-pose.jsnew file mode 100644index 000000000..8b4edd55f--- /dev/null+++ b/src/avatar-pose.js@@ -0,0 +1,246 @@+// Pose stage — a self-contained Three.js surface that drops onto the avatar+// studio page (/avatars/:id) so visitors can drive the avatar through the+// pre-baked motion library instead of staring at a static T-pose.+//+// model-viewer (the default stage) can only play clips embedded in the GLB it+// loaded; most avatars ship none. The clip library in /animations/clips/* is+// authored against the canonical Avaturn skeleton and retargets onto any rigged+// humanoid at runtime via AnimationManager — but that needs a real Three.js+// scene, which is what this module owns. It mounts lazily (first time the Pose+// tab opens) and renders only while visible, so the page pays zero GPU cost+// until someone actually wants to pose.++import {+ Scene,+ PerspectiveCamera,+ WebGLRenderer,+ Box3,+ Vector3,+ Clock,+ HemisphereLight,+ DirectionalLight,+ AmbientLight,+ PMREMGenerator,+ SRGBColorSpace,+ ACESFilmicToneMapping,+} from 'three';+import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';+import { OrbitControls } from 'three/addons/controls/OrbitControls.js';+import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';++import { AnimationManager } from './animation-manager.js';+import { dracoLoader } from './game/avatar-rig.js';+import { log } from './shared/log.js';++const MANIFEST_URL = '/animations/manifest.json';++const _loader = new GLTFLoader();+_loader.setDRACOLoader(dracoLoader);++/**+ * @typedef {{name:string,url:string,label:string,icon:string,loop:boolean}} PoseDef+ */++/**+ * Fetch the pose/animation manifest once. Cached at module scope so reopening+ * the tab (or a second avatar in the same session) never refetches.+ * @returns {Promise<PoseDef[]>}+ */+let _manifestPromise = null;+export function loadPoseManifest() {+ if (!_manifestPromise) {+ _manifestPromise = fetch(MANIFEST_URL, { cache: 'force-cache' })+ .then((r) => (r.ok ? r.json() : []))+ .catch((err) => {+ log.warn('[pose] manifest load failed', err?.message);+ _manifestPromise = null; // allow a later retry+ return [];+ });+ }+ return _manifestPromise;+}++export class PoseStage {+ /**+ * @param {HTMLElement} host container the canvas fills (the av-stage element)+ * @param {{ glbUrl: string }} opts+ */+ constructor(host, { glbUrl }) {+ this.host = host;+ this.glbUrl = glbUrl;++ this.renderer = null;+ this.scene = null;+ this.camera = null;+ this.controls = null;+ this.clock = new Clock();+ this.model = null;+ this.anim = new AnimationManager();++ this._running = false;+ this._frame = 0;+ this._resizeObserver = null;+ this._mounted = false;+ this._disposed = false;++ /** Fired with the active clip name (or null) whenever playback changes. */+ this.onChange = null;+ }++ /**+ * Build the scene, load the avatar, and register the clip library.+ * @returns {Promise<{ supported: boolean }>} supported=false when the rig+ * can't be driven by the canonical clip library (static mesh / non-humanoid).+ */+ async mount() {+ if (this._mounted) return { supported: this.anim.supportsCanonicalClips() };+ this._mounted = true;++ const renderer = new WebGLRenderer({ antialias: true, alpha: true, preserveDrawingBuffer: true });+ renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));+ renderer.outputColorSpace = SRGBColorSpace;+ renderer.toneMapping = ACESFilmicToneMapping;+ renderer.toneMappingExposure = 1.05;+ renderer.domElement.className = 'av-pose-canvas';+ this.renderer = renderer;+ this.host.appendChild(renderer.domElement);++ const scene = new Scene();+ this.scene = scene;++ // Neutral studio environment for physically-based materials, plus a+ // three-point key/fill so the avatar reads with form even on flat GLBs.+ const pmrem = new PMREMGenerator(renderer);+ scene.environment = pmrem.fromScene(new RoomEnvironment(), 0.04).texture;+ pmrem.dispose();+ scene.add(new HemisphereLight(0xffffff, 0x39404d, 0.9));+ const key = new DirectionalLight(0xffffff, 1.5);+ key.position.set(2, 3, 2.4);+ scene.add(key, new AmbientLight(0xffffff, 0.35));++ const w = this.host.clientWidth || 1;+ const h = this.host.clientHeight || 1;+ this.camera = new PerspectiveCamera(35, w / h, 0.01, 100);++ this.controls = new OrbitControls(this.camera, renderer.domElement);+ this.controls.enableDamping = true;+ this.controls.dampingFactor = 0.08;+ this.controls.enablePan = false;+ this.controls.minDistance = 0.6;+ this.controls.maxDistance = 8;+ // Keep the camera above the floor so users can't orbit under the avatar.+ this.controls.maxPolarAngle = Math.PI * 0.92;++ this._resize();+ this._resizeObserver = new ResizeObserver(() => this._resize());+ this._resizeObserver.observe(this.host);++ const gltf = await _loader.loadAsync(this.glbUrl);+ if (this._disposed) return { supported: false };+ this.model = gltf.scene;+ this.model.traverse((n) => { if (n.isMesh) n.frustumCulled = false; });+ scene.add(this.model);+ this._frameModel();++ // Register + retarget the full clip library against this rig.+ this.anim.attach(this.model);+ const defs = await loadPoseManifest();+ this.anim.setAnimationDefs(defs);+ const supported = this.anim.supportsCanonicalClips();+ if (supported) {+ // Embedded clips (if any) come along for free via attach(); the+ // library is what we lazily load. Pre-warm idle so the avatar settles+ // out of bind pose the moment the stage appears.+ this.anim.crossfadeTo('idle', 0).catch(() => {});+ this.anim.onChange = (name) => { try { this.onChange?.(name); } catch {} };+ }++ return { supported };+ }++ /** Frame the avatar: face-on, full body, slightly above mid-height. */+ _frameModel() {+ const box = new Box3().setFromObject(this.model);+ const size = box.getSize(new Vector3());+ const center = box.getCenter(new Vector3());+ const height = size.y || 1.6;++ // Drop the model so its feet sit at y=0, then look at the upper torso.+ this.model.position.y -= box.min.y;+ const target = new Vector3(0, height * 0.55, 0);+ const dist = height * 1.6;+ this.camera.position.set(0, height * 0.62, dist);+ this.camera.near = Math.max(0.01, dist / 100);+ this.camera.far = dist * 20;+ this.camera.updateProjectionMatrix();+ this.controls.target.copy(target);+ this.controls.update();+ }++ /**+ * Play a clip by manifest name. Crossfades from whatever is current so the+ * transition reads smoothly. Honors the def's loop flag.+ * @param {string} name+ * @param {PoseDef} [def]+ */+ async play(name) {+ await this.anim.crossfadeTo(name, 0.25);+ }++ /** 1 = normal; the transport slider drives this. */+ setSpeed(scale) {+ this.anim.setSpeed(scale);+ }++ /** Stop motion and settle back to idle (or bind pose if idle is missing). */+ async reset() {+ await this.anim.crossfadeTo('idle', 0.3);+ }++ /** Begin the render loop. Idempotent. */+ start() {+ if (this._running || this._disposed) return;+ this._running = true;+ this.clock.getDelta(); // discard the gap accumulated while hidden+ const tick = () => {+ if (!this._running) return;+ this._frame = requestAnimationFrame(tick);+ const delta = this.clock.getDelta();+ this.anim.update(delta);+ this.controls.update();+ this.renderer.render(this.scene, this.camera);+ };+ this._frame = requestAnimationFrame(tick);+ }++ /** Pause the render loop (GPU goes quiet) without tearing down state. */+ stop() {+ this._running = false;+ if (this._frame) cancelAnimationFrame(this._frame);+ this._frame = 0;+ }++ _resize() {+ if (!this.renderer || !this.camera) return;+ const w = this.host.clientWidth || 1;+ const h = this.host.clientHeight || 1;+ this.renderer.setSize(w, h, false);+ this.camera.aspect = w / h;+ this.camera.updateProjectionMatrix();+ }++ /** Full teardown — releases the WebGL context and all GPU resources. */+ dispose() {+ this._disposed = true;+ this.stop();+ this._resizeObserver?.disconnect();+ this._resizeObserver = null;+ this.anim.dispose();+ this.scene?.environment?.dispose?.();+ this.renderer?.domElement?.remove();+ this.renderer?.dispose();+ this.renderer = null;+ this.scene = null;+ this.model = null;+ }+}diff --git a/workers/agent-sniper/config.js b/workers/agent-sniper/config.jsnew file mode 100644index 000000000..55b7da518--- /dev/null+++ b/workers/agent-sniper/config.js@@ -0,0 +1,70 @@+// agent-sniper — environment + runtime configuration.+//+// Reads and validates the process environment once at boot. Throws on missing+// REQUIRED vars so a misconfigured worker fails loudly instead of trading with+// half a config. Optional vars get sane, conservative defaults.++function req(name) {+ const v = process.env[name];+ if (!v || !String(v).trim()) {+ throw new Error(`[agent-sniper] missing required env var: ${name}`);+ }+ return v;+}++function num(name, def) {+ const raw = process.env[name];+ if (raw == null || raw === '') return def;+ const n = Number(raw);+ return Number.isFinite(n) ? n : def;+}++function bool(name, def = false) {+ const raw = process.env[name];+ if (raw == null || raw === '') return def;+ return /^(1|true|yes|on)$/i.test(String(raw).trim());+}++export function loadConfig() {+ // DATABASE_URL + JWT_SECRET are consumed transitively by db.js / agent-wallet.js.+ // We assert them here so the failure points at config, not a cryptic decrypt+ // error three layers deep on the first trade.+ req('DATABASE_URL');+ req('JWT_SECRET');++ const network = (process.env.SNIPER_NETWORK || 'mainnet').trim();+ if (network !== 'mainnet' && network !== 'devnet') {+ throw new Error(`[agent-sniper] SNIPER_NETWORK must be mainnet|devnet, got "${network}"`);+ }++ const mode = (process.env.SNIPER_MODE || 'simulate').trim();+ if (mode !== 'live' && mode !== 'simulate') {+ throw new Error(`[agent-sniper] SNIPER_MODE must be live|simulate, got "${mode}"`);+ }++ // Live trading on a public RPC will 429 under the new-mint firehose. Refuse to+ // start live without a real endpoint rather than silently dropping trades.+ if (mode === 'live' && !process.env.SOLANA_RPC_URL && !process.env.HELIUS_API_KEY) {+ throw new Error(+ '[agent-sniper] live mode requires SOLANA_RPC_URL or HELIUS_API_KEY (public RPC will rate-limit)',+ );+ }++ return {+ network,+ mode,+ // Global emergency stop — set SNIPER_GLOBAL_KILL=1 to halt all new buys+ // while still letting the position loop manage/exit open positions.+ globalKill: bool('SNIPER_GLOBAL_KILL', false),+ // Position re-quote / exit-evaluation cadence.+ pollMs: Math.max(1_000, num('SNIPER_POLL_MS', 5_000)),+ // How often the strategy cache is refreshed from the DB.+ strategyRefreshMs: Math.max(5_000, num('SNIPER_STRATEGY_REFRESH_MS', 15_000)),+ // Platform-wide buy throttle — a backstop independent of per-agent caps.+ maxGlobalBuysPerMin: Math.max(0, num('SNIPER_MAX_GLOBAL_BUYS_PER_MIN', 10)),+ // Watchdog: if the feed delivers nothing for this long, re-subscribe.+ feedWatchdogMs: Math.max(30_000, num('SNIPER_FEED_WATCHDOG_MS', 180_000)),+ // Confirmation timeout for a broadcast trade.+ confirmTimeoutMs: Math.max(15_000, num('SNIPER_CONFIRM_TIMEOUT_MS', 60_000)),+ };+}diff --git a/workers/agent-sniper/log.js b/workers/agent-sniper/log.jsnew file mode 100644index 000000000..86845368e--- /dev/null+++ b/workers/agent-sniper/log.js@@ -0,0 +1,19 @@+// agent-sniper — structured logging.+//+// One JSON line per event so the worker's stdout drops straight into the+// existing Cloud Run / Vercel log search ([agent-sniper] prefix) without a+// parser. Secrets (keypairs, encrypted blobs) must NEVER be passed here.++function emit(level, msg, fields) {+ const line = { t: new Date().toISOString(), level, tag: 'agent-sniper', msg };+ if (fields && typeof fields === 'object') Object.assign(line, fields);+ const out = level === 'error' || level === 'warn' ? process.stderr : process.stdout;+ out.write(JSON.stringify(line) + '\n');+}++export const log = {+ info: (msg, fields) => emit('info', msg, fields),+ warn: (msg, fields) => emit('warn', msg, fields),+ error: (msg, fields) => emit('error', msg, fields),+ trade: (msg, fields) => emit('info', msg, { ...fields, event: 'trade' }),+};