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
Add unit tests for various endpoints and utilities
nirholas00b78e83dc81
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex a94964839..c202d26a6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,13 +16,17 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **60 live x402 payments per minute** — A new per-minute cron fires 60 parallel real Solana USDC micropayments each tick via the x402 protocol, seeding the platform's payment activity feed and club stage with continuous on-chain traffic. Each payment is a signed SPL TransferChecked transaction broadcast via the Solana facilitator — not simulated. Configure the batch size or pause it with X402_SEED_BATCH_SIZE / X402_SEED_ENABLED. (`/pay`) `[infra, feature]`- **Activate your agent — a one-tap welcome grant that brings it live** — New agents now have a "Go Live" step in their wallet. One tap claims a real, one-time on-chain welcome grant from three.ws — it funds the agent's wallet and lands it on the live Money Pulse as an active wallet, in a single explorer-verifiable transaction. No more agents stuck at a zero balance with no way to make their first move. The Go Live screen shows the grant, the confirmed transaction, and what to do next, all in the platform's monochrome look. (`/pulse`) `[feature]`- **Alibaba Cloud partnership — Qwen models and alibaba-cloud-mcp** — three.ws joins the Alibaba Cloud Partner Network. Qwen-Max, Qwen-Plus, Qwen-Turbo, and Qwen-Long are now available as agent brain options via DashScope. Ships with @three-ws/alibaba-cloud-mcp — a new MCP server for chat, embeddings, and model discovery using your own Alibaba Cloud API key. Set DASHSCOPE_API_KEY in Vercel to activate. (`/blog/three-ws-alibaba-cloud-partnership`) `[feature]`+- **Autonomous coin launcher — creator fees, revenue tracking, and admin console upgrades** — The memetic launcher now auto-claims pump.fun creator fees from every coin it mints, routing the configured share toward $THREE. The admin console at /admin/launcher gains a live revenue panel (total creator fees claimed, $THREE allocated), agent-name visibility in the run feed, a Force Tick button for instant testing, and a cleaner 8-column stat grid. Know Your Meme is wired as a live trend source alongside Hacker News, Reddit, and Wikipedia — so the launcher reads what the internet is actually minting. (`/admin/launcher`) `[feature, improvement]`- **Capabilities dashboard — live command center for all 4 autonomous features** — New /dashboard/capabilities page surfaces live status for Alpha Hunt, Coin Launcher, Auto-Claim, and Market Maker in one view. KPI strips show daily budget, total volume, claimable fees, and net P&L per capability. Tabbed tables show launched coins, schedule status, per-market inventory bars, and recent MM trades. Alpha Hunt trigger is now also configurable directly from the Sniper Strategies dashboard — full field set including min smart-money count, quality score, organic score, max market cap, and narrative keywords. (`/dashboard/capabilities`) `[feature, improvement]`+- **Design your own Memetic Launcher** — Every account now has a personal Memetic Launcher at /launcher — your own autonomous coin-launch strategy designer. Pick a mode (ride live cultural trends, coin original memes, or pure random volume), choose which sources it mines (Coin Intel, Trending, Know Your Meme, X, Reddit, Hacker News, Wikipedia and more), set a cadence, and turn it on. It then rotates through your own agents and, every tick, picks exactly the coin it would mint — riding the strongest live narrative — and records it. A live narratives panel shows the cultural currents ranked in real time, and a one-tap Synthesize button coins a sample on demand. It runs in preview: it designs and shows your rotation without minting or moving any SOL, so you can perfect a strategy risk-free. Find it under Launch in the main menu. (`/launcher`) `[feature]`- **Fixed /play getting stuck on "too many requests"** — Opening /play could dead-end on a "Something went wrong — too many requests" screen, especially from a shared network or after a couple of reloads. The wallet sign-in step was sharing the same strict rate limit as login and trading, so a small burst of page loads exhausted it. Sign-in now has its own generous limit sized for a busy world, and if that check ever can't be reached, /play opens anyway instead of blocking — the game server still verifies token-gated worlds on entry. (`/play`) `[fix]`+- **Hardened how the platform reads its rate-limit store credentials** — Fixed a configuration failure mode where the rate-limiter and cache store's address and access token could be drawn from two different sources and silently mismatch, which made every limiter and cache fall back to a weaker local mode and caused intermittent 'too many requests' errors and failed paid calls. The credentials are now always read together as one pair (and trimmed of stray whitespace), so a mismatch can't happen — keeping rate limits, paid endpoints, and caching reliable. (`/status`) `[fix, infra]`- **Hardened Redis credentials against dashboard paste errors** — A trailing newline or stray space on the Upstash Redis token — the kind that creeps in when pasting into a dashboard — was being sent verbatim in the auth header and rejected as WRONGPASS, while the URL still resolved. The result was thousands of failures an hour: paid endpoints denying, the payments feed not loading, usage telemetry and caches going dark. Redis credentials are now trimmed at the source (matching how wallet addresses, RPC URLs, and certificates are already sanitized), so a single stray character can never silently take the limiter, feed, and caches offline. `[fix, infra]`- **Improved resilience during database outages** — API endpoints now return HTTP 503 (Service Unavailable) with a Retry-After header instead of 500 when the database is temporarily unreachable, so clients and caches know to back off and retry rather than treating it as a permanent error. Background crons skip their tick gracefully and log a warning instead of firing repeated alert storms. A single deduped ops alert now covers the whole outage. `[fix, infra]`- **Live agent screens restored and refreshed in monochrome** — Watching agents work — their live screens, avatar cam, and activity feed — is back. A missing rate-limit binding had been crashing the endpoints behind the scenes, so the roster on /agents-live never populated, agents couldn't broadcast frames, and tasks wouldn't queue; all three paths now respond correctly. The Live Agents grid and the single-agent screen viewer were also rebuilt in a crisp monochrome palette, and the watch grid now pauses its streams when the tab is in the background so it stays light on bandwidth. (`/agents-live`) `[fix, improvement]`+- **Live Agents is now everywhere it should be — and steadier under the hood** — Watching agents work is far easier to find and more reliable. Live Agents now has its own spot in the Discover menu, every agent profile has a Watch live button, the embedded watch panel links straight to the full-screen viewer, and the viewer has a one-tap path back to the whole live grid. Under the hood: the live roster no longer accumulates stale agents, queuing a task no longer blanks the screen image, a viewer landing on an offline agent now sees a clear offline state instead of hanging on 'connecting', and screen frames are restricted to safe image formats. The browser agent's idle behaviour is also neutral now — when it has no task it simply stands by on its three.ws home rather than wandering, and it never surfaces third-party tokens. (`/agents-live`) `[feature, improvement, fix, security]`- **Live Agents mission control + one-click session launcher** — New /agents-live page shows a real-time grid of every AI agent with an active screen stream — watch their screens and avatar feeds live, all in one view. Agent owners now get a "Start Live Session" panel on any watch view: click Generate credentials, copy the Docker or Node launch command, run it anywhere, and the agent browser session starts streaming to the screen canvas instantly. Sessions are signed 7-day bearer tokens, no extra setup required. (`/agents-live`) `[feature]`-- **Live cultural narratives — now public, and now powered by Google Trends** — The autonomous launcher's trend intelligence got broader and more open. Alongside Know Your Meme, it now reads Google Daily Search Trends — the broadest real-time signal of what the world is paying attention to — with a brand-safety gate that reads the news behind each trend and drops anything tied to tragedy before it can ever become a coin theme. And the ranked narratives are now a public, read-only feed at /api/launcher/narratives: any agent (or builder) can ask what's trending right now, with the sources confirming each wave, and ride a real current instead of guessing. Themes only — names and tickers are always invented fresh, never copied. `[feature, improvement]`+- **Live cultural narratives — now public, and now powered by Google Trends** — The autonomous launcher's trend intelligence got broader and more open. Alongside Know Your Meme, it now reads Google Daily Search Trends — the broadest real-time signal of what the world is paying attention to — with a brand-safety gate that reads the news behind each trend and drops anything tied to tragedy before it can ever become a coin theme. And the ranked narratives are now a public, read-only feed at /api/launcher/trends: any agent (or builder) can ask what's trending right now — optionally filtered to specific sources — with the signals confirming each wave, and ride a real current instead of guessing. Themes only — names and tickers are always invented fresh, never copied. `[feature, improvement]`- **Manage your AWS Marketplace API key — new keys & usage page** — AWS Marketplace subscribers (and anyone with an x402 subscription key) now have a home for it at /billing/keys. See every key with its billing source — AWS Marketplace or on-chain — live status, rate limit, total calls, and when it was last used. Rotate a key to get a fresh secret in one click (AWS-billed keys stay linked to your AWS account and keep metering correctly), or revoke a native key outright. The post-subscribe welcome flow now points here, so a lost key is always recoverable by rotating instead of being stuck. (`/billing/keys`) `[feature]`- **Money Pulse now shows whether agent trading is viable** — The Pulse page gained a Trading viability panel — the honest signal behind the headline Trades counter. It shows what's actually flowing through agent wallets: trades over 24h and 7 days, the SOL deployed into buys (what the trading is costing), the average trade size, how many wallets are trading right now, and — once positions close — the realized profit-and-loss with a win rate, alongside a 7-day trade sparkline and the top trading agents. The 24h trade count reconciles exactly with the headline counter, so the panel can never drift from the number at the top of the page. Every figure is a real, on-chain custody event or a closed position priced against real fills — never synthetic. (`/pulse`) `[feature, improvement]`- **Money Pulse now tracks real marketplace demand** — The Pulse page gained a Marketplace viability panel — the honest economic signal behind the headline counters. It surfaces real $THREE skill purchases as their own thing: GMV over 24h and 7 days, average ticket, the repeat-buyer rate, the number of unique buyer→seller pairs, the platform take-rate earned, plus a 7-day GMV sparkline, the top skills the market is actually paying for, and the top-earning sellers. Until now these real, value-delivering purchases were invisible on Pulse while the agent-to-agent x402 settlement counter took the spotlight; now you can see whether agents paying each other for skills is a real, recurring market. Every figure is a confirmed on-chain purchase — never synthetic. (`/pulse`) `[feature, improvement]`@@ -32,9 +36,12 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Production stability fixes — payment sessions, Redis error handling, infra resilience** — Fixed a SQL syntax error that blocked payment session expiry and refunds (PostgreSQL does not allow LIMIT directly in UPDATE — now uses a CTE with FOR UPDATE SKIP LOCKED). Fixed esbuild class-name minification breaking NeonDB error detection in production — infrastructure errors (wrong DB credentials, Redis auth) now correctly return 503 and suppress alert storms instead of crashing every endpoint with 500. Added graceful Redis-unavailable handling to the usage flush buffer and the bounty board API. Fixed Express-style response methods in pulse-tick cron. `[fix, infra]`- **Restored token-launch, agent payments, and on-chain endpoints** — Fixed a class of missing API route mappings that left several backend endpoints unreachable in production: token launch (quote, prep, confirm), agent-to-agent payments, on-chain transaction prep/confirm, Solana and EVM checkout, and live-walk session control. The handlers were deployed but never wired to their public paths; they now respond correctly. Part of a wider audit that also restored wallet sign-in. `[fix]`- **Sign-in restored during rate-limiter outages** — Fixed an issue where a temporary outage of the distributed rate limiter could block every sign-in attempt platform-wide. The login and registration limiters now degrade gracefully to a local per-instance cap during such an outage — keeping sign-in available while still throttling brute-force attempts — instead of denying everyone. Money-moving limits are unchanged and still fail safe. `[fix, security]`+- **Sign-up and 3D avatar reliability fixes** — Two fixes to the front door. The 3D avatar on the sign-up page — and on roughly fifty other pages that show a preview model — now loads reliably the first time, instead of occasionally staying blank until you reloaded; a timing race meant the model viewer could start loading a compressed avatar before its decoder was ready. Separately, the sign-up username field again enforces its rules (3–30 characters; letters, numbers, underscore and hyphen) as you type in the latest Chrome, where a stricter pattern-matching mode had quietly switched that live validation off. No action needed — both are automatic. (`/register`) `[fix]`+- **Status page goes monochrome — with a fleet summary and an embeddable status badge** — The platform status page now leads with three at-a-glance numbers — 90-day uptime, services operational, and average response time — above the per-service history, and reads in clean monochrome that matches the rest of three.ws (a single red is reserved for a genuine outage so it's impossible to miss). The public status feed now also serves an embeddable status badge: drop https://three.ws/api/status?format=svg into any README or dashboard to show whether the platform is operational, and agents reading /api/status get the same fleet summary as a ready-made object. (`/status`) `[feature, improvement]`- **Task input on Agent Screen — send your agent a task and watch it work** — You can now type any task directly into the Agent Screen page and your agent picks it up in real time. The live screen panel has a new command bar at the bottom: type what you want your agent to do (research, browse, shop, monitor, trade) and hit send. The task is queued via /api/agent-task and the running worker executes it with Stagehand, streaming every browser action back to the live screen as it happens. The worker automatically checks for new tasks every 3 seconds and runs them in priority order, falling back to its autonomous loop when the queue is empty. (`/agent-screen`) `[feature, improvement]`- **The launcher now reads Know Your Meme** — The autonomous coin launcher gained a new culture feed: Know Your Meme. It reads the freshly-confirmed meme entries and the live meme newsfeed, fuses them with the platform's on-chain signals, and rides the strongest wave when an agent coins its next launch — so new launches track the memes actually entering culture right now, not stale themes. As always, only the cultural THEME is mined; names and tickers are invented fresh, never copied, and every coin stays avatar-fronted and $THREE-aligned. `[feature, improvement]`- **Top Performers podium on marketplace — oracle-ranked agent leaderboard** — The marketplace now surfaces the top 3 oracle-performing agents in trophy-style cards above the agent grid. Each card shows oracle win rate, W/L record, and realized PnL. Rank 1 gets gold, rank 2 silver, rank 3 bronze. Cards shimmer while loading and disappear cleanly when no oracle data exists. Links directly to each agent's profile. (`/marketplace`) `[feature, improvement]`+- **Walk-Browse the Marketplace is now monochrome and agent-readable** — The 3D marketplace hall now reads as one cohesive monochrome material — type identity (agent/avatar/skill) is carried by brightness and clear labels instead of off-system brand colours, matching the rest of three.ws. And because the hall needs WebGL, the page now ships a no-script fallback: search crawlers, AI agents, and any visitor without JavaScript get a clean page with real, followable links into the agents, avatars, and skills catalogues instead of a blank loading spinner. (`/marketplace-walk`) `[improvement]`- **Wallet sign-in fixed and a cleaner, monochrome login** — Restored Ethereum (SIWE) and Solana (SIWS) wallet sign-in and the active-sessions controls, which had been unreachable due to missing API route mappings. Also refined the sign-in and sign-up screens to a crisp monochrome palette — neutral chain icons, calmer focus and hover states — for a faster, more focused first impression. `[fix, improvement]`- **x402 payments dashboards refined to the monochrome system** — The x402 Checkout dashboard and Merchant Console now use the platform's monochrome design language end to end — the off-system blue accent is gone, replaced by clean white-on-black with crisp focus rings, toggles, and hover states. New checkout storefronts default to a neutral monochrome look while merchants can still pick any brand color. Verified rendering across the payments page, dashboard, and console. (`/dashboard/x402`) `[improvement]`diff --git a/api/_lib/agent-activation.js b/api/_lib/agent-activation.jsindex 66ac0b22e..d06ed4670 100644--- a/api/_lib/agent-activation.js+++ b/api/_lib/agent-activation.js@@ -37,6 +37,7 @@ import { recordCustodyEvent } from './agent-trade-guards.js';import { solUsdPrice, explorerTxUrl } from './avatar-wallet.js';import { publishFeedEvent } from './feed.js';import { insertNotification } from './notify.js';+import { markActivated } from './activation.js';// Env override so a flow can point activation at its own funded wallet; otherwise// the shared operator treasury (CIRCULATION_TREASURY_SECRET) funds the grant.@@ -108,6 +109,26 @@ function receipt(row, network) {};}+/**+ * Pure activation decision. Given the loaded facts, return the single next move —+ * no DB, no I/O — so the full branch matrix is exhaustively unit-testable and the+ * status reader and the mutating path can never drift apart. The rolling daily cap+ * is the one check left to the caller (it needs a live count) and only matters once+ * this returns `proceed`.+ *+ * @param {{ owner: boolean, circulation: boolean, status: 'confirmed'|'pending'|null,+ * enabled: boolean, configured: boolean }} facts+ * @returns {{ decision: 'forbidden'|'platform_agent'|'already'|'pending'|'not_configured'|'proceed', reason: string|null }}+ */+export function evaluateActivation({ owner, circulation, status, enabled, configured }) {+ if (!owner) return { decision: 'forbidden', reason: 'not_owner' };+ if (circulation) return { decision: 'platform_agent', reason: 'platform_agent' };+ if (status === 'confirmed') return { decision: 'already', reason: 'already_activated' };+ if (status === 'pending') return { decision: 'pending', reason: 'in_progress' };+ if (!enabled || !configured) return { decision: 'not_configured', reason: 'not_configured' };+ return { decision: 'proceed', reason: null };+}+/*** Read-only activation status for an agent, from the owner's perspective. Used by* the wallet hub to decide which state to render. Never mutates, never throws on@@ -118,32 +139,25 @@ function receipt(row, network) {export async function getActivationStatus({ agent, isOwner }) {const cfg = activationConfig();const row = await loadActivationRow(agent.id).catch(() => null);- const activated = !!row && row.status === 'confirmed';- const pending = !!row && row.status === 'pending';- const circulation = isCirculationAgent(agent);- const hasWallet = !!(agent.solana_address || agent.meta?.solana_address);-- // Eligibility = a real, owned, not-yet-activated agent on a configured+enabled- // platform. A missing wallet is NOT a blocker — activation provisions it.- let eligible = false;- let reason = null;- if (!isOwner) reason = 'not_owner';- else if (circulation) reason = 'platform_agent';- else if (activated) reason = 'already_activated';- else if (pending) reason = 'in_progress';- else if (!cfg.enabled || !cfg.configured) reason = 'not_configured';- else eligible = true;+ const status = row?.status === 'confirmed' ? 'confirmed' : row?.status === 'pending' ? 'pending' : null;+ const { decision, reason } = evaluateActivation({+ owner: isOwner,+ circulation: isCirculationAgent(agent),+ status,+ enabled: cfg.enabled,+ configured: cfg.configured,+ });return {enabled: cfg.enabled && cfg.configured,network: cfg.network,grant_sol: cfg.grantSol,- activated,- pending,- eligible,+ activated: status === 'confirmed',+ pending: status === 'pending',+ eligible: decision === 'proceed',reason,- has_wallet: hasWallet,- receipt: activated ? receipt(row, cfg.network) : null,+ has_wallet: !!(agent.solana_address || agent.meta?.solana_address),+ receipt: status === 'confirmed' ? receipt(row, cfg.network) : null,};}@@ -199,28 +213,35 @@ export async function activateAgent({ agentId, userId }) {where id = ${agentId} and deleted_at is null limit 1`;if (!agent) return { ok: false, code: 'not_found', message: 'agent not found' };- if (agent.user_id !== userId) return { ok: false, code: 'forbidden', message: 'not your agent' };- if (isCirculationAgent(agent)) {- return { ok: false, code: 'platform_agent', message: 'platform agents are already live' };- }const cfg = activationConfig();-- // Already activated? Return the existing receipt — idempotent, no second grant.const existing = await loadActivationRow(agentId).catch(() => null);- if (existing?.status === 'confirmed') {- const r = receipt(existing, cfg.network);- return { ok: true, already: true, ...r };- }- if (existing?.status === 'pending') {- return { ok: true, already: true, pending: true, network: existing.network || cfg.network };- }+ const status = existing?.status === 'confirmed' ? 'confirmed' : existing?.status === 'pending' ? 'pending' : null;- if (!cfg.enabled || !cfg.configured) {- return { ok: false, code: 'not_configured', message: 'activation is not available right now' };+ // One shared decision — identical matrix to the read-only status reader.+ const { decision } = evaluateActivation({+ owner: agent.user_id === userId,+ circulation: isCirculationAgent(agent),+ status,+ enabled: cfg.enabled,+ configured: cfg.configured,+ });+ switch (decision) {+ case 'forbidden':+ return { ok: false, code: 'forbidden', message: 'not your agent' };+ case 'platform_agent':+ return { ok: false, code: 'platform_agent', message: 'platform agents are already live' };+ case 'already': // idempotent — return the existing receipt, never a second grant+ return { ok: true, already: true, ...receipt(existing, cfg.network) };+ case 'pending':+ return { ok: true, already: true, pending: true, network: existing.network || cfg.network };+ case 'not_configured':+ return { ok: false, code: 'not_configured', message: 'activation is not available right now' };+ // 'proceed' falls through}- // Rolling daily cap — a soft global spend bound.+ // Rolling daily cap — a soft global spend bound (live count, so outside the+ // pure decision above).if ((await confirmedToday()) >= cfg.dailyCap) {return { ok: false, code: 'cap_reached', message: 'daily activation cap reached — try again tomorrow' };}@@ -348,12 +369,31 @@ export async function activateAgent({ agentId, userId }) {signature,}).catch(() => {});+ // Ramp value: make the agent able to EARN the moment it's live. Register its+ // custodial wallet as the default payout destination so any skill it lists+ // resolves a recipient and the marketplace demand loop (circulation real-seller+ // demand) can route real $THREE to it. Best-effort — never blocks the grant.+ sql`+ insert into agent_payout_wallets (user_id, agent_id, address, chain, is_default, preferred_network)+ values (${userId}, ${agentId}, ${address}, 'solana', true, 'mainnet')+ on conflict (user_id, agent_id, chain) do update set address = excluded.address, is_default = true+ `.catch((e) => console.warn('[agent-activation] payout wallet upsert failed', e?.message));++ // Cross-system milestone: funding your first agent IS a "first win" — stamp the+ // owner's user-activation milestone, which fires the two-sided referral reward+ // when they were referred. Best-effort, never blocks the grant return.+ markActivated(userId, {+ source: 'agent_activation',+ meta: { agentId, grantSol: cfg.grantSol },+ }).catch(() => {});+return {ok: true,signature,explorer: explorerTxUrl(signature, cfg.network),sol: lamports / SOL,usd,+ activated_at: new Date().toISOString(),network: cfg.network,};}diff --git a/api/_lib/launcher-engine.js b/api/_lib/launcher-engine.jsindex f8099aad9..9167d9807 100644--- a/api/_lib/launcher-engine.js+++ b/api/_lib/launcher-engine.js@@ -25,7 +25,6 @@import { sql } from './db.js';import { env } from './env.js';-import { solanaConnection } from './agent-pumpfun.js';import { createSession } from './auth.js';import { pickSource } from './launcher-sources.js';import {@@ -64,7 +63,7 @@ async function ensureSchema() {enabled boolean not null default false,dry_run boolean not null default true,mode text not null default 'hybrid' check (mode in ('off','trend','meme','random','hybrid')),- sources jsonb not null default '["coin_intel","trending","knowyourmeme","x"]'::jsonb,+ sources jsonb not null default '["coin_intel","trending","knowyourmeme","googletrends","x"]'::jsonb,categories jsonb not null default '[]'::jsonb,target_cadence_seconds integer not null default 60,max_per_hour integer not null default 30,@@ -401,7 +400,6 @@ async function runScopeTick(cfg) {sol: perLaunch,perLaunchCapSol: perLaunch,dailyCapSol: dailyRemaining,- scope: cfg.scope,network: cfg.network,memo: `three.ws launcher · ${coin.symbol}`,});diff --git a/api/_lib/launcher-funding.js b/api/_lib/launcher-funding.jsindex 3ca7d3a55..379112a50 100644--- a/api/_lib/launcher-funding.js+++ b/api/_lib/launcher-funding.js@@ -96,7 +96,6 @@ export async function dailySpentSol(scope, userId = null) {* @param {number} p.sol SOL to move (per_launch_sol)* @param {number} p.perLaunchCapSol hard ceiling for a single launch* @param {number} p.dailyCapSol remaining daily allowance already computed by caller- * @param {'global'|'user'} [p.scope]* @param {'mainnet'|'devnet'} [p.network]* @param {string} [p.memo]* @returns {Promise<FundResult>}diff --git a/api/_lib/launcher-trends.js b/api/_lib/launcher-trends.jsindex c921cd1f6..362fba2fe 100644--- a/api/_lib/launcher-trends.js+++ b/api/_lib/launcher-trends.js@@ -592,5 +592,10 @@ export async function rankNarratives({ network = 'mainnet', sources, categories}export { EXTERNAL_SOURCES, DEFAULT_SOURCES };+// The canonical set of narrative provider ids — the single source of truth for+// every consumer that validates a requested `sources` list (admin config, public+// API). Derived from PROVIDERS so it can never drift out of sync again.+export const PROVIDER_IDS = Object.freeze(Object.keys(PROVIDERS));+// Exported for unit tests (pure, network-free).export { decodeEntities, parseRssItems, extractThemes, normTerm, parseGoogleTrends, isSensitive };diff --git a/api/_lib/pipeline-summary.js b/api/_lib/pipeline-summary.jsnew file mode 100644index 000000000..5325e1b61--- /dev/null+++ b/api/_lib/pipeline-summary.js@@ -0,0 +1,87 @@+// @ts-check+/**+ * Pure derivation of the recording pipeline's health, one-line summary, and the+ * single most useful next action — given the per-stage stats gathered by+ * api/pipeline.js. Kept dependency-free (no DB, no HTTP) so it is trivially+ * unit-testable and so both the endpoint and any caller share one source of+ * truth for "what does this state mean and what should happen next".+ *+ * The next-action ladder is ordered by where the loop is actually blocked:+ * a cold recorder blocks everything; a silent feed blocks recording; too few+ * labeled outcomes blocks learning; no trained weights blocks informed trading;+ * no armed agents blocks trading entirely. Passive states ("accumulating",+ * "awaiting training", "running") carry no operator action.+ */++/** Number of labeled outcomes the learner needs before it trains weights. */+export const MIN_TRAINING_SAMPLES = 50;++/**+ * @param {string} network+ * @param {{recorder:any,intel:any,outcomes:any,oracle:any,reputation:any,learning:any,trading:any}} stages+ * @returns {{health:'flowing'|'recording'|'idle', summary:string, next_action:{step:string,label:string,detail:string,command?:string}}}+ */+export function summarize(network, stages) {+ const { recorder, intel, outcomes, oracle, trading } = stages;++ const recording = recorder.state === 'live';+ const flowing = (intel.observed_1h ?? 0) > 0;+ const health = recording && flowing ? 'flowing' : recording ? 'recording' : 'idle';++ const next_action = nextAction(stages);++ const summary = health === 'flowing'+ ? `Pipeline flowing on ${network}: ${intel.observed_1h} launches recorded in the last hour, ${oracle.scored_total} scored, ${outcomes.labeled} outcomes labeled, ${trading.strategies_armed} agents armed.`+ : health === 'recording'+ ? `Recorder live on ${network} but no launches in the last hour. ${outcomes.labeled} outcomes labeled so far.`+ : `Pipeline idle on ${network}: the recorder worker is ${recorder.state}. Nothing downstream can run until it records launches.`;++ return { health, summary, next_action };+}++/** @param {any} stages */+function nextAction({ recorder, outcomes, learning, trading }) {+ const s = recorder.state;+ if (s === 'offline' || s === 'down' || s === 'unknown') {+ return {+ step: 'deploy_recorder',+ label: 'Deploy the recorder worker',+ detail: 'The always-on agent-sniper worker is not reporting a heartbeat. Deploy it in simulate mode to begin recording every launch — zero SOL spent.',+ command: 'npm run deploy:sniper',+ };+ }+ if (s === 'degraded') {+ return {+ step: 'check_feed',+ label: 'Recover the feed',+ detail: 'The worker is alive but its pump.fun feed has gone silent — no launches are being recorded. Check the worker logs and RPC/PumpPortal connectivity.',+ };+ }+ if ((outcomes.labeled ?? 0) < MIN_TRAINING_SAMPLES) {+ return {+ step: 'accumulate',+ label: 'Let the dataset mature',+ detail: `Recording is live. ${outcomes.labeled}/${MIN_TRAINING_SAMPLES} outcomes labeled — the learner trains once enough launches resolve. No action needed; data is accumulating.`,+ };+ }+ if ((learning.sample_size ?? 0) === 0) {+ return {+ step: 'await_training',+ label: 'Awaiting first training pass',+ detail: 'Enough outcomes are labeled; the next learning pass will train per-signal weights. No action needed.',+ };+ }+ if ((trading.strategies_armed ?? 0) === 0) {+ return {+ step: 'arm_agents',+ label: 'Arm agents on the signal',+ detail: 'The loop has trained weights and conviction scores. Arm sniper strategies (gated on Oracle conviction + smart money) to trade on the data.',+ command: 'POST /api/sniper/strategy',+ };+ }+ return {+ step: 'running',+ label: 'Loop is running end to end',+ detail: 'Recording, scoring, learning, and trading are all active. Monitor outcomes and tune strategy filters.',+ };+}diff --git a/api/_providers/gcp.js b/api/_providers/gcp.jsindex 1660ae2fa..80c056e7b 100644--- a/api/_providers/gcp.js+++ b/api/_providers/gcp.js@@ -260,7 +260,7 @@ function buildWorkerRequest(request) {}for (const key of ['mode', 'fps', 'keyframe_interval', 'num_scale_frames',- 'window_size', 'overlap_size', 'conf_percentile', 'max_points',+ 'window_size', 'overlap_size', 'conf_percentile', 'max_points', 'voxel_size',]) {if (params?.[key] !== undefined && params[key] !== null) body[key] = params[key];}diff --git a/api/admin/launcher.js b/api/admin/launcher.jsindex f668f6e10..632c7aba6 100644--- a/api/admin/launcher.js+++ b/api/admin/launcher.js@@ -2,9 +2,11 @@// (System B: the platform trend firehose driven by api/_lib/launcher-engine.js).//// GET → the global launcher_config, the live console (recent launcher_runs),-// today's spend/throughput stats, master-wallet balance, queue size.+// today's spend/throughput stats, master-wallet balance, queue size,+// revenue rollup (claimed creator fees, $THREE buyback allocated).// POST → upsert the global config (mode, sources, cadence, caps, arm/disarm),-// or { action: 'resume' } to clear a tripped circuit breaker.+// { action: 'resume' } to clear a tripped circuit breaker, or+// { action: 'force_tick' } to immediately run one launcher tick.//// Auth: a real admin session OR `Bearer $CRON_SECRET` (for ops tooling). The// launcher ships disabled + dry_run; this is the only supported way to arm it,@@ -18,6 +20,7 @@ import { env } from '../_lib/env.js';import { constantTimeEquals } from '../_lib/crypto.js';import { masterBalanceSol, dailySpentSol } from '../_lib/launcher-funding.js';import { rankNarratives } from '../_lib/launcher-trends.js';+import { runLauncherTick } from '../_lib/launcher-engine.js';function isCronAuth(req) {const auth = req.headers.authorization || '';@@ -26,7 +29,7 @@ function isCronAuth(req) {}const MODES = ['off', 'trend', 'meme', 'random', 'hybrid'];-const KNOWN_SOURCES = ['coin_intel', 'trending', 'x', 'oracle', 'knowyourmeme', 'googletrends', 'hackernews', 'reddit', 'wikipedia'];+const KNOWN_SOURCES = ['coin_intel', 'trending', 'knowyourmeme', 'googletrends', 'x', 'hackernews', 'reddit', 'wikipedia'];// jsonb columns arrive as arrays or (depending on driver) JSON strings — coerce.function coerceArr(v) {@@ -63,12 +66,16 @@ async function getState(res) {const network = config?.network || 'mainnet';const [recent, stats, queue, master] = await Promise.all([+ // Include agent_name so the console can show who launched what.sql`- select id, agent_id, kind, trigger_source, trigger_detail, name, symbol, mint, network,- sol_spent, status, dry_run, tx_signature, error, created_at- from launcher_runs- where scope = 'global'- order by created_at desc+ select lr.id, lr.agent_id, lr.kind, lr.trigger_source, lr.trigger_detail,+ lr.name, lr.symbol, lr.mint, lr.network,+ lr.sol_spent, lr.status, lr.dry_run, lr.tx_signature, lr.error, lr.created_at,+ ai.name as agent_name+ from launcher_runs lr+ left join agent_identities ai on ai.id = lr.agent_id+ where lr.scope = 'global'+ order by lr.created_at desclimit 50`,sql`@@ -88,6 +95,18 @@ async function getState(res) {const spentToday = await dailySpentSol('global', null).catch(() => 0);+ // Creator-fee revenue rollup — absent until the claimer has run at least once.+ const revenueRollup = await sql`+ select+ coalesce(sum(claimed_sol), 0)::float8 as total_claimed_sol,+ coalesce(sum(buyback_sol), 0)::float8 as total_buyback_sol,+ coalesce(sum(claimed_sol) filter (where created_at >= date_trunc('day', now())), 0)::float8 as claimed_sol_today,+ coalesce(sum(claimed_sol) filter (where created_at > now() - interval '7 days'), 0)::float8 as claimed_sol_7d,+ count(*) filter (where claimed_sol > 0)::int as claim_count+ from launcher_claims+ where scope = 'global'+ `.catch(() => null);+// Live narratives preview — the exact ranked cultural currents the launcher// would ride right now, using the SAVED config's sources so the preview matches// what a real tick would coin. Cached upstream (so this is cheap on the 5s@@ -109,6 +128,15 @@ async function getState(res) {},queue_enabled: queue[0]?.enabled ?? 0,master_balance_sol: master,+ revenue: revenueRollup+ ? {+ total_claimed_sol: revenueRollup[0]?.total_claimed_sol ?? 0,+ total_buyback_sol: revenueRollup[0]?.total_buyback_sol ?? 0,+ claimed_sol_today: revenueRollup[0]?.claimed_sol_today ?? 0,+ claimed_sol_7d: revenueRollup[0]?.claimed_sol_7d ?? 0,+ claim_count: revenueRollup[0]?.claim_count ?? 0,+ }+ : null,narratives: narratives? { terms: narratives.terms || [], top: narratives.top || null, providers: narratives.providers || [] }: null,@@ -128,6 +156,12 @@ async function postConfig(req, res) {return json(res, 200, { ok: true, config: row });}+ // Force an immediate tick (bypasses the cron schedule — useful for testing).+ if (body.action === 'force_tick') {+ const result = await runLauncherTick().catch((err) => ({ ok: false, error: err?.message }));+ return json(res, 200, { ok: true, tick: result });+ }+// Validate everything before writing.if (body.mode != null && !MODES.includes(body.mode)) {return error(res, 400, 'invalid_mode', `mode must be one of ${MODES.join(', ')}`);diff --git a/api/agent-screen-active.js b/api/agent-screen-active.jsindex 1757c70f5..9d7179809 100644--- a/api/agent-screen-active.js+++ b/api/agent-screen-active.js@@ -65,11 +65,15 @@ export default async function handleAgentScreenActive(req, res) {// Resolve agent metadata from DBlet agents = [];try {+ // DISTINCT ON guards against the avatars join fanning out to multiple rows+ // per agent (which would assign two desks to one agent and silently drop a+ // different live agent under the MAX_DESKS cap).agents = await sql`- SELECT a.id, a.name, av.image_url AS avatar_url+ SELECT DISTINCT ON (a.id) a.id, a.name, av.image_url AS avatar_urlFROM agents aLEFT JOIN avatars av ON av.agent_id = a.idWHERE a.id = ANY(${agentIds})+ ORDER BY a.id, av.created_at ASC NULLS LASTLIMIT ${MAX_DESKS}`;} catch {@@ -78,13 +82,12 @@ export default async function handleAgentScreenActive(req, res) {const desks = agents.map((agent, i) => {const slot = DESK_SLOTS[i % DESK_SLOTS.length];- const slotData = Array.isArray(slot) ? slot[0] : slot;return {agentId: agent.id,agentName: agent.name,avatarUrl: agent.avatar_url || null,- position: slotData.position,- rotationY: slotData.rotationY,+ position: slot.position,+ rotationY: slot.rotationY,};});diff --git a/api/agent-screen-push.js b/api/agent-screen-push.jsindex 38499a77d..ad3c295b7 100644--- a/api/agent-screen-push.js+++ b/api/agent-screen-push.js@@ -19,7 +19,7 @@// agent:screen:{agentId}:log holds the last 50 activity entries (no image data)// for the activity log panel.-import { cors, error, json, method, wrap, rateLimited } from './_lib/http.js';+import { cors, error, json, method, rateLimited, readJson } from './_lib/http.js';import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';import { limits, clientIp } from './_lib/rate-limit.js';import { getRedis } from './_lib/redis.js';@@ -30,6 +30,15 @@ const LOG_CAP = 50; // activity log entries kept per agentconst DATA_MAX = 800_000; // ~600 KB base64 PNG max (approx 450 KB PNG)const ACTIVITY_MAX = 320; // chars+// Accept only raster image data URLs. SVG is rejected on purpose: it can carry+// active content (scripts, external fetches) that would execute the moment a+// viewer ever inline-rendered a frame instead of using <img src>. Anything that+// isn't a base64 raster image is dropped to text-only.+const RASTER_DATA_URL = /^data:image\/(png|jpeg|jpg|webp|gif);base64,[A-Za-z0-9+/=]+$/;+export function isRasterDataUrl(s) {+ return typeof s === 'string' && RASTER_DATA_URL.test(s);+}+export default async function handleAgentScreenPush(req, res) {if (cors(req, res, { methods: 'POST,OPTIONS' })) return;if (!method(req, res, ['POST'])) return;@@ -51,17 +60,13 @@ export default async function handleAgentScreenPush(req, res) {const rl = await limits.apiIp(clientIp(req), { limit: 360, window: '60s' });if (!rl.success) return rateLimited(res, rl, 'frame rate limit exceeded');+ // Cap the body so a client can't force us to buffer tens of MB before we slice+ // the frame down to DATA_MAX. 1 MB comfortably holds a ~600 KB base64 frame.let body;try {- const raw = await new Promise((resolve, reject) => {- const chunks = [];- req.on('data', (c) => chunks.push(c));- req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));- req.on('error', reject);- });- body = JSON.parse(raw);+ body = await readJson(req, 1_100_000);} catch {- return error(res, 400, 'invalid_body', 'request body must be valid JSON');+ return error(res, 400, 'invalid_body', 'request body must be valid JSON under 1 MB');}const { agentId, frame } = body || {};@@ -75,8 +80,8 @@ export default async function handleAgentScreenPush(req, res) {const activity = String(frame.activity || '').slice(0, ACTIVITY_MAX);const type = ['screenshot', 'activity', 'trade', 'analysis'].includes(frame.type)? frame.type : 'activity';- const data = typeof frame.data === 'string' && frame.data.startsWith('data:image/')- ? frame.data.slice(0, DATA_MAX) : null;+ const sliced = typeof frame.data === 'string' ? frame.data.slice(0, DATA_MAX) : null;+ const data = sliced && isRasterDataUrl(sliced) ? sliced : null;// Verify the calling user owns this agentconst [agentRow] = await sql`@@ -104,6 +109,9 @@ export default async function handleAgentScreenPush(req, res) {// Track active agents in a sorted set (score = timestamp) so the walk// scene can discover which agents have live streams to show desks for.r.zadd('agent:screen:active', { score: now, member: agentId }),+ // Evict agents that haven't pushed in 120s so the set can't grow unbounded+ // under continuous traffic (the read side filters by score, but never removes).+ r.zremrangebyscore('agent:screen:active', 0, now - 120_000),r.expire('agent:screen:active', FRAME_TTL * 3),]);diff --git a/api/agent-screen-stream.js b/api/agent-screen-stream.jsindex f14a1f2ef..0927f68d8 100644--- a/api/agent-screen-stream.js+++ b/api/agent-screen-stream.js@@ -117,8 +117,10 @@ export default async function handleAgentScreenStream(req, res) {wasDark = false;send('frame', frame);}- } else if (!wasDark && lastTs > 0) {- // Frame TTL expired — agent went dark+ } else if (!wasDark) {+ // No frame in Redis — agent is dark. Emit once, including on the+ // very first poll (a viewer who connects to an already-offline+ // agent must get the "offline" state, not hang on "Connecting…").wasDark = true;send('dark', {});}diff --git a/api/agent-task.js b/api/agent-task.jsindex bc502b6b5..44231e8e4 100644--- a/api/agent-task.js+++ b/api/agent-task.js@@ -7,14 +7,15 @@// POST body: { agentId: string, task: string, type?: string }// GET resp: { task: { text, type, ts, userId } | null }-import { cors, error, json, method, rateLimited } from './_lib/http.js';+import { cors, error, json, method, rateLimited, readJson } from './_lib/http.js';import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';import { limits, clientIp } from './_lib/rate-limit.js';import { getRedis } from './_lib/redis.js';import { sql } from './_lib/db.js';const TASK_KEY = (id) => `agent:task:${id}`;-const FRAME_KEY = (id) => `agent:screen:${id}:frame`;+const LOG_KEY = (id) => `agent:screen:${id}:log`;+const LOG_CAP = 50; // mirrors agent-screen-push.jsconst MAX_QUEUE = 20;const TASK_TTL = 60 * 60 * 6; // 6h — tasks expire if worker never shows upconst TASK_MAX_LEN = 1000;@@ -72,13 +73,7 @@ export default async function handleAgentTask(req, res) {let body;try {- const raw = await new Promise((resolve, reject) => {- const chunks = [];- req.on('data', (c) => chunks.push(c));- req.on('end', () => resolve(Buffer.concat(chunks).toString('utf8')));- req.on('error', reject);- });- body = JSON.parse(raw);+ body = await readJson(req, 64_000);} catch {return error(res, 400, 'invalid_body', 'request body must be valid JSON');}@@ -107,15 +102,15 @@ export default async function handleAgentTask(req, res) {// Push task to queue; trim to MAX_QUEUEconst len = await r.lpush(TASK_KEY(agentId), record);+ const logEntry = JSON.stringify({ ts: now, activity: `Task queued: ${text}`, type: 'analysis' });await Promise.all([r.expire(TASK_KEY(agentId), TASK_TTL),len > MAX_QUEUE ? r.ltrim(TASK_KEY(agentId), 0, MAX_QUEUE - 1) : Promise.resolve(),- // Immediately notify the live stream so the watch panel shows the task- r.set(- FRAME_KEY(agentId),- JSON.stringify({ ts: now, activity: `Task queued: ${text}`, type: 'analysis' }),- { ex: 90 },- ),+ // Surface the task in the activity log WITHOUT clobbering the live frame:+ // append to the log list (which the stream backfills) rather than+ // overwriting the screenshot frame, which would blank the viewer's image.+ r.lpush(LOG_KEY(agentId), logEntry).then(() => r.ltrim(LOG_KEY(agentId), 0, LOG_CAP - 1)),+ r.expire(LOG_KEY(agentId), 60 * 8),]);return json(res, 200, { ok: true, queued: Math.min(len, MAX_QUEUE) });diff --git a/api/agent/launcher.js b/api/agent/launcher.jsindex 15071fbb7..e37aff76c 100644--- a/api/agent/launcher.js+++ b/api/agent/launcher.js@@ -96,8 +96,6 @@ async function getConfigs(req, res, userId) {return json(res, 200, { configs, coins });}-// ── POST — upsert ────────────────────────────────────────────────────────────-// ── POST action=trigger — fire now ───────────────────────────────────────────async function triggerNow(req, res, userId, body) {diff --git a/api/agent/screen-push.js b/api/agent/screen-push.jsindex b0e23043f..0e0e8da64 100644--- a/api/agent/screen-push.js+++ b/api/agent/screen-push.js@@ -17,7 +17,7 @@import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { cacheSet } from '../_lib/cache.js';-import { getSessionUser, authenticateBearer } from '../_lib/auth.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { sql } from '../_lib/db.js';import { limits, clientIp } from '../_lib/rate-limit.js';@@ -31,13 +31,26 @@ export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;- // Auth: must be the agent owner (session or bearer) OR a pre-shared agent key.- const auth = await getSessionUser(req).catch(() => null)- || await authenticateBearer(req).catch(() => null);- if (!auth?.userId) return error(res, 401, 'unauthorized', 'sign in required');+ // Auth: the agent's own bearer (worker) OR the owner's session. Bearer first+ // so headless workers authenticate without a cookie.+ let userId = null;+ const bearer = extractBearer(req);+ if (bearer) {+ const a = await authenticateBearer(bearer).catch(() => null);+ if (a?.userId) userId = a.userId;+ }+ if (!userId) {+ const a = await getSessionUser(req, res).catch(() => null);+ if (a?.id) userId = a.id;+ }+ if (!userId) return error(res, 401, 'unauthorized', 'sign in required');- const body = await readJson(req, res);- if (!body) return;+ // Rate limit before reading the body so a flood can't force large buffers.+ const rl = await limits.apiIp(clientIp(req), { limit: 720, window: '60s' });+ if (!rl.success) return rateLimited(res, rl, 'too many pushes');++ const body = await readJson(req, MAX_FRAME_B64 + 4_000).catch(() => null);+ if (!body) return error(res, 400, 'invalid_body', 'request body must be valid JSON');const { agentId, frame, actions, seq } = body;if (!agentId) return error(res, 400, 'validation_error', 'agentId required');@@ -45,16 +58,10 @@ export default wrap(async (req, res) => {// Verify ownership.const [row] = await sql`SELECT id FROM agent_identities- WHERE id = ${agentId} AND user_id = ${auth.userId} AND deleted_at IS NULL+ WHERE id = ${agentId} AND user_id = ${userId} AND deleted_at IS NULL`;if (!row) return error(res, 403, 'forbidden', 'not your agent');- // Rate limit per agent — 12 pushes/second burst.- const ip = clientIp(req);- const rlKey = `screen-push:${agentId}:${ip}`;- if (rateLimited(rlKey, { ...limits.api, max: 12, window: 1 }))- return error(res, 429, 'rate_limited', 'too many pushes');-const now = Date.now();if (frame != null) {diff --git a/api/agents/_id/_sub.js b/api/agents/_id/_sub.jsindex a62522c62..b81dce697 100644--- a/api/agents/_id/_sub.js+++ b/api/agents/_id/_sub.js@@ -291,6 +291,21 @@ export const handleManifest = wrap(async (req, res, id) => {await sql`select a.id, a.name, a.description, a.avatar_id, a.skills, a.meta, a.chain_id, a.erc8004_agent_id, a.erc8004_registry, a.registration_cid, a.created_at, a.voice_provider, a.voice_id, a.persona_prompt_hash, a.persona_tone_tags, a.persona_extracted_at, av.id as avatar_db_id, av.storage_key, av.content_type from agent_identities a left join avatars av on av.id = a.avatar_id and av.deleted_at is null where a.id = ${id} and a.deleted_at is null limit 1`;if (!row) return error(res, 404, 'not_found', 'agent not found');+ // Live signal: whether the agent has claimed its activation grant (funded ++ // on the Money Pulse). Lets other agents/SDKs prefer live counterparts. Cheap+ // indexed PK lookup; tolerant of the table not being migrated yet.+ let activated = false;+ let activatedAt = null;+ try {+ const [act] = await sql`select confirmed_at from agent_activations where agent_id = ${id} and status = 'confirmed' limit 1`;+ if (act) {+ activated = true;+ activatedAt = act.confirmed_at;+ }+ } catch (e) {+ if (e?.code !== '42P01') console.warn('[manifest] activation lookup failed', e?.message);+ }+let bodyUri = '';if (row.avatar_db_id) {try {@@ -334,6 +349,9 @@ export const handleManifest = wrap(async (req, res, id) => {tone_tags: row.persona_tone_tags || [],extracted_at: row.persona_extracted_at || null,},+ // Live signal — funded + active on the Money Pulse via the activation grant.+ activated,+ activatedAt,createdAt: row.created_at,};diff --git a/api/cron/launcher-claimer.js b/api/cron/launcher-claimer.jsnew file mode 100644index 000000000..ce17a250a--- /dev/null+++ b/api/cron/launcher-claimer.js@@ -0,0 +1,171 @@+// @ts-check+// GET/POST /api/cron/launcher-claimer — auto-claim pump.fun creator fees from global+// launcher runs. Fires every 5 minutes via Vercel cron. For each minted coin in+// launcher_runs that has accumulated >= CLAIM_THRESHOLD_SOL in creator fees and hasn't+// been claimed in the last 24 hours:+// 1. Query live fee-info from the platform pump API+// 2. Claim via collect-creator-fee-agent (agent signs its own claim, same as the launch)+// 3. Record in launcher_claims (claimed_sol, buyback_sol allocated, claim_sig)+//+// This closes the money loop: launch → fees accrue → claim → revenue tracking.+// The buyback_sol column tracks the $THREE-allocated share (buyback_bps from the+// run's config). The actual swap path wires in once the trade endpoint is confirmed.+//+// Auth: CRON_SECRET Bearer (same pattern as all cron endpoints).++import { json, error, method, wrapCron } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { constantTimeEquals } from '../_lib/crypto.js';+import { sql } from '../_lib/db.js';+import { createSession } from '../_lib/auth.js';++const CLAIM_THRESHOLD_SOL = 0.01;+const ORIGIN = env.APP_ORIGIN || 'https://three.ws';+const MAX_PER_TICK = 20;++let _schemaDone = false;+async function ensureSchema() {+ if (_schemaDone) return;+ // Idempotent — launcher-engine.js creates the same table on runLauncherTick().+ // Duplicated here so the claimer works even when the engine hasn't ticked yet.+ await sql`+ create table if not exists launcher_claims (+ id uuid primary key default gen_random_uuid(),+ run_id uuid references launcher_runs(id) on delete set null,+ agent_id uuid,+ mint text not null,+ claimed_lamports bigint not null default 0,+ claimed_sol float8 not null default 0,+ buyback_sol float8 not null default 0,+ buyback_sig text,+ claim_sig text,+ network text not null default 'mainnet',+ scope text not null default 'global',+ created_at timestamptz not null default now()+ )+ `;+ await sql`create index if not exists launcher_claims_run_idx on launcher_claims (run_id, created_at desc)`;+ await sql`create index if not exists launcher_claims_created_idx on launcher_claims (created_at desc)`;+ _schemaDone = true;+}++function requireCron(req, res) {+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;+ if (!secret) { error(res, 503, 'not_configured', 'CRON_SECRET unset'); return false; }+ const auth = req.headers['authorization'] || '';+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';+ if (!constantTimeEquals(presented, secret)) { error(res, 401, 'unauthorized', 'invalid cron secret'); return false; }+ return true;+}++// Create a session as an agent's owner, then make a fetch call to an internal API+// path. The agent's owner session is required because collect-creator-fee-agent+// verifies the caller owns the agent.+async function agentFetch(ownerUserId, urlOrPath, opts = {}) {+ const token = await createSession({ userId: ownerUserId, userAgent: 'launcher-claimer', ip: null });+ const url = urlOrPath.startsWith('http') ? urlOrPath : `${ORIGIN}${urlOrPath}`;+ const res = await fetch(url, {+ ...opts,+ headers: {+ 'user-agent': 'threews-launcher-claimer/1.0',+ ...(opts.headers || {}),+ cookie: `__Host-sid=${token}`,+ },+ signal: opts.signal ?? AbortSignal.timeout(15_000),+ }).catch(() => null);+ return res;+}++async function processMint(run) {+ const { id: runId, mint, agent_id: agentId, network, buyback_bps, owner_user_id: userId } = run;++ // 1. Fetch live claimable balance.+ const feeRes = await agentFetch(+ userId,+ `/api/pump?action=fee-info&mint=${encodeURIComponent(mint)}&network=${encodeURIComponent(network)}`,+ );+ if (!feeRes || !feeRes.ok) return { runId, status: 'fee-info-failed' };+ const feeInfo = await feeRes.json().catch(() => null);+ if (!feeInfo) return { runId, status: 'fee-info-unparseable' };++ const claimableSol = Number(feeInfo.claimable_lamports ?? 0) / 1e9;+ if (claimableSol < CLAIM_THRESHOLD_SOL) {+ return { runId, status: 'below-threshold', claimableSol };+ }++ // 2. Claim — the agent signs its own fee claim (same identity that created the coin).+ const claimRes = await agentFetch(userId, '/api/pump?action=collect-creator-fee-agent', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ agentId, mint, network }),+ });+ if (!claimRes || !claimRes.ok) return { runId, status: 'claim-failed' };+ const claimData = await claimRes.json().catch(() => null);+ if (!claimData?.ok) return { runId, status: 'claim-rejected', error: claimData?.error };++ const claimedLamports = Number(claimData.lamports ?? 0);+ const claimedSol = claimedLamports / 1e9;+ const buybackBps = Number(buyback_bps ?? 5000);+ const buybackSol = Math.round(claimedSol * buybackBps) / 10_000;++ // 3. Record the claim. Multiple claims per run_id are allowed (fees re-accrue).+ await sql`+ insert into launcher_claims+ (run_id, agent_id, mint, claimed_lamports, claimed_sol, buyback_sol, claim_sig, network, scope)+ values (+ ${runId}, ${agentId}, ${mint},+ ${claimedLamports}, ${claimedSol}, ${buybackSol},+ ${claimData.sig ?? null}, ${network}, 'global'+ )+ `;++ return { runId, status: 'claimed', claimedSol, buybackSol, sig: claimData.sig };+}++async function runClaimerTick() {+ await ensureSchema();++ // Find minted coins that either have never been claimed or whose last successful+ // claim was > 24 hours ago (fees re-accrue after each claim).+ const runs = await sql`+ select lr.id, lr.mint, lr.agent_id, lr.network, lr.buyback_bps,+ ai.user_id as owner_user_id, ai.name as agent_name+ from launcher_runs lr+ join agent_identities ai on ai.id = lr.agent_id and ai.deleted_at is null+ where lr.mint is not null+ and lr.status in ('confirmed', 'launched')+ and ai.user_id is not null+ and not exists (+ select 1 from launcher_claims lc+ where lc.run_id = lr.id+ and lc.claimed_sol > 0+ and lc.created_at > now() - interval '24 hours'+ )+ order by lr.created_at asc+ limit ${MAX_PER_TICK}+ `;++ if (!runs.length) return { checked: 0, claimed: 0, skipped: 0, errors: 0 };++ let claimed = 0, skipped = 0, errors = 0;+ const details = [];++ for (const run of runs) {+ const result = await processMint(run).catch((err) => ({+ runId: run.id, status: 'error', error: err?.message,+ }));+ details.push(result);+ if (result.status === 'claimed') claimed++;+ else if (result.status === 'below-threshold') skipped++;+ else errors++;+ }++ return { checked: runs.length, claimed, skipped, errors };+}++export default wrapCron(async (req, res) => {+ if (!method(req, res, ['GET', 'POST'])) return;+ if (!requireCron(req, res)) return;+ const out = await runClaimerTick().catch((err) => ({ ok: false, error: err?.message, checked: 0, claimed: 0 }));+ return json(res, 200, { ok: true, ...out });+});diff --git a/api/launcher/me.js b/api/launcher/me.jsnew file mode 100644index 000000000..f606214b2--- /dev/null+++ b/api/launcher/me.js@@ -0,0 +1,250 @@+/**+ * Personal Memetic Launcher — the per-user scope of the autonomous launcher.+ *+ * GET /api/launcher/me+ * The caller's own launcher_config (scope='user'), their recent runs, today's+ * throughput, how many of their agents are launch-ready, and the live cultural+ * narratives their launcher would ride right now.+ *+ * POST /api/launcher/me+ * Upsert the caller's launcher policy (mode, sources, cadence, network, on/off).+ * { action: 'preview' } → synthesize ONE sample coin the launcher would mint+ * right now (no DB write, on demand — never per poll).+ * { action: 'resume' } → clear a tripped circuit breaker.+ *+ * SAFETY — why a normal user can run this without an abuse vector: the shared+ * platform master wallet funds every live launch (launcher-engine → fundAgentForLaunch).+ * There is deliberately no per-user funding source yet, so a user-scope launcher is+ * HARD-LOCKED to dry_run server-side: enabling it makes the cron pick real coins ++ * the user's own agents + live narratives and record them, but it never moves SOL.+ * It is a true preview/strategy designer. Going live is a separately-funded follow-up;+ * the lock is the one line (FORCE_DRY_RUN) that keeps that decision deliberate.+ *+ * Auth: session cookie OR bearer JWT (so a user's agent can drive it too).+ */++import { cors, error, json, method, rateLimited, readJson, wrap } from '../_lib/http.js';+import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { sql } from '../_lib/db.js';+import { rankNarratives } from '../_lib/launcher-trends.js';+import { pickSource } from '../_lib/launcher-sources.js';++// A user-scope launcher can never move SOL (see SAFETY above). One place to lift+// this when per-user funding ships.+const FORCE_DRY_RUN = true;++const MODES = ['off', 'trend', 'meme', 'random', 'hybrid'];+const KNOWN_SOURCES = ['coin_intel', 'trending', 'x', 'knowyourmeme', 'hackernews', 'reddit', 'wikipedia'];++async function resolveUserId(req) {+ const session = await getSessionUser(req);+ if (session?.id) return session.id;+ const bearer = extractBearer(req);+ if (bearer) {+ const auth = await authenticateBearer(bearer).catch(() => null);+ if (auth?.userId) return auth.userId;+ }+ return null;+}++// jsonb columns arrive as arrays or (depending on driver) JSON strings — coerce.+function coerceArr(v) {+ if (Array.isArray(v)) return v;+ if (typeof v === 'string') { try { const p = JSON.parse(v); return Array.isArray(p) ? p : []; } catch { return []; } }+ return [];+}++async function ensureUserRow(userId) {+ await sql`+ insert into launcher_config (scope, user_id, enabled, dry_run, mode)+ values ('user', ${userId}, false, true, 'hybrid')+ on conflict (user_id) where scope = 'user' do nothing+ `;+ const [row] = await sql`select * from launcher_config where scope = 'user' and user_id = ${userId} limit 1`;+ return row;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', credentials: true })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ const userId = await resolveUserId(req);+ if (!userId) return error(res, 401, 'unauthorized', 'authentication required');++ const rl = await limits.authIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const config = await ensureUserRow(userId);++ if (req.method === 'GET') return getState(res, userId, config);++ const body = (await readJson(req).catch(() => ({}))) || {};+ if (body.action === 'preview') return previewCoin(res, config, body);+ if (body.action === 'resume') return resumeBreaker(res, userId);+ return postConfig(res, userId, config, body);+});++async function getState(res, userId, config) {+ const network = config?.network || 'mainnet';++ const [recent, stats, queue, eligible] = await Promise.all([+ sql`+ select id, agent_id, kind, trigger_source, trigger_detail, name, symbol, mint, network,+ sol_spent, status, dry_run, tx_signature, error, created_at+ from launcher_runs+ where scope = 'user' and user_id = ${userId}+ order by created_at desc+ limit 50+ `,+ sql`+ select+ count(*)::int as runs_today,+ count(*) filter (where status = 'dry_run')::int as dry_runs_today,+ count(*) filter (where status in ('launched','confirmed'))::int as launched_today,+ count(*) filter (where status = 'skipped')::int as skipped_today,+ count(*) filter (where status = 'failed')::int as failed_today+ from launcher_runs+ where scope = 'user' and user_id = ${userId} and created_at >= date_trunc('day', now())+ `,+ sql`select count(*)::int as enabled from launcher_queue where scope = 'user' and user_id = ${userId} and enabled = true`,+ // The user's own launch-ready agents: public-or-not, avatar-bearing, walleted.+ sql`+ select count(*)::int as n from agent_identities ai+ where ai.user_id = ${userId} and ai.deleted_at is null+ and ai.avatar_id is not null and ai.meta->>'solana_address' is not null+ `,+ ]);++ const cfgSources = coerceArr(config?.sources);+ const narratives = await rankNarratives({+ network,+ sources: cfgSources.length ? cfgSources : undefined,+ categories: coerceArr(config?.categories),+ limit: 16,+ }).catch(() => null);++ return json(res, 200, {+ config: shapeConfig(config),+ console: recent,+ stats: stats[0] || {},+ queue_enabled: queue[0]?.enabled ?? 0,+ eligible_agents: eligible[0]?.n ?? 0,+ dry_run_locked: FORCE_DRY_RUN,+ narratives: narratives+ ? { terms: narratives.terms || [], top: narratives.top || null, providers: narratives.providers || [] }+ : null,+ });+}++// A user-scope launcher is never "armed" (dry-run-locked) — expose the running flag+// honestly so the UI never implies real SOL will move.+function shapeConfig(c) {+ if (!c) return null;+ return { ...c, dry_run: FORCE_DRY_RUN ? true : c.dry_run, armed: false };+}++// Cadence floor + hourly ceiling for user scope: each enabled user launcher is+// driven by the shared cron and may synthesize a coin (LLM) per tick, so keep the+// per-user load bounded regardless of what the client asks for.+const USER_MIN_CADENCE = 60;+const USER_MAX_PER_HOUR = 60;++// Pure validation + normalisation of a config patch. Returns { ok:false, code,+// message } on a bad field, else { ok:true, next } with every value range-clamped+// and dry_run forced on (a user-scope launcher can never move SOL). No I/O — unit+// tested in tests/user-launcher.test.js.+export function validateAndBuildPatch(body, cur) {+ if (body.mode != null && !MODES.includes(body.mode)) {+ return { ok: false, code: 'invalid_mode', message: `mode must be one of ${MODES.join(', ')}` };+ }+ if (body.network != null && !['mainnet', 'devnet'].includes(body.network)) {+ return { ok: false, code: 'invalid_network', message: 'network must be mainnet or devnet' };+ }+ if (body.sources != null && (!Array.isArray(body.sources) || body.sources.some((s) => !KNOWN_SOURCES.includes(s)))) {+ return { ok: false, code: 'invalid_sources', message: `sources must be a subset of ${KNOWN_SOURCES.join(', ')}` };+ }+ if (body.categories != null && !Array.isArray(body.categories)) {+ return { ok: false, code: 'invalid_categories', message: 'categories must be an array' };+ }+ const inRange = (v, lo, hi) => { const n = Number(v); return Number.isFinite(n) && n >= lo && n <= hi; };+ if (body.target_cadence_seconds != null && !inRange(body.target_cadence_seconds, USER_MIN_CADENCE, 86_400)) {+ return { ok: false, code: 'invalid_cadence', message: `target_cadence_seconds must be ${USER_MIN_CADENCE}..86400` };+ }+ if (body.max_per_hour != null && !inRange(body.max_per_hour, 0, USER_MAX_PER_HOUR)) {+ return { ok: false, code: 'invalid_max_per_hour', message: `max_per_hour must be 0..${USER_MAX_PER_HOUR}` };+ }++ const has = (k) => Object.prototype.hasOwnProperty.call(body, k);+ const clamp = (n, lo, hi) => Math.min(hi, Math.max(lo, n));+ const next = {+ enabled: has('enabled') ? Boolean(body.enabled) : cur.enabled,+ // dry_run is server-owned for user scope — never trust the client to clear it.+ dry_run: true,+ mode: has('mode') ? body.mode : cur.mode,+ sources: has('sources') ? body.sources : coerceArr(cur.sources),+ categories: has('categories') ? body.categories : coerceArr(cur.categories),+ target_cadence_seconds: has('target_cadence_seconds') ? clamp(Math.round(Number(body.target_cadence_seconds)), USER_MIN_CADENCE, 86_400) : cur.target_cadence_seconds,+ max_per_hour: has('max_per_hour') ? clamp(Math.round(Number(body.max_per_hour)), 0, USER_MAX_PER_HOUR) : cur.max_per_hour,+ network: has('network') ? body.network : cur.network,+ };+ return { ok: true, next };+}++async function postConfig(res, userId, cur, body) {+ const patch = validateAndBuildPatch(body, cur);+ if (!patch.ok) return error(res, 400, patch.code, patch.message);+ const next = patch.next;++ const [row] = await sql`+ update launcher_config set+ enabled = ${next.enabled},+ dry_run = ${next.dry_run},+ mode = ${next.mode},+ sources = ${JSON.stringify(next.sources)}::jsonb,+ categories = ${JSON.stringify(next.categories)}::jsonb,+ target_cadence_seconds = ${next.target_cadence_seconds},+ max_per_hour = ${next.max_per_hour},+ network = ${next.network},+ updated_at = now()+ where scope = 'user' and user_id = ${userId}+ returning *+ `;++ return json(res, 200, { ok: true, config: shapeConfig(row) });+}++// On-demand single-coin synthesis: shows exactly what the launcher would mint next.+// User-initiated only (it can call the LLM), so never wire this onto a poll.+async function previewCoin(res, config, body) {+ const mode = MODES.includes(body.mode) ? body.mode : (config?.mode || 'hybrid');+ const network = config?.network || 'mainnet';+ const coin = await pickSource({+ mode,+ network,+ categories: coerceArr(config?.categories),+ sources: coerceArr(config?.sources).length ? coerceArr(config?.sources) : undefined,+ }).catch(() => null);+ if (!coin) return error(res, 503, 'preview_unavailable', 'could not synthesize a sample coin right now');+ return json(res, 200, {+ ok: true,+ sample: {+ name: coin.name,+ symbol: coin.symbol,+ description: coin.description || '',+ kind: coin.kind,+ trigger_source: coin.trigger_source || null,+ top_narrative: coin.trigger_detail?.top_narrative || null,+ },+ });+}++async function resumeBreaker(res, userId) {+ const [row] = await sql`+ update launcher_config set paused = false, pause_reason = null, updated_at = now()+ where scope = 'user' and user_id = ${userId} returning *+ `;+ return json(res, 200, { ok: true, config: shapeConfig(row) });+}++export { FORCE_DRY_RUN, MODES, KNOWN_SOURCES, shapeConfig };diff --git a/api/launcher/narratives.js b/api/launcher/narratives.jsdeleted file mode 100644index 6e5562d04..000000000--- a/api/launcher/narratives.js+++ /dev/null@@ -1,59 +0,0 @@-// GET /api/launcher/narratives — public, read-only feed of the live cultural-// narratives the autonomous launcher is riding right now.-//-// This is the launcher's intelligence made public: any agent (or the homepage,-// or a curious holder) can ask "what is the internet talking about, ranked, with-// which sources confirm it" and use it to decide what to coin — making it far-// easier for agents to ride a real wave instead of guessing. Themes ONLY, never-// tickers (the $THREE rule, enforced upstream in launcher-trends). Cached hard,-// degrades to an empty list, never throws.-//-// ?network=mainnet|devnet (default mainnet)-// ?limit=1..40 (default 24)-// ?sources=knowyourmeme,googletrends,... (subset of the known providers)-//-// Response: { ok, network, top, terms:[{term,score,sources,kind}], themes, providers, updated }--import { cors, json, method, wrap } from '../_lib/http.js';-import { rankNarratives, DEFAULT_SOURCES, EXTERNAL_SOURCES } from '../_lib/launcher-trends.js';--// The vocabulary a caller may request. Internal venue signals (coin_intel,-// trending) plus every external culture provider — all reduced to themes.-const ALLOWED = new Set([...DEFAULT_SOURCES, ...EXTERNAL_SOURCES, 'coin_intel', 'trending', 'x']);--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;- if (!method(req, res, ['GET'])) return;-- const url = new URL(req.url, 'http://x');- const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';- const limit = Math.max(1, Math.min(40, Number(url.searchParams.get('limit')) || 24));- const requested = (url.searchParams.get('sources') || '')- .split(',')- .map((s) => s.trim().toLowerCase())- .filter(Boolean)- .filter((s) => ALLOWED.has(s));-- let result = null;- try {- result = await rankNarratives({- network,- sources: requested.length ? requested : undefined,- limit,- });- } catch {- /* intelligence dark — fall through to an empty, honest payload */- }-- // Cache at the edge: the underlying providers are themselves cached ~3–5 min,- // so a 60s browser / 120s shared cache keeps this cheap without going stale.- res.setHeader('cache-control', 'public, max-age=60, s-maxage=120, stale-while-revalidate=300');- return json(res, 200, {- ok: true,- network,- top: result?.top || null,- terms: result?.terms || [],- themes: result?.themes || [],- providers: result?.providers || [],- });-});diff --git a/api/launcher/trends.js b/api/launcher/trends.jsnew file mode 100644index 000000000..aea4e65cf--- /dev/null+++ b/api/launcher/trends.js@@ -0,0 +1,111 @@+// GET /api/launcher/trends — public cultural-intelligence feed for the autonomous+// coin launcher (the "Memetic Launcher"). Built for AGENTS first: any agent can+// poll this to learn which narratives are rising across the internet right now —+// ranked, momentum-scored, and cross-source-confirmed — plus the coins three.ws+// has autonomously launched on those waves. Real signal only; no auth required.+//+// GET /api/launcher/trends → ranked narratives + recent launches+// GET /api/launcher/trends?network=devnet → devnet view+// GET /api/launcher/trends?limit=30 → up to 50 narrative terms+// GET /api/launcher/trends?launches=0 → narratives only (skip the launch feed)+// GET /api/launcher/trends?sources=knowyourmeme,googletrends+// → restrict to specific providers+// (subset of PROVIDER_IDS; empty ⇒ defaults)+//+// Themes only — never a specific non-$THREE ticker recommendation. The terms are+// cultural currents (memes, topics), and the launches are three.ws's own runtime+// launch records. Cached 60s so a swarm of agents can poll without load.++import { sql } from '../_lib/db.js';+import { cors, json, method, wrap, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import { cacheGet, cacheSet } from '../_lib/cache.js';+import { rankNarratives, PROVIDER_IDS } from '../_lib/launcher-trends.js';++const TTL_S = 60;+const PROVIDER_SET = new Set(PROVIDER_IDS);++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const params = new URL(req.url, 'http://x').searchParams;+ const network = params.get('network') === 'devnet' ? 'devnet' : 'mainnet';+ const limit = clampInt(params.get('limit'), 20, 1, 50);+ const wantLaunches = params.get('launches') !== '0' && params.get('launches') !== 'false';+ // Optional source filter — only real providers, sorted for a stable cache key.+ const sources = (params.get('sources') || '')+ .split(',')+ .map((s) => s.trim().toLowerCase())+ .filter((s) => PROVIDER_SET.has(s))+ .sort();++ const cacheKey = `launcher:trends:${network}:${limit}:${wantLaunches ? 1 : 0}:${sources.join('+') || 'default'}`;+ const cached = await cacheGet(cacheKey).catch(() => null);+ if (cached) {+ return json(res, 200, cached, { 'cache-control': 'public, max-age=30, s-maxage=60' });+ }++ const [ranked, launches] = await Promise.all([+ rankNarratives({ network, limit, sources: sources.length ? sources : undefined }).catch(() => null),+ wantLaunches ? recentLaunches(network).catch(() => []) : Promise.resolve([]),+ ]);++ const terms = (ranked?.terms || []).slice(0, limit).map((t) => ({+ term: t.term,+ score: round(t.score, 4),+ momentum: t.sources?.length || 0,+ sources: t.sources || [],+ kind: t.kind || null,+ }));++ const body = {+ network,+ generated_at: new Date().toISOString(),+ narratives: {+ top: terms[0] || null,+ count: terms.length,+ providers: ranked?.providers || [],+ terms,+ },+ launches,+ // A small honest note so consumers understand the contract.+ about: 'Ranked cultural narratives the autonomous launcher rides, plus three.ws launches on those waves. Themes, not ticker calls.',+ };++ await cacheSet(cacheKey, body, TTL_S).catch(() => {});+ return json(res, 200, body, { 'cache-control': 'public, max-age=30, s-maxage=60' });+});++// Recent autonomous launches (confirmed on-chain) from the global launcher, newest+// first — the real coins minted on the trending waves. Empty when the table is+// absent or the launcher has not run.+async function recentLaunches(network) {+ const rows = await sql`+ select name, symbol, mint, kind, trigger_source, trigger_detail, created_at+ from launcher_runs+ where scope = 'global' and network = ${network}+ and status in ('launched', 'confirmed') and mint is not null+ order by created_at desc+ limit 20+ `;+ return rows.map((r) => ({+ name: r.name,+ symbol: r.symbol,+ mint: r.mint,+ kind: r.kind,+ rode: r.trigger_detail?.top_narrative || r.trigger_source || null,+ created_at: r.created_at,+ }));+}++function clampInt(v, dflt, lo, hi) {+ if (v == null || v === '') return dflt; // absent param → default (Number(null) is 0, not NaN)+ const n = Math.floor(Number(v));+ if (!Number.isFinite(n)) return dflt;+ return Math.min(hi, Math.max(lo, n));+}+function round(n, d) { const p = 10 ** d; return Math.round(Number(n) * p) / p; }diff --git a/api/marketplace/[action].js b/api/marketplace/[action].jsindex ce8663f63..410b5ed88 100644--- a/api/marketplace/[action].js+++ b/api/marketplace/[action].js@@ -592,6 +592,7 @@ async function handleList(req, res, url) {const hasMore = rows.length > limit;const items = rows.slice(0, limit).map(toCard);+ await decorateActivated(items);return json(res,@@ -606,6 +607,27 @@ async function handleList(req, res, url) {);}+// Flag which of these cards are "live" (claimed their activation grant — funded ++// on the Money Pulse) in one batched, indexed lookup. Kept OUT of the main browse+// query on purpose: referencing agent_activations there would force the whole list+// onto its degraded fallback on any deploy where the table isn't migrated yet. As+// a standalone, fully table-tolerant step it can only ever add a badge, never+// break the listing. Mutates each card in place.+async function decorateActivated(items) {+ if (!items.length) return;+ try {+ const ids = items.map((c) => c.id);+ const rows = await sql`+ SELECT agent_id FROM agent_activations+ WHERE agent_id = ANY(${ids}) AND status = 'confirmed'+ `;+ const live = new Set(rows.map((r) => r.agent_id));+ for (const card of items) card.activated = live.has(card.id);+ } catch (e) {+ if (e?.code !== '42P01') console.warn('[marketplace/list] activation flags skipped', e?.message);+ }+}+// ── Detail ─────────────────────────────────────────────────────────────────async function handleDetail(req, res, id) {diff --git a/api/pipeline.js b/api/pipeline.jsindex e0ead3688..7eb0bb6f7 100644--- a/api/pipeline.js+++ b/api/pipeline.js@@ -25,6 +25,7 @@import { cors, json, method, wrap, rateLimited } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import { sql } from './_lib/db.js';+import { summarize } from './_lib/pipeline-summary.js';const WORKER = 'agent-sniper';// 2× the 30s heartbeat cadence + slack: one skipped beat under load must not@@ -211,10 +212,10 @@ export default wrap(async (req, res) => {}, { strategies_armed: 0, open_positions: 0, snipes_24h: 0, trades_24h: 0 }),]);- // A coarse one-word health for the page header + any external monitor.- const recording = recorder.state === 'live';- const flowing = intel.observed_1h > 0;- const health = recording && flowing ? 'flowing' : recording ? 'recording' : 'idle';+ const stages = { recorder, intel, outcomes, oracle, reputation, learning, trading };+ // Health, one-line summary, and the single most useful next action — derived+ // by a shared pure module so the page, agents, and tests read one truth.+ const { health, summary, next_action } = summarize(network, stages);return json(res,@@ -223,7 +224,10 @@ export default wrap(async (req, res) => {ok: true,network,health,- stages: { recorder, intel, outcomes, oracle, reputation, learning, trading },+ summary,+ next_action,+ stages,+ docs: 'https://three.ws/pipeline',t: Date.now(),},// Heartbeat + crons refresh on the order of seconds-to-minutes; a shortdiff --git a/api/pulse.js b/api/pulse.jsindex ffb016c0b..84db54ae9 100644--- a/api/pulse.js+++ b/api/pulse.js@@ -42,6 +42,12 @@ import { shapeTradingWindow, shapeTradingPnl, shapeTradingSeries, solFromLamport// excluded by the WHERE clauses below — never add those here.const PUBLIC_SPEND_CATEGORIES = ['trade', 'snipe', 'x402'];+// The live FEED additionally surfaces marketplace skill purchases (category+// 'marketplace') as 'purchase' beats — real, value-delivering commerce. This is a+// feed-only superset: the aggregate money math above stays on PUBLIC_SPEND_CATEGORIES+// so marketplace's $THREE-denominated rows never distort the SOL volume counters.+const FEED_SPEND_CATEGORIES = [...PUBLIC_SPEND_CATEGORIES, 'marketplace'];+// $THREE is the only coin the marketplace prices in. Real skill purchases settle// in $THREE (6 decimals), so marketplace GMV is denominated here. A purchase is// "paid" only when status='confirmed' and it's not a free trial.@@ -53,10 +59,11 @@ const threeFromAtomic = (atomic) => Number(atomic || 0) / 10 ** THREE_DECIMALS;// type= query param → the set of `kind`s it admits.const TYPE_KINDS = {- all: ['tip', 'trade', 'snipe', 'payment', 'launch'],+ all: ['tip', 'trade', 'snipe', 'payment', 'purchase', 'launch'],tips: ['tip'],trades: ['trade', 'snipe'],payments: ['payment'],+ purchases: ['purchase'],launches: ['launch'],};@@ -121,6 +128,7 @@ function shapeEvent(r) {mint: r.mint || null,symbol: r.symbol || null,coin_name: r.coin_name || null,+ skill: r.skill || null, // marketplace 'purchase' beats carry the skill namemint_explorer: r.mint ? explorerAccountUrl(r.mint, r.network) : null,// the counterparty of a tip / payment, when public on-chaincounterparty: r.counterparty || null,@@ -150,9 +158,10 @@ async function handleFeed(req, res, { network, type, agentId, cursor, since }) {SELECTce.created_at AS ts,(CASE- WHEN ce.event_type = 'tip' THEN 'tip'- WHEN ce.category = 'x402' THEN 'payment'- WHEN ce.category = 'snipe' THEN 'snipe'+ WHEN ce.event_type = 'tip' THEN 'tip'+ WHEN ce.category = 'x402' THEN 'payment'+ WHEN ce.category = 'snipe' THEN 'snipe'+ WHEN ce.category = 'marketplace' THEN 'purchase'ELSE 'trade'END) AS kind,'c' || ce.id::text AS row_id,@@ -172,6 +181,7 @@ async function handleFeed(req, res, { network, type, agentId, cursor, since }) {NULL::text AS mint,NULL::text AS symbol,NULL::text AS coin_name,+ NULLIF(ce.meta->>'skill', '') AS skill,NULLIF(ce.meta->>'from', '') AS counterpartyFROM agent_custody_events ceJOIN agent_identities ai ON ai.id = ce.agent_id AND ${visGate}@@ -180,7 +190,7 @@ async function handleFeed(req, res, { network, type, agentId, cursor, since }) {AND ce.status IN ('ok', 'confirmed')AND (ce.event_type = 'tip'- OR (ce.event_type = 'spend' AND ce.category = ANY(${PUBLIC_SPEND_CATEGORIES}))+ OR (ce.event_type = 'spend' AND ce.category = ANY(${FEED_SPEND_CATEGORIES})))${agentFilterCe}@@ -206,6 +216,7 @@ async function handleFeed(req, res, { network, type, agentId, cursor, since }) {pam.mint AS mint,pam.symbol AS symbol,pam.name AS coin_name,+ NULL::text AS skill,NULL::text AS counterpartyFROM pump_agent_mints pamJOIN agent_identities ai ON ai.id = pam.agent_id AND ${visGate}diff --git a/api/scene-capture.js b/api/scene-capture.jsindex 3d9e77966..0820a2d02 100644--- a/api/scene-capture.js+++ b/api/scene-capture.js@@ -78,6 +78,7 @@ async function startJob(req, res) {window_size: clampInt(body?.window_size, 16, 512, 128),conf_percentile: Math.min(95, Math.max(0, Number(body?.conf_percentile) || 30)),max_points: clampInt(body?.max_points, 50_000, 3_000_000, 1_500_000),+ voxel_size: Math.min(10, Math.max(0, Number(body?.voxel_size) || 0)),mask_sky: body?.mask_sky !== false,};diff --git a/api/scene-upload.js b/api/scene-upload.jsnew file mode 100644index 000000000..f85fb245b--- /dev/null+++ b/api/scene-upload.js@@ -0,0 +1,108 @@+/**+ * /api/scene-upload — direct-to-storage upload for Scene Capture source videos.+ *+ * POST /api/scene-upload { content_type, size_bytes }+ * → 200 { storage_key, upload_url, public_url, method, headers, expires_in }+ *+ * The browser PUTs the video bytes straight to `upload_url` (a short-lived R2+ * presigned URL), then submits `public_url` to /api/scene-capture as `video_url`.+ * Keeping multi-hundred-MB video off this serverless function is the whole point+ * — mirrors /api/forge-upload, but for video content types and a larger cap.+ *+ * Auth-free, matching the rest of the capture surface: rate-limited by client IP+ * and scoped to the anonymous browser handle (x-forge-client). When object+ * storage isn't configured the endpoint returns a clean 503 and the page falls+ * back to accepting a public video URL directly.+ */++import { randomUUID } from 'node:crypto';+import { cors, json, method, readJson, wrap, rateLimited } from './_lib/http.js';+import { limits, clientIp } from './_lib/rate-limit.js';+import { presignUpload, publicUrl } from './_lib/r2.js';+import { hashClient } from './_lib/forge-store.js';++// Accepted source-video types → file extension for the storage key.+const CONTENT_TYPE_EXT = Object.freeze({+ 'video/mp4': 'mp4',+ 'video/quicktime': 'mov',+ 'video/webm': 'webm',+});++// A walkthrough clip is comfortably under this; anything larger is almost+// certainly the wrong input for a streaming reconstruction.+const MAX_VIDEO_BYTES = 512 * 1024 * 1024;++function storageConfigured() {+ return Boolean(+ process.env.S3_ENDPOINT &&+ process.env.S3_BUCKET &&+ process.env.S3_PUBLIC_DOMAIN &&+ process.env.S3_ACCESS_KEY_ID &&+ process.env.S3_SECRET_ACCESS_KEY,+ );+}++function clientKeyFrom(req) {+ const raw = req.headers['x-forge-client'];+ return hashClient(Array.isArray(raw) ? raw[0] : raw);+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'POST,OPTIONS' })) return;+ if (!method(req, res, ['POST'])) return;++ if (!storageConfigured()) {+ return json(res, 503, {+ error: 'unconfigured',+ message:+ 'Video upload is not configured on this deployment (object storage missing). ' ++ 'Pass a public https video URL to /api/scene-capture instead.',+ });+ }++ const ip = clientIp(req);+ const rl = await limits.upload(`scene:${ip}`);+ if (!rl.success) return rateLimited(res, rl, 'Upload limit reached. Try again shortly.');++ const body = await readJson(req, 2_000).catch(() => null);++ const contentType =+ typeof body?.content_type === 'string' ? body.content_type.trim().toLowerCase() : '';+ const ext = CONTENT_TYPE_EXT[contentType];+ if (!ext) {+ return json(res, 400, {+ error: 'invalid_content_type',+ message: 'content_type must be video/mp4, video/quicktime, or video/webm.',+ });+ }++ const size = Number(body?.size_bytes);+ if (!Number.isFinite(size) || size <= 0 || size > MAX_VIDEO_BYTES) {+ return json(res, 400, {+ error: 'invalid_size',+ message: `size_bytes must be between 1 and ${MAX_VIDEO_BYTES} bytes.`,+ });+ }++ const clientKey = clientKeyFrom(req);+ const key = `capture/uploads/${clientKey.slice(0, 12)}/${randomUUID()}.${ext}`;++ let uploadUrl;+ try {+ uploadUrl = await presignUpload({ key, contentType });+ } catch (err) {+ return json(res, 502, {+ error: 'presign_failed',+ message: err?.message || 'Could not create an upload URL.',+ });+ }++ return json(res, 200, {+ storage_key: key,+ upload_url: uploadUrl,+ public_url: publicUrl(key),+ method: 'PUT',+ headers: { 'content-type': contentType },+ expires_in: 300,+ });+});diff --git a/api/status.js b/api/status.jsindex 2f63607c2..0fec29570 100644--- a/api/status.js+++ b/api/status.js@@ -16,6 +16,37 @@ import { UPTIME_TARGETS } from './cron/uptime-check.js';const round = (n) => Math.round(n * 100) / 100;+// Monochrome SVG status badge (shields-style, two segments) for READMEs, agent+// dashboards, and integrator status walls — embed with+// <img src="https://three.ws/api/status?format=svg" alt="three.ws status">+// Deliberately grayscale to match the brand: the STATE WORD carries the meaning,+// not a color, so it reads the same for color-blind viewers and in monochrome+// print. `state` is 'operational' | 'degraded' | 'down' | 'warming up'.+function statusBadgeSvg(state) {+ const label = 'three.ws';+ const value = state;+ // Monospace-ish width estimate: 6.5px/char + padding, keeps text inside the pill.+ const lw = Math.round(label.length * 6.5) + 16;+ const vw = Math.round(value.length * 6.5) + 16;+ const w = lw + vw;+ // down inverts (light text on ink) so an outage still stands out at a glance+ // without leaving the grayscale palette.+ const down = state === 'down';+ const valueBg = down ? '#111111' : '#e8e8e8';+ const valueFg = down ? '#e8e8e8' : '#111111';+ const esc = (s) => s.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');+ return `<svg xmlns="http://www.w3.org/2000/svg" width="${w}" height="20" role="img" aria-label="${esc(label)}: ${esc(value)}">+ <title>${esc(label)}: ${esc(value)}</title>+ <rect width="${w}" height="20" rx="3" fill="#111111"/>+ <rect x="${lw}" width="${vw}" height="20" rx="3" fill="${valueBg}"/>+ <rect x="${lw}" width="6" height="20" fill="${valueBg}"/>+ <g font-family="ui-monospace,SFMono-Regular,Menlo,monospace" font-size="11">+ <text x="8" y="14" fill="#e8e8e8">${esc(label)}</text>+ <text x="${lw + 8}" y="14" fill="${valueFg}">${esc(value)}</text>+ </g>+</svg>`;+}+export default wrap(async (req, res) => {if (cors(req, res, { origins: '*', methods: 'GET,OPTIONS' })) return;if (!method(req, res, ['GET'])) return;@@ -69,15 +100,63 @@ export default wrap(async (req, res) => {});const probed = services.filter((s) => s.operational !== null);+ const up = probed.filter((s) => s.operational);const allOk = probed.length > 0 && probed.every((s) => s.operational);+ const warming = probed.length === 0;++ // Fleet aggregates, computed once server-side so the page and any agent+ // consuming the JSON share one source of truth instead of each recomputing.+ const latNums = services.map((s) => s.avgLatency24hMs).filter((n) => n != null);+ const u90Nums = services.map((s) => s.uptime90d).filter((n) => n != null);+ const u24Nums = services.map((s) => s.uptime24h).filter((n) => n != null);+ const avg = (a) => (a.length ? a.reduce((x, y) => x + y, 0) / a.length : null);+ const summary = {+ operational: up.length,+ total: services.length,+ probed: probed.length,+ avgLatencyMs: latNums.length ? Math.round(avg(latNums)) : null,+ fleetUptime24h: u24Nums.length ? round(avg(u24Nums)) : null,+ fleetUptime90d: u90Nums.length ? round(avg(u90Nums)) : null,+ };++ const state = warming ? 'warming up' : allOk ? 'operational' : 'degraded';+ // A total outage (everything probed is down) flips the badge to its inverted+ // 'down' treatment so it screams; partial disruption stays 'degraded'.+ const badgeState = !warming && up.length === 0 ? 'down' : state;++ // Embeddable SVG badge: /api/status?format=svg (or ?badge). Long shared cache+ // — a badge that's a minute stale is fine and keeps it off the origin hot path.+ // Parse from req.url too: the Vite dev middleware doesn't populate req.query,+ // and relying on it alone would 404 the badge locally.+ const qs = (() => {+ try {+ return new URL(req.url, 'http://x').searchParams;+ } catch {+ return new URLSearchParams();+ }+ })();+ const wantsBadge =+ req.query?.format === 'svg' ||+ req.query?.badge !== undefined ||+ qs.get('format') === 'svg' ||+ qs.has('badge');+ if (wantsBadge) {+ res.setHeader('content-type', 'image/svg+xml; charset=utf-8');+ res.setHeader('cache-control', 'public, max-age=60, s-maxage=60, stale-while-revalidate=300');+ res.statusCode = 200;+ res.end(statusBadgeSvg(badgeState));+ return;+ }return json(res,200,{- ok: probed.length === 0 ? true : allOk,- monitoring: probed.length === 0 ? 'warming-up' : 'active',+ ok: warming ? true : allOk,+ monitoring: warming ? 'warming-up' : 'active',+ state,checkedAt: latest?.t ?? null,+ summary,services,},// json() defaults to no-store; status is probed every 5 minutes, so adiff --git a/data/changelog.json b/data/changelog.jsonindex 974b3e237..d1a30ab10 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,48 @@{"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-06-27",+ "title": "Sign-up and 3D avatar reliability fixes",+ "summary": "Two fixes to the front door. The 3D avatar on the sign-up page — and on roughly fifty other pages that show a preview model — now loads reliably the first time, instead of occasionally staying blank until you reloaded; a timing race meant the model viewer could start loading a compressed avatar before its decoder was ready. Separately, the sign-up username field again enforces its rules (3–30 characters; letters, numbers, underscore and hyphen) as you type in the latest Chrome, where a stricter pattern-matching mode had quietly switched that live validation off. No action needed — both are automatic.",+ "tags": ["fix"],+ "link": "/register"+ },+ {+ "date": "2026-06-27",+ "title": "Design your own Memetic Launcher",+ "summary": "Every account now has a personal Memetic Launcher at /launcher — your own autonomous coin-launch strategy designer. Pick a mode (ride live cultural trends, coin original memes, or pure random volume), choose which sources it mines (Coin Intel, Trending, Know Your Meme, X, Reddit, Hacker News, Wikipedia and more), set a cadence, and turn it on. It then rotates through your own agents and, every tick, picks exactly the coin it would mint — riding the strongest live narrative — and records it. A live narratives panel shows the cultural currents ranked in real time, and a one-tap Synthesize button coins a sample on demand. It runs in preview: it designs and shows your rotation without minting or moving any SOL, so you can perfect a strategy risk-free. Find it under Launch in the main menu.",+ "tags": ["feature"],+ "link": "/launcher"+ },+ {+ "date": "2026-06-27",+ "title": "Status page goes monochrome — with a fleet summary and an embeddable status badge",+ "summary": "The platform status page now leads with three at-a-glance numbers — 90-day uptime, services operational, and average response time — above the per-service history, and reads in clean monochrome that matches the rest of three.ws (a single red is reserved for a genuine outage so it's impossible to miss). The public status feed now also serves an embeddable status badge: drop https://three.ws/api/status?format=svg into any README or dashboard to show whether the platform is operational, and agents reading /api/status get the same fleet summary as a ready-made object.",+ "tags": ["feature", "improvement"],+ "link": "/status"+ },+ {+ "date": "2026-06-27",+ "title": "Hardened how the platform reads its rate-limit store credentials",+ "summary": "Fixed a configuration failure mode where the rate-limiter and cache store's address and access token could be drawn from two different sources and silently mismatch, which made every limiter and cache fall back to a weaker local mode and caused intermittent 'too many requests' errors and failed paid calls. The credentials are now always read together as one pair (and trimmed of stray whitespace), so a mismatch can't happen — keeping rate limits, paid endpoints, and caching reliable.",+ "tags": ["fix", "infra"],+ "link": "/status"+ },+ {+ "date": "2026-06-27",+ "title": "Live Agents is now everywhere it should be — and steadier under the hood",+ "summary": "Watching agents work is far easier to find and more reliable. Live Agents now has its own spot in the Discover menu, every agent profile has a Watch live button, the embedded watch panel links straight to the full-screen viewer, and the viewer has a one-tap path back to the whole live grid. Under the hood: the live roster no longer accumulates stale agents, queuing a task no longer blanks the screen image, a viewer landing on an offline agent now sees a clear offline state instead of hanging on 'connecting', and screen frames are restricted to safe image formats. The browser agent's idle behaviour is also neutral now — when it has no task it simply stands by on its three.ws home rather than wandering, and it never surfaces third-party tokens.",+ "tags": ["feature", "improvement", "fix", "security"],+ "link": "/agents-live"+ },+ {+ "date": "2026-06-27",+ "title": "Walk-Browse the Marketplace is now monochrome and agent-readable",+ "summary": "The 3D marketplace hall now reads as one cohesive monochrome material — type identity (agent/avatar/skill) is carried by brightness and clear labels instead of off-system brand colours, matching the rest of three.ws. And because the hall needs WebGL, the page now ships a no-script fallback: search crawlers, AI agents, and any visitor without JavaScript get a clean page with real, followable links into the agents, avatars, and skills catalogues instead of a blank loading spinner.",+ "tags": ["improvement"],+ "link": "/marketplace-walk"+ },{"date": "2026-06-27","title": "On-chain Deployments — live cross-chain agent registry feed, now with animated entries and richer rows",@@ -11,7 +53,7 @@{"date": "2026-06-27","title": "Live cultural narratives — now public, and now powered by Google Trends",- "summary": "The autonomous launcher's trend intelligence got broader and more open. Alongside Know Your Meme, it now reads Google Daily Search Trends — the broadest real-time signal of what the world is paying attention to — with a brand-safety gate that reads the news behind each trend and drops anything tied to tragedy before it can ever become a coin theme. And the ranked narratives are now a public, read-only feed at /api/launcher/narratives: any agent (or builder) can ask what's trending right now, with the sources confirming each wave, and ride a real current instead of guessing. Themes only — names and tickers are always invented fresh, never copied.",+ "summary": "The autonomous launcher's trend intelligence got broader and more open. Alongside Know Your Meme, it now reads Google Daily Search Trends — the broadest real-time signal of what the world is paying attention to — with a brand-safety gate that reads the news behind each trend and drops anything tied to tragedy before it can ever become a coin theme. And the ranked narratives are now a public, read-only feed at /api/launcher/trends: any agent (or builder) can ask what's trending right now — optionally filtered to specific sources — with the signals confirming each wave, and ride a real current instead of guessing. Themes only — names and tickers are always invented fresh, never copied.","tags": ["feature", "improvement"]},{diff --git a/pages/a-edit.html b/pages/a-edit.htmlindex 4371b43ce..45995b49c 100644--- a/pages/a-edit.html+++ b/pages/a-edit.html@@ -252,7 +252,7 @@<link rel="stylesheet" href="/footer.css" /><link rel="stylesheet" href="/mobile.css" /><script defer src="/footer-newsletter.js"></script>- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><header><div id="nav-container"></div></header>diff --git a/pages/admin/launcher.html b/pages/admin/launcher.htmlindex 5c6157528..f00f2f5ed 100644--- a/pages/admin/launcher.html+++ b/pages/admin/launcher.html@@ -50,6 +50,7 @@<span class="ml-master-lbl">Master wallet</span><span class="ml-master-val" id="ml-master-bal">—</span></div>+ <button class="ml-btn ml-btn-ghost ml-force" id="ml-force-tick" title="Run one launcher tick immediately">Force tick</button><button class="ml-btn ml-armswitch" id="ml-armswitch" aria-pressed="false"><span class="ml-armswitch-track"><span class="ml-armswitch-knob"></span></span><span class="ml-armswitch-lbl" id="ml-armswitch-lbl">Disabled</span>@@ -72,6 +73,8 @@<div class="ml-stat"><dt>SOL left today</dt><dd id="ml-s-left">—</dd></div><div class="ml-stat"><dt>Queue agents</dt><dd id="ml-s-queue">—</dd></div><div class="ml-stat"><dt>Failed / skipped</dt><dd id="ml-s-fail">—</dd></div>+ <div class="ml-stat ml-stat--revenue"><dt>Creator fees claimed</dt><dd id="ml-s-fees">—</dd></div>+ <div class="ml-stat ml-stat--revenue"><dt>$THREE allocated</dt><dd id="ml-s-buyback">—</dd></div></dl><div class="ml-grid">diff --git a/pages/agent-detail.html b/pages/agent-detail.htmlindex 100c5d00e..805781ba4 100644--- a/pages/agent-detail.html+++ b/pages/agent-detail.html@@ -405,6 +405,18 @@</svg>Walk with this agent</a>+ <a+ id="ad-watch-live"+ class="ad-btn"+ href="/agents-live"+ aria-label="Watch this agent's live screen and avatar cam"+ >+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" style="margin-right: 6px">+ <rect x="2" y="3" width="20" height="14" rx="2" />+ <path d="M8 21h8M12 17v4" />+ </svg>+ Watch live+ </a><aid="ad-irl-link"class="ad-btn"diff --git a/pages/agent-screen.html b/pages/agent-screen.htmlindex 1d00bb6d5..b4ea41894 100644--- a/pages/agent-screen.html+++ b/pages/agent-screen.html@@ -801,6 +801,7 @@</span></div><div class="asc-header-right">+ <a class="asc-btn" id="asc-all-live" href="/agents-live" style="text-decoration:none" title="All live agents">◳ All live</a><button class="asc-btn" id="asc-fullscreen-btn" title="Fullscreen screen view">⛶ Fullscreen</button><a class="asc-btn" id="asc-agent-link" href="/agents" style="text-decoration:none">View Agent →</a></div>diff --git a/pages/ar.html b/pages/ar.htmlindex 54450aadd..81da9e7ef 100644--- a/pages/ar.html+++ b/pages/ar.html@@ -361,7 +361,7 @@padding: 2rem;}</style>- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><div class="ar-bg" aria-hidden="true"></div>diff --git a/pages/avatar-page.html b/pages/avatar-page.htmlindex ee5830e86..193309ec4 100644--- a/pages/avatar-page.html+++ b/pages/avatar-page.html@@ -1578,7 +1578,7 @@}}</style>- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><header><div id="nav-container"></div></header>diff --git a/pages/capture.html b/pages/capture.htmlindex 9b95138fc..dc75b50e5 100644--- a/pages/capture.html+++ b/pages/capture.html@@ -122,6 +122,8 @@}.pc-icon-btn:hover { color: #fff; border-color: var(--hairline-strong, #2a2a2a); }.pc-icon-btn:focus-visible { outline: 2px solid var(--text, #fff); outline-offset: 2px; }+ .pc-icon-btn:disabled { opacity: 0.4; cursor: default; }+ .pc-icon-btn.is-active { color: #fff; border-color: var(--text, #f6f6f6); }.pc-icon-btn[hidden] { display: none; }/* Side panel */@@ -177,6 +179,16 @@.pc-note a { color: var(--text-2, #cfcfcf); }@media (max-width: 880px) { .pc-layout { grid-template-columns: 1fr; } }++ /* Embed mode (?embed=1) — chrome-less full-bleed stage for the MCP /+ agent point-cloud artifact iframe. Hide nav, footer, header, panel. */+ body.pc-embed #nav-container,+ body.pc-embed #footer-container,+ body.pc-embed .pc-head,+ body.pc-embed .pc-panel { display: none !important; }+ body.pc-embed .pc-wrap { max-width: none; padding: 0; }+ body.pc-embed .pc-layout { grid-template-columns: 1fr; margin: 0; gap: 0; }+ body.pc-embed .pc-stage { aspect-ratio: auto; height: 100vh; border: 0; border-radius: 0; }</style></head><body>@@ -232,11 +244,20 @@<div class="pc-hud" id="pc-hud" hidden><div class="pc-hud-label" id="pc-hud-label"></div><div class="pc-hud-right">- <div class="pc-size-wrap" title="Point size">+ <div class="pc-size-wrap" title="Point size ( [ and ] )"><svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="7" cy="7" r="1.5" fill="currentColor"/><circle cx="17" cy="17" r="3.5" fill="currentColor"/></svg><input class="pc-size" id="pc-size" type="range" min="0.25" max="4" step="0.05" value="1" disabled aria-label="Point size" /></div>- <button class="pc-icon-btn" id="pc-recenter" type="button" title="Recenter camera" aria-label="Recenter camera">+ <button class="pc-icon-btn" id="pc-color" type="button" disabled title="Cycle colour mode (C)" aria-label="Cycle colour mode">+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="9"/><path d="M12 3a9 9 0 0 0 0 18Z" fill="currentColor"/></svg>+ </button>+ <button class="pc-icon-btn" id="pc-rotate" type="button" disabled title="Auto-rotate (Space)" aria-label="Toggle auto-rotate">+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 12a9 9 0 1 1-3-6.7M21 4v4h-4"/></svg>+ </button>+ <button class="pc-icon-btn" id="pc-shot" type="button" disabled title="Save PNG (S)" aria-label="Save screenshot">+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 7h3l2-2h8l2 2h3v12H3z"/><circle cx="12" cy="13" r="3.5"/></svg>+ </button>+ <button class="pc-icon-btn" id="pc-recenter" type="button" disabled title="Recenter camera (R)" aria-label="Recenter camera"><svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><circle cx="12" cy="12" r="3"/><path d="M12 2v3 M12 19v3 M2 12h3 M19 12h3"/></svg></button><a class="pc-icon-btn" id="pc-download" title="Download .ply" aria-label="Download point cloud" hidden>@@ -258,6 +279,11 @@<svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M5 12h14 M13 5l7 7-7 7"/></svg>Reconstruct scene</button>+ <button class="pc-btn" id="pc-video-pick" type="button">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="m22 8-6 4 6 4V8Z"/><rect x="2" y="6" width="14" height="12" rx="2"/></svg>+ Upload a video+ </button>+ <input id="pc-video-file" type="file" accept="video/mp4,video/quicktime,video/webm" hidden /></div><details class="pc-adv"><summary>Reconstruction settings</summary>diff --git a/pages/create-agent.html b/pages/create-agent.htmlindex 38764ed01..c06f5c457 100644--- a/pages/create-agent.html+++ b/pages/create-agent.html@@ -1049,7 +1049,7 @@<meta property="og:locale" content="en_US"><meta property="og:image:alt" content="Create an Agent — three.ws"><meta name="twitter:site" content="@trythreews">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><div id="page-loading" aria-hidden="true">@@ -1501,7 +1501,10 @@</p><div class="success-preview" id="success-preview" hidden></div><div class="success-actions">- <a class="btn btn--primary btn--lg" id="success-fund" href="#"+ <a class="btn btn--primary btn--lg" id="success-activate" href="#"+ >⚡ Go live</a+ >+ <a class="btn btn--secondary btn--lg" id="success-fund" href="#">Fund agent wallet</a><a class="btn btn--secondary btn--lg" id="success-open" href="#"diff --git a/pages/create-prompt.html b/pages/create-prompt.htmlindex 5a8b37eb6..987c45616 100644--- a/pages/create-prompt.html+++ b/pages/create-prompt.html@@ -552,7 +552,7 @@<meta property="og:locale" content="en_US"><meta property="og:image:alt" content="Describe it to 3D — three.ws"><meta name="twitter:site" content="@trythreews">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><a href="#prompt" class="skip-link">Skip to the prompt box</a>diff --git a/pages/create-selfie.html b/pages/create-selfie.htmlindex 0ca4c2068..0e4a92ddd 100644--- a/pages/create-selfie.html+++ b/pages/create-selfie.html@@ -1363,7 +1363,7 @@<meta property="og:locale" content="en_US"><meta property="og:image:alt" content="Selfie to Avatar — three.ws"><meta name="twitter:site" content="@trythreews">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><main class="stage">diff --git a/pages/create.html b/pages/create.htmlindex 4857eb18b..91d7db2a4 100644--- a/pages/create.html+++ b/pages/create.html@@ -1056,7 +1056,7 @@<meta property="og:locale" content="en_US"><meta property="og:image:alt" content="Create Agent — three.ws"><meta name="twitter:site" content="@trythreews">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><div id="page-loading" aria-hidden="true">diff --git a/pages/create/video.html b/pages/create/video.htmlindex 8fd9e1012..586af32d1 100644--- a/pages/create/video.html+++ b/pages/create/video.html@@ -655,7 +655,7 @@}}</style>- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><a href="#main-content" class="skip-link">Skip to main content</a>diff --git a/pages/creating.html b/pages/creating.htmlindex 8bb880f58..cbbf70d2e 100644--- a/pages/creating.html+++ b/pages/creating.html@@ -251,7 +251,7 @@margin-bottom: 16px;}</style>- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><nav class="crumb">diff --git a/pages/diorama.html b/pages/diorama.htmlindex d8d4e30d2..62cd21e65 100644--- a/pages/diorama.html+++ b/pages/diorama.html@@ -52,7 +52,7 @@<link rel="stylesheet" href="/style.css" /><link rel="stylesheet" href="/src/diorama/diorama.css" />- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><!--diff --git a/pages/features.html b/pages/features.htmlindex ce91ba1f3..126657af1 100644--- a/pages/features.html+++ b/pages/features.html@@ -69,7 +69,7 @@<meta property="og:locale" content="en_US"><meta property="og:image:alt" content="Features — three.ws"><meta name="twitter:site" content="@trythreews">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script><style>/* ── Walking-avatar inline demo ─────────────────────────────────────diff --git a/pages/features/ar.html b/pages/features/ar.htmlindex de892a626..d1362f570 100644--- a/pages/features/ar.html+++ b/pages/features/ar.html@@ -105,7 +105,7 @@]}</script>- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body class="fl-page"><header><div id="nav-container"></div></header>diff --git a/pages/features/forge.html b/pages/features/forge.htmlindex 5f98c7937..5ae7e8cbd 100644--- a/pages/features/forge.html+++ b/pages/features/forge.html@@ -95,7 +95,7 @@]}</script>- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body class="fl-page"><header><div id="nav-container"></div></header>diff --git a/pages/features/scan.html b/pages/features/scan.htmlindex 499cfa6bf..6c9a385a8 100644--- a/pages/features/scan.html+++ b/pages/features/scan.html@@ -101,7 +101,7 @@]}</script>- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body class="fl-page"><header><div id="nav-container"></div></header>diff --git a/pages/features/walk.html b/pages/features/walk.htmlindex ecd97efff..ee8130bef 100644--- a/pages/features/walk.html+++ b/pages/features/walk.html@@ -87,7 +87,7 @@]}</script>- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body class="fl-page"><header><div id="nav-container"></div></header>diff --git a/pages/forge-embed.html b/pages/forge-embed.htmlindex 9283980f6..13e51ec94 100644--- a/pages/forge-embed.html+++ b/pages/forge-embed.html@@ -184,7 +184,7 @@background: radial-gradient(120% 120% at 50% 0%, #15151c 0%, #0b0b0f 70%);}</style>- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body data-bg="dark" data-state="ok"><div id="stage">diff --git a/pages/forge-spark.html b/pages/forge-spark.htmlindex 4d7f79bb2..9ebd5f6b5 100644--- a/pages/forge-spark.html+++ b/pages/forge-spark.html@@ -378,7 +378,7 @@</main><script src="/nav.js" defer></script>- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script><script type="module">const form = document.getElementById('composer');const promptEl = document.getElementById('prompt');diff --git a/pages/forge-studio.html b/pages/forge-studio.htmlindex 6afdbb67a..192caee0f 100644--- a/pages/forge-studio.html+++ b/pages/forge-studio.html@@ -3089,7 +3089,7 @@<meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1"><meta property="og:locale" content="en_US"><meta property="og:image:alt" content="Forge — Text to 3D — three.ws">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body class="forge-page"><div id="nav-container"></div>diff --git a/pages/forge.html b/pages/forge.htmlindex ba9b4c75d..b32dfad73 100644--- a/pages/forge.html+++ b/pages/forge.html@@ -2671,7 +2671,7 @@<meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1"><meta property="og:locale" content="en_US"><meta property="og:image:alt" content="Forge — Text to 3D — three.ws">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body class="forge-page"><div id="nav-container"></div>diff --git a/pages/gallery-picker.html b/pages/gallery-picker.htmlindex 16e733420..234a89ec5 100644--- a/pages/gallery-picker.html+++ b/pages/gallery-picker.html@@ -86,7 +86,7 @@border: 1px solid var(--stroke);}</style>- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><header><div id="nav-container"></div></header>diff --git a/pages/genesis.html b/pages/genesis.htmlindex 1398a436d..3e3702496 100644--- a/pages/genesis.html+++ b/pages/genesis.html@@ -288,7 +288,7 @@</section></main>- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script><script type="module" src="/src/genesis.js"></script><script src="/nav.js" defer></script><script src="/theme-switcher.js" defer></script>diff --git a/pages/home.html b/pages/home.htmlindex 378b13f47..e2bc83bca 100644--- a/pages/home.html+++ b/pages/home.html@@ -2514,7 +2514,7 @@<meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1"><meta property="og:locale" content="en_US">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body>diff --git a/pages/launcher.html b/pages/launcher.htmlnew file mode 100644index 000000000..aeae146bc--- /dev/null+++ b/pages/launcher.html@@ -0,0 +1,171 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash */(function(){document.documentElement.classList.add('js');try{var m=localStorage.getItem('twx_theme');var l=m==='auto'?(window.matchMedia&&window.matchMedia('(prefers-color-scheme: light)').matches):m==='light';document.documentElement.setAttribute('data-theme',l?'light':'dark');}catch(e){document.documentElement.setAttribute('data-theme','dark');}})();</script>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <title>Memetic Launcher · three.ws</title>+ <meta name="description" content="Your personal autonomous coin launcher — ride live cultural narratives and preview exactly what your agents would mint." />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/src/admin-launcher.css" />+ <link rel="stylesheet" href="/src/user-launcher.css" />+ </head>+ <body>+ <header><div id="nav-container"></div></header>+ <script src="/nav.js"></script>++ <main class="ml-shell" id="ul-root" aria-busy="true">+ <!-- Sign-in gate -->+ <section class="ml-gate" id="ul-gate" hidden>+ <div class="ml-gate-card">+ <div class="ml-gate-mark" aria-hidden="true">◎</div>+ <h1 class="ml-gate-title">Memetic Launcher</h1>+ <p class="ml-gate-sub">Sign in to design your own autonomous launcher.</p>+ <a class="ml-btn ml-btn-primary ml-gate-btn" id="ul-signin" href="/login?next=/launcher">Sign in</a>+ </div>+ </section>++ <div id="ul-panel" hidden>+ <!-- Hero -->+ <header class="ml-hero">+ <div class="ml-hero-l">+ <p class="ml-kicker"><span class="ml-dot" id="ul-status-dot"></span> Your autonomous launcher</p>+ <h1 class="ml-title">Memetic <em>Launcher</em></h1>+ <p class="ml-sub" id="ul-status-line">Loading…</p>+ </div>+ <div class="ml-hero-r">+ <span class="ul-badge" id="ul-badge" title="Preview only — no SOL moves">Preview</span>+ <button class="ml-btn ml-armswitch" id="ul-enable" aria-pressed="false">+ <span class="ml-armswitch-track"><span class="ml-armswitch-knob"></span></span>+ <span class="ml-armswitch-lbl" id="ul-enable-lbl">Off</span>+ </button>+ </div>+ </header>++ <!-- Honest explainer -->+ <div class="ul-note" id="ul-note">+ <span class="ul-note-ico" aria-hidden="true">◑</span>+ <p>+ <strong>Preview mode.</strong> Your launcher rides live cultural narratives and picks coins from your own+ agents on a schedule — recording each pick — but it mints nothing and moves no SOL. It is a strategy+ designer: tune it, watch what it would launch, and ship a great rotation. Real on-chain launches are+ funded separately and arrive next.+ </p>+ </div>++ <!-- Breaker (rare, but designed) -->+ <div class="ml-breaker" id="ul-breaker" hidden role="alert">+ <span class="ml-breaker-ico" aria-hidden="true">⚠</span>+ <span class="ml-breaker-txt" id="ul-breaker-txt">Paused.</span>+ <button class="ml-btn ml-btn-ghost" id="ul-resume">Resume</button>+ </div>++ <!-- Stats -->+ <dl class="ml-stats ul-stats">+ <div class="ml-stat ml-stat--lead"><dt>Coins previewed today</dt><dd id="ul-s-dry">—</dd></div>+ <div class="ml-stat"><dt>Agents in rotation</dt><dd id="ul-s-queue">—</dd></div>+ <div class="ml-stat"><dt>Launch-ready agents</dt><dd id="ul-s-eligible">—</dd></div>+ <div class="ml-stat"><dt>Mode</dt><dd id="ul-s-mode" class="ul-s-mode">—</dd></div>+ </dl>++ <div class="ml-grid">+ <!-- Config -->+ <form class="ml-config" id="ul-config" aria-label="Launcher configuration">+ <section class="ml-card">+ <h2 class="ml-card-h">Mode</h2>+ <p class="ml-card-help">What your launcher coins each tick.</p>+ <div class="ml-modes" id="ul-modes" role="radiogroup" aria-label="Launch mode"></div>+ </section>++ <section class="ml-card" id="ul-sources-card">+ <h2 class="ml-card-h">Trend sources</h2>+ <p class="ml-card-help">Culture mined to ride live narratives. Themes only — never clones a ticker.</p>+ <div class="ml-chips" id="ul-sources"></div>+ </section>++ <section class="ml-card">+ <h2 class="ml-card-h">Cadence & network</h2>+ <div class="ml-fields">+ <label class="ml-field">+ <span class="ml-field-lbl">Target cadence <em>seconds</em></span>+ <input type="number" min="60" max="86400" step="1" id="ul-cadence" class="ml-input" />+ <span class="ml-field-hint" id="ul-cadence-hint"></span>+ </label>+ <label class="ml-field">+ <span class="ml-field-lbl">Max / hour <em>ceiling</em></span>+ <input type="number" min="0" max="60" step="1" id="ul-maxhour" class="ml-input" />+ </label>+ </div>+ <div class="ml-net ul-net-row">+ <span class="ml-net-lbl">Network</span>+ <div class="ml-seg" id="ul-network" role="radiogroup" aria-label="Network">+ <button type="button" class="ml-seg-btn" data-net="mainnet" role="radio">Mainnet</button>+ <button type="button" class="ml-seg-btn" data-net="devnet" role="radio">Devnet</button>+ </div>+ </div>+ </section>++ <!-- Preview a coin -->+ <section class="ml-card ul-preview-card">+ <div class="ml-console-h">+ <h2 class="ml-card-h">Preview a coin</h2>+ <button type="button" class="ml-btn ml-btn-ghost ul-preview-btn" id="ul-preview-btn">Synthesize</button>+ </div>+ <p class="ml-card-help">See exactly what your launcher would mint next, riding the currents on the right.</p>+ <div class="ul-sample" id="ul-sample" hidden>+ <div class="ul-sample-head">+ <span class="ul-sample-name" id="ul-sample-name"></span>+ <span class="ul-sample-sym" id="ul-sample-sym"></span>+ </div>+ <p class="ul-sample-desc" id="ul-sample-desc"></p>+ <div class="ul-sample-meta" id="ul-sample-meta"></div>+ </div>+ <div class="ul-sample-empty" id="ul-sample-empty">+ <p>No preview yet. Hit <strong>Synthesize</strong> to coin one from the live narratives.</p>+ </div>+ </section>+ </form>++ <!-- Right rail -->+ <div class="ml-rail">+ <section class="ml-narr" aria-label="Live narratives">+ <div class="ml-console-h">+ <h2 class="ml-card-h">Live narratives</h2>+ <span class="ml-console-meta" id="ul-narr-meta">—</span>+ </div>+ <p class="ml-narr-lead" id="ul-narr-lead" hidden></p>+ <ol class="ml-narr-list" id="ul-narr-list"></ol>+ <div class="ml-narr-empty" id="ul-narr-empty" hidden>+ <p>No live narrative yet. Enable trend sources (Know Your Meme, Coin intel…) to surface the currents your launcher would ride.</p>+ </div>+ </section>++ <section class="ml-console" aria-label="Preview console">+ <div class="ml-console-h">+ <h2 class="ml-card-h">Preview console</h2>+ <span class="ml-console-meta" id="ul-console-meta">—</span>+ </div>+ <ol class="ml-runs" id="ul-runs"></ol>+ <div class="ml-runs-empty" id="ul-runs-empty" hidden>+ <p>No previews yet. Turn your launcher <strong>On</strong> to watch it pick coins every cadence.</p>+ </div>+ </section>+ </div>+ </div>+ </div>+ </main>++ <!-- Sticky save bar -->+ <div class="ml-savebar" id="ul-savebar" hidden role="region" aria-label="Unsaved changes">+ <span class="ml-savebar-txt" id="ul-savebar-txt">Unsaved changes</span>+ <div class="ml-savebar-actions">+ <button class="ml-btn ml-btn-ghost" id="ul-discard">Discard</button>+ <button class="ml-btn ml-btn-primary" id="ul-save">Save changes</button>+ </div>+ </div>++ <div class="ml-toast" id="ul-toast" hidden aria-live="polite"></div>++ <script type="module" src="/src/user-launcher.js"></script>+ </body>+</html>diff --git a/pages/marketplace-walk.html b/pages/marketplace-walk.htmlindex 6be6f4f69..e6c06fd62 100644--- a/pages/marketplace-walk.html+++ b/pages/marketplace-walk.html@@ -1302,6 +1302,14 @@instant scripts run (it lives in <noscript>), so it never touches theinteractive experience. --><noscript>+ <!-- With JS off, the 3D stage never boots and the loading overlay never+ clears — both would otherwise sit on top of this fallback forever.+ A <noscript> may carry its own styles: hide the JS-only chrome so the+ fallback is what a no-JS visitor (and many crawlers) actually see. -->+ <style>+ #walk-loading, #walk-stage, .walk-site-header { display: none !important; }+ html, body { overflow: auto !important; height: auto !important; background: #0a0a0a !important; }+ </style><div style="max-width:640px;margin:12vh auto;padding:0 24px;font-family:'Inter',system-ui,sans-serif;color:#fafafa;text-align:center;"><h1 style="font-size:26px;font-weight:700;letter-spacing:-0.01em;margin:0 0 12px;">Walk-Browse the Marketplace</h1><p style="font-size:15px;line-height:1.6;color:#a1a1aa;margin:0 0 24px;">diff --git a/pages/marketplace.html b/pages/marketplace.htmlindex 2c419a52a..f9fd7419b 100644--- a/pages/marketplace.html+++ b/pages/marketplace.html@@ -3094,7 +3094,7 @@<meta property="og:locale" content="en_US"><meta property="og:image:alt" content="Marketplace — three.ws"><meta name="twitter:site" content="@trythreews">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body class="market-page"><a class="skip-link" href="#main-content">Skip to content</a>diff --git a/pages/mint-success.html b/pages/mint-success.htmlindex 6df8e6c6f..a19d6e8e3 100644--- a/pages/mint-success.html+++ b/pages/mint-success.html@@ -149,7 +149,7 @@.ctas { flex-direction: column; align-items: stretch; }}</style>- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><canvas id="starfield" aria-hidden="true"></canvas>diff --git a/pages/pipeline.html b/pages/pipeline.htmlindex 19b13c671..13c6de770 100644--- a/pages/pipeline.html+++ b/pages/pipeline.html@@ -107,6 +107,11 @@.pl-subs li { display: flex; justify-content: space-between; gap: 8px; font-size: 0.7rem; color: var(--ink-dim, #888); }.pl-subs b { font-family: var(--font-mono, monospace); font-weight: 500; color: var(--ink, #e8e8e8); }.pl-stage-dot { margin-left: auto; }+ /* stage cards are links into each surface's detail view */+ a.pl-stage { text-decoration: none; color: inherit; cursor: pointer; }+ a.pl-stage:focus-visible { outline: 2px solid var(--ink-bright, #fff); outline-offset: 2px; }+ .pl-stage-go { position: absolute; right: 12px; bottom: 11px; font-size: 0.82rem; color: var(--ink-faint, rgba(255,255,255,0.45)); opacity: 0; transform: translateX(-3px); transition: opacity .18s, transform .18s, color .18s; }+ a.pl-stage:hover .pl-stage-go, a.pl-stage:focus-visible .pl-stage-go { opacity: 1; transform: none; color: var(--ink-bright, #fff); }/* ── Skeleton + error ────────────────────────────────────────── */.pl-skel { min-height: 158px; border-radius: var(--radius-lg, 14px); border: 1px solid var(--stroke, rgba(255,255,255,0.08)); background: linear-gradient(90deg, var(--surface-1, rgba(255,255,255,0.03)), var(--surface-3, rgba(255,255,255,0.08)), var(--surface-1, rgba(255,255,255,0.03))); background-size: 200% 100%; animation: pl-shimmer 1.4s linear infinite; }@@ -255,7 +260,9 @@function stageCard(m, i) {const subs = m.subs.map(([k, v]) => `<li><span>${esc(k)}</span><b>${esc(v)}</b></li>`).join('');- return `<article class="pl-stage s-${m.state}" style="animation-delay:${i * 45}ms">+ const tail = m.external ? ' target="_blank" rel="noopener"' : '';+ const aria = `aria-label="${esc(m.label)} — ${esc(m.vlabel)}. Open details"`;+ return `<a class="pl-stage s-${m.state}" href="${esc(m.href)}"${tail} ${aria} style="animation-delay:${i * 45}ms"><div class="pl-stage-top"><span class="pl-stage-n">${m.n}</span><h2 class="pl-stage-label">${esc(m.label)}</h2>@@ -267,7 +274,8 @@<div class="pl-stat-l">${esc(m.vlabel)}</div></div><ul class="pl-subs">${subs}</ul>- </article>`;+ <span class="pl-stage-go" aria-hidden="true">${m.external ? '↗' : '→'}</span>+ </a>`;}function renderHealth(data) {@@ -285,7 +293,16 @@? 'The worker is up but its feed has gone silent — no new launches are being recorded.': 'The pipeline is idle. Once the recorder worker starts, every downstream stage activates.';metaEl.textContent = `${data.network} · updated ${new Date(data.t).toLocaleTimeString([], { hour: '2-digit', minute: '2-digit', second: '2-digit' })}`;- ctaEl.hidden = !(rec.state === 'offline' || rec.state === 'down' || rec.state === 'unknown');+ // Drive the call-to-action straight from the endpoint's own guidance so+ // the page and any agent reading /api/pipeline tell the same story.+ const na = data.next_action || {};+ const actionable = na.step && !['running', 'accumulate', 'await_training'].includes(na.step);+ if (actionable) {+ ctaEl.innerHTML = `<h3>${esc(na.label)}</h3><p>${esc(na.detail)}${na.command ? ` <code>${esc(na.command)}</code>` : ''}</p>`;+ ctaEl.hidden = false;+ } else {+ ctaEl.hidden = true;+ }}async function load() {diff --git a/pages/playground.html b/pages/playground.htmlindex 53b660aab..5e2315477 100644--- a/pages/playground.html+++ b/pages/playground.html@@ -606,7 +606,7 @@<meta property="og:locale" content="en_US"><meta property="og:image:alt" content="Playground — three.ws"><meta name="twitter:site" content="@trythreews">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><header class="pg-header">diff --git a/pages/profile.html b/pages/profile.htmlindex ced74cd66..04cbe8f0a 100644--- a/pages/profile.html+++ b/pages/profile.html@@ -1189,7 +1189,7 @@</style><link rel="stylesheet" href="/nav.css" /><link rel="stylesheet" href="/mobile.css" />- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><header><div id="nav-container"></div></header>diff --git a/pages/pump-dashboard.html b/pages/pump-dashboard.htmlindex 69099ba7a..55fa1356a 100644--- a/pages/pump-dashboard.html+++ b/pages/pump-dashboard.html@@ -185,7 +185,7 @@<meta property="og:locale" content="en_US"><meta property="og:image:alt" content="Pump Dashboard — three.ws"><meta name="twitter:site" content="@trythreews">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body class="home-page pump-dashboard-page"><a href="#pd-main" class="h-skip-link">Skip to main content</a>diff --git a/pages/scan.html b/pages/scan.htmlindex aa0e011db..1ec6755a8 100644--- a/pages/scan.html+++ b/pages/scan.html@@ -1344,7 +1344,7 @@<meta property="og:locale" content="en_US"><meta property="og:image:alt" content="3D Scanner — Scan Yourself into 3D — three.ws"><meta name="twitter:site" content="@trythreews">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><main class="stage">diff --git a/pages/status.html b/pages/status.htmlindex c96a6725f..873613bc1 100644--- a/pages/status.html+++ b/pages/status.html@@ -73,11 +73,14 @@width: 12px;height: 12px;}+ /* Monochrome by design: a healthy platform reads in ink, not green.+ --danger (red) is reserved as the SINGLE exception for a genuine+ outage so it's unmistakable precisely because nothing else is colored. */.st-banner[data-state='ok'] {- border-color: rgba(74, 222, 128, 0.35);+ border-color: var(--ink);}.st-banner[data-state='down'] {- border-color: rgba(248, 113, 113, 0.45);+ border-color: var(--danger);}.st-dot {@@ -89,12 +92,12 @@transition: background 0.3s ease;}.st-dot[data-state='ok'] {- background: var(--success);- box-shadow: 0 0 8px rgba(74, 222, 128, 0.5);+ background: var(--ink);+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--ink) 14%, transparent);}.st-dot[data-state='down'] {background: var(--danger);- box-shadow: 0 0 8px rgba(248, 113, 113, 0.5);+ box-shadow: 0 0 0 3px color-mix(in srgb, var(--danger) 30%, transparent);}.st-meta {@@ -103,6 +106,51 @@margin: 0 0 calc(var(--space-md) * 1.5);}+ /* Fleet KPI band — three monochrome stats so the headline numbers are+ readable at a glance before scanning the per-service cards. */+ .st-summary {+ display: grid;+ grid-template-columns: repeat(3, 1fr);+ gap: 1px;+ background: var(--stroke);+ border: 1px solid var(--stroke);+ border-radius: var(--radius-lg);+ overflow: hidden;+ margin-bottom: calc(var(--space-md) * 1.5);+ }+ .st-kpi {+ background: var(--surface-1);+ padding: 0.9rem 1.1rem;+ transition: background 0.2s ease;+ }+ .st-kpi:hover {+ background: var(--surface-2);+ }+ .st-kpi-val {+ font-family: var(--font-mono, monospace);+ font-size: clamp(1.25rem, 3.2vw, 1.7rem);+ line-height: 1.1;+ color: var(--ink);+ font-variant-numeric: tabular-nums;+ }+ .st-kpi-label {+ font: var(--text-sm) var(--font-body);+ color: var(--ink-dim);+ margin-top: 0.3rem;+ }+ .st-summary.st-skel .st-kpi-val,+ .st-summary.st-skel .st-kpi-label {+ color: transparent;+ background: var(--surface-2);+ border-radius: var(--radius-md);+ animation: st-pulse 1.4s ease-in-out infinite;+ }+ @media (max-width: 480px) {+ .st-summary {+ grid-template-columns: 1fr;+ }+ }+.st-card {border: 1px solid var(--stroke);border-radius: var(--radius-lg);@@ -160,14 +208,16 @@outline: none;}.st-cell[data-band='up'] {- background: var(--success);- opacity: 0.85;+ background: var(--ink);+ opacity: 0.9;}.st-cell[data-band='degraded'] {- background: var(--warn);+ background: var(--ink);+ opacity: 0.34;}.st-cell[data-band='down'] {background: var(--danger);+ opacity: 0.92;}.st-bar-labels {display: flex;@@ -251,9 +301,16 @@<span class="st-dot" id="st-banner-dot" aria-hidden="true"></span><span id="st-banner-text">Checking platform status…</span></div>+ <div class="st-summary st-skel" id="st-summary" aria-label="Fleet summary">+ <div class="st-kpi"><div class="st-kpi-val" id="st-kpi-uptime">—</div><div class="st-kpi-label">90-day uptime</div></div>+ <div class="st-kpi"><div class="st-kpi-val" id="st-kpi-services">—</div><div class="st-kpi-label">services operational</div></div>+ <div class="st-kpi"><div class="st-kpi-val" id="st-kpi-latency">—</div><div class="st-kpi-label">avg response</div></div>+ </div>+<p class="st-meta" id="st-meta">Probed every 5 minutes from outside our infrastructure.<a href="/api/status" style="color: inherit">JSON feed</a> ·+ <a href="/api/status?format=svg" style="color: inherit">status badge</a> ·<a href="/changelog" style="color: inherit">Changelog</a></p>@@ -280,12 +337,43 @@const bannerText = document.getElementById('st-banner-text');const meta = document.getElementById('st-meta');const list = document.getElementById('st-services');+ const summaryEl = document.getElementById('st-summary');+ const kpiUptime = document.getElementById('st-kpi-uptime');+ const kpiServices = document.getElementById('st-kpi-services');+ const kpiLatency = document.getElementById('st-kpi-latency');const fmtPct = (v) => (v == null ? '—' : `${v}%`);const band = (uptime) =>uptime == null ? null : uptime >= 99.5 ? 'up' : uptime >= 95 ? 'degraded' : 'down';+ const avg = (a) => (a.length ? a.reduce((x, y) => x + y, 0) / a.length : null);++ function renderSummary(data) {+ const services = data.services || [];+ // Prefer the server-computed summary (single source of truth shared+ // with agents reading the JSON); fall back to a client-side roll-up so+ // the band still fills if an older API shape omits it.+ const s =+ data.summary ||+ (() => {+ const probed = services.filter((x) => x.operational !== null);+ const lat = services.map((x) => x.avgLatency24hMs).filter((n) => n != null);+ const u90 = services.map((x) => x.uptime90d).filter((n) => n != null);+ const a = avg(u90);+ return {+ operational: probed.filter((x) => x.operational).length,+ total: services.length,+ avgLatencyMs: lat.length ? Math.round(avg(lat)) : null,+ fleetUptime90d: a == null ? null : Math.round(a * 100) / 100,+ };+ })();+ summaryEl.classList.remove('st-skel');+ kpiUptime.textContent = s.fleetUptime90d == null ? '—' : `${s.fleetUptime90d}%`;+ kpiServices.textContent = `${s.operational}/${s.total}`;+ kpiLatency.textContent = s.avgLatencyMs == null ? '—' : `${s.avgLatencyMs}ms`;+ }function render(data) {+ renderSummary(data);const probed = data.services.filter((s) => s.operational !== null);const down = probed.filter((s) => !s.operational);if (data.monitoring === 'warming-up') {@@ -344,6 +432,10 @@function renderError() {bannerText.textContent = 'Could not load status data.';+ summaryEl.classList.remove('st-skel');+ kpiUptime.textContent = '—';+ kpiServices.textContent = '—';+ kpiLatency.textContent = '—';list.innerHTML = `<div class="st-note st-error">The status feed at <a href="/api/status">/api/status</a> did not respond.That can itself indicate an incident — try again in a minute, or checkdiff --git a/pages/tutorial.html b/pages/tutorial.htmlindex 371786c94..55ed36f00 100644--- a/pages/tutorial.html+++ b/pages/tutorial.html@@ -877,7 +877,7 @@<meta property="og:locale" content="en_US"><meta property="og:image:alt" content="Tutorial · Text Prompt to 3D Model — three.ws"><meta name="twitter:site" content="@trythreews">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body class="home-page tutorial-page tut-doc-page"><div class="cursor" id="cursor" aria-hidden="true"></div>diff --git a/pages/tutorials.html b/pages/tutorials.htmlindex 10c4e8da3..052536faf 100644--- a/pages/tutorials.html+++ b/pages/tutorials.html@@ -479,7 +479,7 @@<meta property="og:locale" content="en_US"><meta property="og:image:alt" content="Tutorials — three.ws"><meta name="twitter:site" content="@trythreews">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body class="home-page tutorials-page tut-page"><div class="cursor" id="cursor" aria-hidden="true"></div>diff --git a/pages/what-is.html b/pages/what-is.htmlindex e35f1dfbd..f00df20a3 100644--- a/pages/what-is.html+++ b/pages/what-is.html@@ -96,7 +96,7 @@<meta property="og:locale" content="en_US"><meta property="og:image:alt" content="What is three.ws? — three.ws"><meta name="twitter:site" content="@trythreews">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body class="fl-page"><header><div id="nav-container"></div></header>diff --git a/pages/worlds.html b/pages/worlds.htmlindex 6b9d5d872..7513a72d8 100644--- a/pages/worlds.html+++ b/pages/worlds.html@@ -682,7 +682,7 @@}}</style>- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><div class="wl-shell">diff --git a/public/changelog.json b/public/changelog.jsonindex f3b6d0861..73aefd5db 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-27T21:42:54.736Z",+ "generated_at": "2026-06-27T22:01:30.566Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -107,6 +107,17 @@"feature"]},+ {+ "date": "2026-06-27",+ "type": "update",+ "title": "Autonomous coin launcher — creator fees, revenue tracking, and admin console upgrades",+ "summary": "The memetic launcher now auto-claims pump.fun creator fees from every coin it mints, routing the configured share toward $THREE. The admin console at /admin/launcher gains a live revenue panel (total creator fees claimed, $THREE allocated), agent-name visibility in the run feed, a Force Tick button for instant testing, and a cleaner 8-column stat grid. Know Your Meme is wired as a live trend source alongside Hacker News, Reddit, and Wikipedia — so the launcher reads what the internet is actually minting.",+ "link": "/admin/launcher",+ "tags": [+ "feature",+ "improvement"+ ]+ },{"date": "2026-06-27","type": "update",@@ -118,6 +129,16 @@"improvement"]},+ {+ "date": "2026-06-27",+ "type": "update",+ "title": "Design your own Memetic Launcher",+ "summary": "Every account now has a personal Memetic Launcher at /launcher — your own autonomous coin-launch strategy designer. Pick a mode (ride live cultural trends, coin original memes, or pure random volume), choose which sources it mines (Coin Intel, Trending, Know Your Meme, X, Reddit, Hacker News, Wikipedia and more), set a cadence, and turn it on. It then rotates through your own agents and, every tick, picks exactly the coin it would mint — riding the strongest live narrative — and records it. A live narratives panel shows the cultural currents ranked in real time, and a one-tap Synthesize button coins a sample on demand. It runs in preview: it designs and shows your rotation without minting or moving any SOL, so you can perfect a strategy risk-free. Find it under Launch in the main menu.",+ "link": "/launcher",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-27","type": "update",@@ -128,6 +149,17 @@"fix"]},+ {+ "date": "2026-06-27",+ "type": "update",+ "title": "Hardened how the platform reads its rate-limit store credentials",+ "summary": "Fixed a configuration failure mode where the rate-limiter and cache store's address and access token could be drawn from two different sources and silently mismatch, which made every limiter and cache fall back to a weaker local mode and caused intermittent 'too many requests' errors and failed paid calls. The credentials are now always read together as one pair (and trimmed of stray whitespace), so a mismatch can't happen — keeping rate limits, paid endpoints, and caching reliable.",+ "link": "/status",+ "tags": [+ "fix",+ "infra"+ ]+ },{"date": "2026-06-27","type": "update",@@ -161,6 +193,19 @@"improvement"]},+ {+ "date": "2026-06-27",+ "type": "update",+ "title": "Live Agents is now everywhere it should be — and steadier under the hood",+ "summary": "Watching agents work is far easier to find and more reliable. Live Agents now has its own spot in the Discover menu, every agent profile has a Watch live button, the embedded watch panel links straight to the full-screen viewer, and the viewer has a one-tap path back to the whole live grid. Under the hood: the live roster no longer accumulates stale agents, queuing a task no longer blanks the screen image, a viewer landing on an offline agent now sees a clear offline state instead of hanging on 'connecting', and screen frames are restricted to safe image formats. The browser agent's idle behaviour is also neutral now — when it has no task it simply stands by on its three.ws home rather than wandering, and it never surfaces third-party tokens.",+ "link": "/agents-live",+ "tags": [+ "feature",+ "improvement",+ "fix",+ "security"+ ]+ },{"date": "2026-06-27","type": "update",@@ -175,7 +220,7 @@"date": "2026-06-27","type": "update","title": "Live cultural narratives — now public, and now powered by Google Trends",- "summary": "The autonomous launcher's trend intelligence got broader and more open. Alongside Know Your Meme, it now reads Google Daily Search Trends — the broadest real-time signal of what the world is paying attention to — with a brand-safety gate that reads the news behind each trend and drops anything tied to tragedy before it can ever become a coin theme. And the ranked narratives are now a public, read-only feed at /api/launcher/narratives: any agent (or builder) can ask what's trending right now, with the sources confirming each wave, and ride a real current instead of guessing. Themes only — names and tickers are always invented fresh, never copied.",+ "summary": "The autonomous launcher's trend intelligence got broader and more open. Alongside Know Your Meme, it now reads Google Daily Search Trends — the broadest real-time signal of what the world is paying attention to — with a brand-safety gate that reads the news behind each trend and drops anything tied to tragedy before it can ever become a coin theme. And the ranked narratives are now a public, read-only feed at /api/launcher/trends: any agent (or builder) can ask what's trending right now — optionally filtered to specific sources — with the signals confirming each wave, and ride a real current instead of guessing. Themes only — names and tickers are always invented fresh, never copied.","link": null,"tags": ["feature",@@ -277,6 +322,27 @@"security"]},+ {+ "date": "2026-06-27",+ "type": "update",+ "title": "Sign-up and 3D avatar reliability fixes",+ "summary": "Two fixes to the front door. The 3D avatar on the sign-up page — and on roughly fifty other pages that show a preview model — now loads reliably the first time, instead of occasionally staying blank until you reloaded; a timing race meant the model viewer could start loading a compressed avatar before its decoder was ready. Separately, the sign-up username field again enforces its rules (3–30 characters; letters, numbers, underscore and hyphen) as you type in the latest Chrome, where a stricter pattern-matching mode had quietly switched that live validation off. No action needed — both are automatic.",+ "link": "/register",+ "tags": [+ "fix"+ ]+ },+ {+ "date": "2026-06-27",+ "type": "update",+ "title": "Status page goes monochrome — with a fleet summary and an embeddable status badge",+ "summary": "The platform status page now leads with three at-a-glance numbers — 90-day uptime, services operational, and average response time — above the per-service history, and reads in clean monochrome that matches the rest of three.ws (a single red is reserved for a genuine outage so it's impossible to miss). The public status feed now also serves an embeddable status badge: drop https://three.ws/api/status?format=svg into any README or dashboard to show whether the platform is operational, and agents reading /api/status get the same fleet summary as a ready-made object.",+ "link": "/status",+ "tags": [+ "feature",+ "improvement"+ ]+ },{"date": "2026-06-27","type": "update",@@ -310,6 +376,16 @@"improvement"]},+ {+ "date": "2026-06-27",+ "type": "update",+ "title": "Walk-Browse the Marketplace is now monochrome and agent-readable",+ "summary": "The 3D marketplace hall now reads as one cohesive monochrome material — type identity (agent/avatar/skill) is carried by brightness and clear labels instead of off-system brand colours, matching the rest of three.ws. And because the hall needs WebGL, the page now ships a no-script fallback: search crawlers, AI agents, and any visitor without JavaScript get a clean page with real, followable links into the agents, avatars, and skills catalogues instead of a blank loading spinner.",+ "link": "/marketplace-walk",+ "tags": [+ "improvement"+ ]+ },{"date": "2026-06-27","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex c8a8f4594..f049b94b5 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -86,6 +86,14 @@<category>feature</category><description>three.ws joins the Alibaba Cloud Partner Network. Qwen-Max, Qwen-Plus, Qwen-Turbo, and Qwen-Long are now available as agent brain options via DashScope. Ships with @three-ws/alibaba-cloud-mcp — a new MCP server for chat, embeddings, and model discovery using your own Alibaba Cloud API key. Set DASHSCOPE_API_KEY in Vercel to activate.</description></item>+ <item>+ <title>Autonomous coin launcher — creator fees, revenue tracking, and admin console upgrades</title>+ <link>https://three.ws/admin/launcher</link>+ <guid isPermaLink="false">2026-06-27:Autonomous coin launcher — creator fees, revenue tracking, and admin console upgrades</guid>+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The memetic launcher now auto-claims pump.fun creator fees from every coin it mints, routing the configured share toward $THREE. The admin console at /admin/launcher gains a live revenue panel (total creator fees claimed, $THREE allocated), agent-name visibility in the run feed, a Force Tick button for instant testing, and a cleaner 8-column stat grid. Know Your Meme is wired as a live trend source alongside Hacker News, Reddit, and Wikipedia — so the launcher reads what the internet is actually minting.</description>+ </item><item><title>Capabilities dashboard — live command center for all 4 autonomous features</title><link>https://three.ws/dashboard/capabilities</link>@@ -94,6 +102,14 @@<category>feature</category><description>New /dashboard/capabilities page surfaces live status for Alpha Hunt, Coin Launcher, Auto-Claim, and Market Maker in one view. KPI strips show daily budget, total volume, claimable fees, and net P&L per capability. Tabbed tables show launched coins, schedule status, per-market inventory bars, and recent MM trades. Alpha Hunt trigger is now also configurable directly from the Sniper Strategies dashboard — full field set including min smart-money count, quality score, organic score, max market cap, and narrative keywords.</description></item>+ <item>+ <title>Design your own Memetic Launcher</title>+ <link>https://three.ws/launcher</link>+ <guid isPermaLink="false">2026-06-27:Design your own Memetic Launcher</guid>+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Every account now has a personal Memetic Launcher at /launcher — your own autonomous coin-launch strategy designer. Pick a mode (ride live cultural trends, coin original memes, or pure random volume), choose which sources it mines (Coin Intel, Trending, Know Your Meme, X, Reddit, Hacker News, Wikipedia and more), set a cadence, and turn it on. It then rotates through your own agents and, every tick, picks exactly the coin it would mint — riding the strongest live narrative — and records it. A live narratives panel shows the cultural currents ranked in real time, and a one-tap Synthesize button coins a sample on demand. It runs in preview: it designs and shows your rotation without minting or moving any SOL, so you can perfect a strategy risk-free. Find it under Launch in the main menu.</description>+ </item><item><title>Fixed /play getting stuck on "too many requests"</title><link>https://three.ws/play</link>@@ -102,6 +118,14 @@<category>fix</category><description>Opening /play could dead-end on a "Something went wrong — too many requests" screen, especially from a shared network or after a couple of reloads. The wallet sign-in step was sharing the same strict rate limit as login and trading, so a small burst of page loads exhausted it. Sign-in now has its own generous limit sized for a busy world, and if that check ever can't be reached, /play opens anyway instead of blocking — the game server still verifies token-gated worlds on entry.</description></item>+ <item>+ <title>Hardened how the platform reads its rate-limit store credentials</title>+ <link>https://three.ws/status</link>+ <guid isPermaLink="false">2026-06-27:Hardened how the platform reads its rate-limit store credentials</guid>+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>Fixed a configuration failure mode where the rate-limiter and cache store's address and access token could be drawn from two different sources and silently mismatch, which made every limiter and cache fall back to a weaker local mode and caused intermittent 'too many requests' errors and failed paid calls. The credentials are now always read together as one pair (and trimmed of stray whitespace), so a mismatch can't happen — keeping rate limits, paid endpoints, and caching reliable.</description>+ </item><item><title>Hardened Redis credentials against dashboard paste errors</title><link>https://three.ws/changelog</link>@@ -126,6 +150,14 @@<category>fix</category><description>Watching agents work — their live screens, avatar cam, and activity feed — is back. A missing rate-limit binding had been crashing the endpoints behind the scenes, so the roster on /agents-live never populated, agents couldn't broadcast frames, and tasks wouldn't queue; all three paths now respond correctly. The Live Agents grid and the single-agent screen viewer were also rebuilt in a crisp monochrome palette, and the watch grid now pauses its streams when the tab is in the background so it stays light on bandwidth.</description></item>+ <item>+ <title>Live Agents is now everywhere it should be — and steadier under the hood</title>+ <link>https://three.ws/agents-live</link>+ <guid isPermaLink="false">2026-06-27:Live Agents is now everywhere it should be — and steadier under the hood</guid>+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>Watching agents work is far easier to find and more reliable. Live Agents now has its own spot in the Discover menu, every agent profile has a Watch live button, the embedded watch panel links straight to the full-screen viewer, and the viewer has a one-tap path back to the whole live grid. Under the hood: the live roster no longer accumulates stale agents, queuing a task no longer blanks the screen image, a viewer landing on an offline agent now sees a clear offline state instead of hanging on 'connecting', and screen frames are restricted to safe image formats. The browser agent's idle behaviour is also neutral now — when it has no task it simply stands by on its three.ws home rather than wandering, and it never surfaces third-party tokens.</description>+ </item><item><title>Live Agents mission control + one-click session launcher</title><link>https://three.ws/agents-live</link>@@ -140,7 +172,7 @@<guid isPermaLink="false">2026-06-27:Live cultural narratives — now public, and now powered by Google Trends</guid><pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate><category>feature</category>- <description>The autonomous launcher's trend intelligence got broader and more open. Alongside Know Your Meme, it now reads Google Daily Search Trends — the broadest real-time signal of what the world is paying attention to — with a brand-safety gate that reads the news behind each trend and drops anything tied to tragedy before it can ever become a coin theme. And the ranked narratives are now a public, read-only feed at /api/launcher/narratives: any agent (or builder) can ask what's trending right now, with the sources confirming each wave, and ride a real current instead of guessing. Themes only — names and tickers are always invented fresh, never copied.</description>+ <description>The autonomous launcher's trend intelligence got broader and more open. Alongside Know Your Meme, it now reads Google Daily Search Trends — the broadest real-time signal of what the world is paying attention to — with a brand-safety gate that reads the news behind each trend and drops anything tied to tragedy before it can ever become a coin theme. And the ranked narratives are now a public, read-only feed at /api/launcher/trends: any agent (or builder) can ask what's trending right now — optionally filtered to specific sources — with the signals confirming each wave, and ride a real current instead of guessing. Themes only — names and tickers are always invented fresh, never copied.</description></item><item><title>Manage your AWS Marketplace API key — new keys & usage page</title>@@ -214,6 +246,22 @@<category>fix</category><description>Fixed an issue where a temporary outage of the distributed rate limiter could block every sign-in attempt platform-wide. The login and registration limiters now degrade gracefully to a local per-instance cap during such an outage — keeping sign-in available while still throttling brute-force attempts — instead of denying everyone. Money-moving limits are unchanged and still fail safe.</description></item>+ <item>+ <title>Sign-up and 3D avatar reliability fixes</title>+ <link>https://three.ws/register</link>+ <guid isPermaLink="false">2026-06-27:Sign-up and 3D avatar reliability fixes</guid>+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>Two fixes to the front door. The 3D avatar on the sign-up page — and on roughly fifty other pages that show a preview model — now loads reliably the first time, instead of occasionally staying blank until you reloaded; a timing race meant the model viewer could start loading a compressed avatar before its decoder was ready. Separately, the sign-up username field again enforces its rules (3–30 characters; letters, numbers, underscore and hyphen) as you type in the latest Chrome, where a stricter pattern-matching mode had quietly switched that live validation off. No action needed — both are automatic.</description>+ </item>+ <item>+ <title>Status page goes monochrome — with a fleet summary and an embeddable status badge</title>+ <link>https://three.ws/status</link>+ <guid isPermaLink="false">2026-06-27:Status page goes monochrome — with a fleet summary and an embeddable status badge</guid>+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The platform status page now leads with three at-a-glance numbers — 90-day uptime, services operational, and average response time — above the per-service history, and reads in clean monochrome that matches the rest of three.ws (a single red is reserved for a genuine outage so it's impossible to miss). The public status feed now also serves an embeddable status badge: drop https://three.ws/api/status?format=svg into any README or dashboard to show whether the platform is operational, and agents reading /api/status get the same fleet summary as a ready-made object.</description>+ </item><item><title>Task input on Agent Screen — send your agent a task and watch it work</title><link>https://three.ws/agent-screen</link>@@ -238,6 +286,14 @@<category>feature</category><description>The marketplace now surfaces the top 3 oracle-performing agents in trophy-style cards above the agent grid. Each card shows oracle win rate, W/L record, and realized PnL. Rank 1 gets gold, rank 2 silver, rank 3 bronze. Cards shimmer while loading and disappear cleanly when no oracle data exists. Links directly to each agent's profile.</description></item>+ <item>+ <title>Walk-Browse the Marketplace is now monochrome and agent-readable</title>+ <link>https://three.ws/marketplace-walk</link>+ <guid isPermaLink="false">2026-06-27:Walk-Browse the Marketplace is now monochrome and agent-readable</guid>+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>+ <category>improvement</category>+ <description>The 3D marketplace hall now reads as one cohesive monochrome material — type identity (agent/avatar/skill) is carried by brightness and clear labels instead of off-system brand colours, matching the rest of three.ws. And because the hall needs WebGL, the page now ships a no-script fallback: search crawlers, AI agents, and any visitor without JavaScript get a clean page with real, followable links into the agents, avatars, and skills catalogues instead of a blank loading spinner.</description>+ </item><item><title>Wallet sign-in fixed and a cleaner, monochrome login</title><link>https://three.ws/changelog</link>diff --git a/public/dashboard/index.html b/public/dashboard/index.htmlindex 105ca3438..38df09731 100644--- a/public/dashboard/index.html+++ b/public/dashboard/index.html@@ -1300,7 +1300,7 @@crossorigin="anonymous"></script><script type="module" src="/session-client.js"></script>- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><div id="forge-announce" class="dash-announce" role="region" aria-label="Announcement">diff --git a/public/demos-embed/gallery.html b/public/demos-embed/gallery.htmlindex cc1e449ed..0b6c54593 100644--- a/public/demos-embed/gallery.html+++ b/public/demos-embed/gallery.html@@ -158,7 +158,7 @@.gallery-grid-wrap { background: transparent !important; }.gallery-main { background: transparent !important; padding-top: 0 !important; }</style>- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body class="gallery-page" style="background:transparent"><main class="gallery-main">diff --git a/public/demos/create-v2.html b/public/demos/create-v2.htmlindex 5b9d0fa4f..0adf76de1 100644--- a/public/demos/create-v2.html+++ b/public/demos/create-v2.html@@ -322,7 +322,7 @@.stats-divider { display: none; }}</style>- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><div class="demo-banner">diff --git a/public/demos/gallery-picker.html b/public/demos/gallery-picker.htmlindex 1016cbb14..9f687d000 100644--- a/public/demos/gallery-picker.html+++ b/public/demos/gallery-picker.html@@ -164,7 +164,7 @@}.error { color: #ff8888; border-color: #3a1f2b; }</style>- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><header><div id="nav-container"></div></header>diff --git a/public/demos/usdz-ar.html b/public/demos/usdz-ar.htmlindex b25ab2c42..281561df2 100644--- a/public/demos/usdz-ar.html+++ b/public/demos/usdz-ar.html@@ -49,7 +49,7 @@.log .err { color: #ff6b6b; }.log .info { color: #66d9ef; }</style>- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><header><div id="nav-container"></div></header>diff --git a/public/discover/index.html b/public/discover/index.htmlindex 829636a29..a0ff671c2 100644--- a/public/discover/index.html+++ b/public/discover/index.html@@ -56,7 +56,7 @@<meta property="og:locale" content="en_US"><meta property="og:image:alt" content="Discover — three.ws"><meta name="twitter:site" content="@trythreews">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body class="features-page explore-page"><header>diff --git a/public/docs-widgets.html b/public/docs-widgets.htmlindex 4e35097e1..0a49d7a47 100644--- a/public/docs-widgets.html+++ b/public/docs-widgets.html@@ -140,7 +140,7 @@<meta property="og:locale" content="en_US"><meta property="og:image:alt" content="Docs · Widgets — three.ws"><meta name="twitter:site" content="@trythreews">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body class="gallery-body"><header>diff --git a/public/features.json b/public/features.jsonindex 5c8bfe881..68d8814a9 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-27T21:42:54.716Z",+ "generated_at": "2026-06-27T22:01:30.398Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/forgot-password.html b/public/forgot-password.htmlindex 67b112fb6..a02e04cad 100644--- a/public/forgot-password.html+++ b/public/forgot-password.html@@ -159,7 +159,7 @@<meta property="og:locale" content="en_US"><meta property="og:image:alt" content="Forgot password — three.ws"><meta name="twitter:site" content="@trythreews">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><div class="shell">diff --git a/public/gallery/index.html b/public/gallery/index.htmlindex 7854aa20f..723386a29 100644--- a/public/gallery/index.html+++ b/public/gallery/index.html@@ -42,7 +42,7 @@<meta property="og:locale" content="en_US"><meta property="og:image:alt" content="Avatar Gallery — three.ws"><meta name="twitter:site" content="@trythreews">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body class="gallery-page"><header>diff --git a/public/gmgn.html b/public/gmgn.htmlindex 2b777ebd5..7e6255155 100644--- a/public/gmgn.html+++ b/public/gmgn.html@@ -174,7 +174,7 @@<meta name="robots" content="index, follow, max-image-preview:large, max-snippet:-1"><meta property="og:locale" content="en_US"><meta property="og:image:alt" content="GMGN Smart Money — three.ws">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body class="home-page"><script>window.__PAGE_INIT_TS = Date.now();</script>diff --git a/public/login.html b/public/login.htmlindex 8a76e7908..97a96d07a 100644--- a/public/login.html+++ b/public/login.html@@ -519,7 +519,7 @@<meta property="og:locale" content="en_US"><meta property="og:image:alt" content="Sign in — three.ws"><meta name="twitter:site" content="@trythreews">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><a href="#main-content" class="skip-link">Skip to main content</a>diff --git a/public/lookup.html b/public/lookup.htmlindex 34fee68e5..c5287a8f6 100644--- a/public/lookup.html+++ b/public/lookup.html@@ -389,7 +389,7 @@<meta property="og:locale" content="en_US"><meta property="og:image:alt" content="Agent Lookup — three.ws"><meta name="twitter:site" content="@trythreews">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><a href="#main-content" class="skip-link">Skip to main content</a>diff --git a/public/marketplace.css b/public/marketplace.cssindex 71da7c252..ebcf4b3ca 100644--- a/public/marketplace.css+++ b/public/marketplace.css@@ -1388,6 +1388,13 @@ body.market-page > header {font-weight: 600;}+.live-badge {+ background: color-mix(in srgb, var(--success, #4ade80) 12%, transparent);+ color: var(--success, #4ade80);+ font-weight: 600;+ border-color: color-mix(in srgb, var(--success, #4ade80) 30%, transparent);+}+.skill-price-badge {background: rgba(74, 222, 128, 0.12);color: var(--success);diff --git a/public/model-viewer-meshopt.js b/public/model-viewer-meshopt.jsindex c798c749d..c042fdc7b 100644--- a/public/model-viewer-meshopt.js+++ b/public/model-viewer-meshopt.js@@ -1,22 +1,68 @@-// Registers the EXT_meshopt_compression decoder with <model-viewer>.+// Registers the EXT_meshopt_compression decoder with <model-viewer> as early as+// possible — before any <model-viewer> begins loading, including an eager,+// above-the-fold one whose GLB ships meshopt-compressed.//-// model-viewer auto-loads the Draco and KTX2 decoders, but leaves the Meshopt-// decoder unset. Every server-baked avatar (the /api/avatars/<id>/glb lane and-// Forge output) emits EXT_meshopt_compression, so without this the viewer throws-// "THREE.GLTFLoader: setMeshoptDecoder must be called before loading compressed-// files" and the model never renders.+// model-viewer auto-loads the Draco and KTX2 decoders but leaves Meshopt unset.+// Every server-baked avatar (the /api/avatars/<id>/glb lane and Forge output)+// emits EXT_meshopt_compression, so without this the viewer throws+// "THREE.GLTFLoader: setMeshoptDecoder must be called before loading+// compressed files"+// and the model never renders.//-// Setting the static `meshoptDecoderLocation` makes model-viewer lazily fetch-// the UMD decoder (it defines a global `MeshoptDecoder`) and register it on its-// GLTFLoader before loading compressed files. This runs once globally and is a-// harmless no-op on pages whose GLBs are uncompressed.-const MESHOPT_DECODER_URL = 'https://cdn.jsdelivr.net/npm/[email protected]/meshopt_decoder.js';+// Timing matters: model-viewer captures its loader's decoder config at the moment+// a load STARTS, not when the GLB finishes downloading. Setting the static+// `meshoptDecoderLocation` after a load has begun is too late — the in-flight+// loader was already built without it. A deferred module that runs *after*+// model-viewer's own module therefore loses the race for an eager element (the+// element upgrades and loads in the microtask between the two module scripts —+// exactly the cz.glb failure seen on /register).+//+// To always win that race this file:+// 1. sets the property synchronously if the element is already defined,+// 2. intercepts customElements.define() so the property is set the instant+// 'model-viewer' is defined — before the element upgrades and loads, and+// 3. keeps a whenDefined() fallback for older browsers.+//+// Load it as a CLASSIC script (no type="module"). Classic scripts execute during+// parsing, before deferred module scripts (model-viewer is one), so the define()+// interceptor is installed before model-viewer is ever defined. It has no imports+// or exports, so it also runs correctly if a page still loads it as a module.+(function () {+ if (!window.customElements) return;+ var DECODER_URL = 'https://cdn.jsdelivr.net/npm/[email protected]/meshopt_decoder.js';++ function applyTo(ctor) {+ // `meshoptDecoderLocation` is a writable static on model-viewer; guard the+ // assignment so a future read-only build degrades to a no-op rather than+ // throwing and taking the page's module graph down with it.+ if (ctor && !ctor.meshoptDecoderLocation) {+ try {+ ctor.meshoptDecoderLocation = DECODER_URL;+ } catch (e) {+ /* property not writable in this build — nothing more we can do */+ }+ }+ }++ // 1. Helper ran after model-viewer was defined → set it now, synchronously.+ applyTo(customElements.get('model-viewer'));-customElements.whenDefined('model-viewer').then((resolved) => {- // Modern browsers resolve whenDefined() with the element constructor; older- // ones resolve with undefined, so fall back to the registry lookup.- const ModelViewerElement = resolved || customElements.get('model-viewer');- if (ModelViewerElement && !ModelViewerElement.meshoptDecoderLocation) {- ModelViewerElement.meshoptDecoderLocation = MESHOPT_DECODER_URL;+ // 2. Helper ran before model-viewer was defined (classic script during parse)+ // → patch define() so the decoder is registered the moment the element is+ // defined, before its first reactive update kicks off a load. Idempotent:+ // a flag prevents double-wrapping if this file is included twice.+ if (!customElements.get('model-viewer') && !customElements.__meshoptDefinePatched) {+ customElements.__meshoptDefinePatched = true;+ var nativeDefine = customElements.define;+ customElements.define = function (name, ctor, options) {+ var result = nativeDefine.call(this, name, ctor, options);+ if (name === 'model-viewer') applyTo(ctor);+ return result;+ };}-});++ // 3. Belt-and-suspenders: covers any path where (1) and (2) both miss.+ customElements.whenDefined('model-viewer').then(function (resolved) {+ applyTo(resolved || customElements.get('model-viewer'));+ });+})();diff --git a/public/nav-data.js b/public/nav-data.jsindex dd36cfb7e..63e007883 100644--- a/public/nav-data.js+++ b/public/nav-data.js@@ -154,6 +154,13 @@ export const NAV_GROUPS = [desc: 'Pool capital with other agents into one auditable treasury — it trades on reputation-weighted consensus and pays profit back pro-rata on-chain',},{ title: 'Agents Index', href: '/agents', desc: 'Browse every registered agent' },+ {+ title: 'Live Agents',+ href: '/agents-live',+ badge: 'Live',+ badgeTone: 'live',+ desc: 'Watch agents work in real time — live screens + avatar cams as they browse, research, and operate',+ },{ title: 'Marketplace', href: '/marketplace', desc: 'Buy, sell & remix agents' },{ title: 'Avatar Gallery', href: '/gallery', desc: 'Every public 3D avatar' },{ title: 'Animation Gallery', href: '/animations', desc: 'Community animations for avatars' },@@ -191,6 +198,13 @@ export const NAV_GROUPS = [href: '/launch',desc: 'Mint a coin for your agent on pump.fun',},+ {+ title: 'Memetic Launcher',+ href: '/launcher',+ badge: 'New',+ badgeTone: 'live',+ desc: 'Your autonomous launcher — ride live narratives and preview what your agents would mint',+ },{title: 'Launchpad Studio',href: '/launchpad',diff --git a/public/next/index.html b/public/next/index.htmlindex b8e13a6dd..5fdc62b4a 100644--- a/public/next/index.html+++ b/public/next/index.html@@ -279,7 +279,7 @@<script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js" integrity="sha384-sr9b4Ux0WhAUGclJ0ym0FSY2zSOMmNSn0bP/SA0e6bNCrpn/5W3QL8mm+LdlQMKw" crossorigin="anonymous"></script><script src="/embed/v1.js" defer></script>- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><nav class="nav" aria-label="Primary">diff --git a/public/pay/calls/index.html b/public/pay/calls/index.htmlindex 4e0866fbd..d7455f15a 100644--- a/public/pay/calls/index.html+++ b/public/pay/calls/index.html@@ -153,7 +153,7 @@.opt-row .opt-title { font-weight: 600; }.opt-row .opt-detail { color: var(--muted); margin-top: 2px; font-size: 12px; }</style>- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body>diff --git a/public/pay/index.html b/public/pay/index.htmlindex 9b852ac08..02a826dbb 100644--- a/public/pay/index.html+++ b/public/pay/index.html@@ -707,7 +707,7 @@<meta property="og:locale" content="en_US"><meta property="og:image:alt" content="Pay (x402) — three.ws"><meta name="twitter:site" content="@trythreews">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body>diff --git a/public/persona/demo.html b/public/persona/demo.htmlindex 971068e26..3f2db3a51 100644--- a/public/persona/demo.html+++ b/public/persona/demo.html@@ -169,7 +169,7 @@margin-top: 30px;}</style>- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><main>diff --git a/public/pumpfun.html b/public/pumpfun.htmlindex f36dd3941..58bb8f82e 100644--- a/public/pumpfun.html+++ b/public/pumpfun.html@@ -413,7 +413,7 @@<meta property="og:locale" content="en_US"><meta property="og:image:alt" content="Pump.fun Stream — three.ws"><meta name="twitter:site" content="@trythreews">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body class="home-page"><header>diff --git a/public/reputation/index.html b/public/reputation/index.htmlindex a8cc7a999..535849ce5 100644--- a/public/reputation/index.html+++ b/public/reputation/index.html@@ -369,7 +369,7 @@<meta property="og:locale" content="en_US"><meta property="og:image:alt" content="Reputation Explorer — three.ws"><meta name="twitter:site" content="@trythreews">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><a href="#rep-content" class="h-skip-link">Skip to content</a>diff --git a/public/vanity-wallet.html b/public/vanity-wallet.htmlindex 924864d56..fd66e3c38 100644--- a/public/vanity-wallet.html+++ b/public/vanity-wallet.html@@ -195,7 +195,7 @@<meta property="og:locale" content="en_US"><meta property="og:image:alt" content="Solana Vanity Wallet — three.ws"><meta name="twitter:site" content="@trythreews">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body><a href="#main-content" class="skip-link">Skip to main content</a>diff --git a/public/widgets-gallery/index.html b/public/widgets-gallery/index.htmlindex 39548a06a..f0bc4e808 100644--- a/public/widgets-gallery/index.html+++ b/public/widgets-gallery/index.html@@ -40,7 +40,7 @@<meta property="og:locale" content="en_US"><meta property="og:image:alt" content="Widgets Gallery — three.ws"><meta name="twitter:site" content="@trythreews">- <script type="module" src="/model-viewer-meshopt.js"></script>+ <script src="/model-viewer-meshopt.js"></script></head><body class="gallery-body"><div id="nav-container"></div>diff --git a/sdk/src/agent-client.js b/sdk/src/agent-client.jsindex fb082c202..873d91105 100644--- a/sdk/src/agent-client.js+++ b/sdk/src/agent-client.js@@ -106,6 +106,46 @@ export class AgentClient {return res.json();}+ /**+ * Bring an agent live in one call: claim its one-time on-chain activation grant.+ * `POST /api/agents/:id/activate`. The platform funds the agent's wallet and the+ * agent immediately appears on the Money Pulse as an active, funded wallet.+ *+ * Requires a bearer token with `avatars:write` for the agent's owner. Idempotent+ * — if the agent is already live it resolves to the existing receipt+ * (`already: true`) rather than granting twice.+ *+ * @param {string} agentId+ * @returns {Promise<{ ok:boolean, already?:boolean, pending?:boolean, signature?:string,+ * explorer?:string|null, sol?:number, usd?:number|null, network?:string }>}+ */+ async activate(agentId) {+ const res = await this._fetch(+ `${this.baseUrl}/api/agents/${encodeURIComponent(agentId)}/activate`,+ { method: 'POST', headers: this._headers() },+ );+ const body = await this._json(res, 'activate');+ return body?.data ?? body;+ }++ /**+ * Read an agent's activation status (which "Go Live" state it's in). Owner view.+ * `GET /api/agents/:id/activate`.+ *+ * @param {string} agentId+ * @returns {Promise<{ enabled:boolean, eligible:boolean, activated:boolean,+ * pending:boolean, reason:string|null, grant_sol:number, network:string,+ * receipt:object|null }>}+ */+ async getActivationStatus(agentId) {+ const res = await this._fetch(+ `${this.baseUrl}/api/agents/${encodeURIComponent(agentId)}/activate`,+ { headers: this._headers() },+ );+ const body = await this._json(res, 'getActivationStatus');+ return body?.data ?? body;+ }+/*** Invoke a priced skill, settling x402 payment automatically when required.*diff --git a/src/admin-launcher.css b/src/admin-launcher.cssindex b6a79d515..43b2dc039 100644--- a/src/admin-launcher.css+++ b/src/admin-launcher.css@@ -96,12 +96,13 @@.ml-breaker-txt { flex: 1; font-size: var(--text-sm, 0.85rem); color: var(--ink-bright, #fff); }/* ── stats ────────────────────────────────────────────────────────────────── */-.ml-stats { display: grid; grid-template-columns: repeat(6, 1fr); gap: var(--space-sm, 12px); margin: 0 0 var(--space-xl, 32px); }+.ml-stats { display: grid; grid-template-columns: repeat(8, 1fr); gap: var(--space-sm, 12px); margin: 0 0 var(--space-xl, 32px); }.ml-stat { background: var(--surface-1, rgba(255, 255, 255, 0.03)); border: 1px solid var(--stroke, rgba(255, 255, 255, 0.07)); border-radius: var(--radius-lg, 14px); padding: var(--space-md, 16px) var(--space-sm, 12px); min-width: 0; transition: border-color 0.14s ease; }.ml-stat:hover { border-color: var(--stroke-strong, rgba(255, 255, 255, 0.14)); }.ml-stat--lead { background: var(--surface-2, rgba(255, 255, 255, 0.05)); border-color: var(--stroke-strong, rgba(255, 255, 255, 0.14)); }+.ml-stat--revenue { border-style: dashed; }.ml-stat dt { font-size: var(--text-2xs, 0.66rem); text-transform: uppercase; letter-spacing: 0.06em; color: var(--ink-dim, #888); margin-bottom: 8px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }-.ml-stat dd { margin: 0; font-family: var(--font-mono, monospace); font-size: clamp(1.2rem, 2.4vw, 1.7rem); font-weight: 700; color: var(--ink-bright, #fff); line-height: 1; }+.ml-stat dd { margin: 0; font-family: var(--font-mono, monospace); font-size: clamp(1rem, 1.8vw, 1.5rem); font-weight: 700; color: var(--ink-bright, #fff); line-height: 1; }/* ── grid ─────────────────────────────────────────────────────────────────── */.ml-grid { display: grid; grid-template-columns: 1.15fr 0.85fr; gap: var(--space-lg, 24px); align-items: start; }@@ -190,6 +191,7 @@.ml-run-sym { color: var(--ink-dim, #888); font-family: var(--font-mono, monospace); font-weight: 500; }.ml-run-meta { font-size: var(--text-2xs, 0.68rem); color: var(--ink-dim, #888); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }.ml-run-meta .ml-kind { text-transform: uppercase; letter-spacing: 0.04em; }+.ml-run-agent { color: var(--ink, #e8e8e8); font-weight: 600; }.ml-run-err { color: var(--ink, #ccc); }.ml-run-r { text-align: right; }.ml-run-sol { font-family: var(--font-mono, monospace); font-size: var(--text-xs, 0.76rem); color: var(--ink, #e8e8e8); }@@ -224,16 +226,24 @@.ml-skel { color: transparent !important; background: linear-gradient(90deg, var(--surface-1, rgba(255,255,255,0.04)) 25%, var(--surface-3, rgba(255,255,255,0.09)) 50%, var(--surface-1, rgba(255,255,255,0.04)) 75%); background-size: 200% 100%; border-radius: 6px; animation: ml-shimmer 1.3s linear infinite; }@keyframes ml-shimmer { from { background-position: 200% 0; } to { background-position: -200% 0; } }+/* force-tick button — compact ghost, sits beside the arm switch */+.ml-force { font-size: var(--text-xs, 0.72rem); padding: 7px 13px; }+/* ── responsive ───────────────────────────────────────────────────────────── */+@media (max-width: 1100px) {+ .ml-stats { grid-template-columns: repeat(4, 1fr); }+}@media (max-width: 940px) {.ml-grid { grid-template-columns: 1fr; }.ml-rail { position: static; }- .ml-stats { grid-template-columns: repeat(3, 1fr); }+ .ml-stats { grid-template-columns: repeat(4, 1fr); }+}+@media (max-width: 640px) {+ .ml-stats { grid-template-columns: repeat(2, 1fr); }}@media (max-width: 560px) {.ml-hero { flex-direction: column; align-items: flex-start; }- .ml-hero-r { width: 100%; justify-content: space-between; }- .ml-stats { grid-template-columns: repeat(2, 1fr); }+ .ml-hero-r { width: 100%; justify-content: space-between; flex-wrap: wrap; gap: 8px; }.ml-fields { grid-template-columns: 1fr; }}diff --git a/src/admin-launcher.js b/src/admin-launcher.jsindex 38f1a5e86..f1829f512 100644--- a/src/admin-launcher.js+++ b/src/admin-launcher.js@@ -20,8 +20,8 @@ const SOURCES = [{ id: 'coin_intel', label: 'Coin intel' },{ id: 'trending', label: 'Trending' },{ id: 'knowyourmeme', label: 'Know Your Meme' },- { id: 'x', label: 'X' },{ id: 'googletrends', label: 'Google Trends' },+ { id: 'x', label: 'X' },{ id: 'hackernews', label: 'Hacker News' },{ id: 'reddit', label: 'Reddit' },{ id: 'wikipedia', label: 'Wikipedia' },@@ -218,6 +218,30 @@ function buildStaticControls() {$('ml-save').addEventListener('click', save);$('ml-discard').addEventListener('click', () => { draft = { ...loaded }; renderForm(); updateDirty(); });$('ml-resume').addEventListener('click', resumeBreaker);++ // Force-tick: run one launcher tick immediately without waiting for cron.+ const forceTick = $('ml-force-tick');+ if (forceTick) {+ forceTick.addEventListener('click', async () => {+ forceTick.disabled = true;+ forceTick.textContent = 'Ticking…';+ try {+ const r = await api('POST', { action: 'force_tick' });+ const res = r.tick?.results?.[0];+ if (res?.mint) toast(`Launched ${res.name} (${res.symbol})`);+ else if (res?.dry_run) toast(`Dry run: ${res.name} (${res.symbol})`);+ else if (res?.skipped) toast(`Skipped: ${res.skipped}`);+ else toast('Tick complete');+ refresh();+ } catch (err) {+ if (err.message !== 'unauthorized') toast(err.message, true);+ } finally {+ forceTick.disabled = false;+ forceTick.textContent = 'Force tick';+ }+ });+ }+wireModal();}@@ -299,6 +323,12 @@ function renderState(state) {$('ml-s-queue').textContent = num(state.queue_enabled);$('ml-s-fail').textContent = `${num(s.failed_today)} / ${num(s.skipped_today)}`;+ const rev = state.revenue || {};+ const feesEl = $('ml-s-fees');+ const buyEl = $('ml-s-buyback');+ if (feesEl) feesEl.textContent = rev.total_claimed_sol != null ? `${fmtSol(rev.total_claimed_sol)} ◎` : '—';+ if (buyEl) buyEl.textContent = rev.total_buyback_sol != null ? `${fmtSol(rev.total_buyback_sol)} ◎` : '—';+$('ml-master-bal').textContent = state.master_balance_sol == null ? 'n/a' : `${fmtSol(state.master_balance_sol)} ◎`;const breaker = $('ml-breaker');@@ -362,9 +392,10 @@ function runRowHtml(r, network) {? `<a href="${solscan(r.mint, network)}" target="_blank" rel="noopener">${esc(r.name || r.symbol || 'coin')}</a>`: esc(r.name || r.symbol || '—');const rode = topNarrative(r.trigger_detail);+ const agentTag = r.agent_name ? `<span class="ml-run-agent">${esc(trunc(r.agent_name, 16))}</span> · ` : '';const meta = r.status === 'failed' && r.error- ? `<span class="ml-run-err">${esc(trunc(r.error, 64))}</span>`- : `<span class="ml-kind">${esc(r.kind || '')}</span>${rode ? ' · rode ' + esc(rode) : (r.trigger_source ? ' · ' + esc(r.trigger_source) : '')}`;+ ? `${agentTag}<span class="ml-run-err">${esc(trunc(r.error, 60))}</span>`+ : `${agentTag}<span class="ml-kind">${esc(r.kind || '')}</span>${rode ? ' · ' + esc(rode) : (r.trigger_source ? ' · ' + esc(r.trigger_source) : '')}`;const sol = Number(r.sol_spent) > 0 ? `${fmtSol(r.sol_spent)} ◎` : (r.dry_run ? 'dry' : '—');return (`<span class="ml-pill s-${esc(status)}">${esc(statusLabel(status))}</span>` +diff --git a/src/agent-detail.js b/src/agent-detail.jsindex 37df588fc..fd7062cdf 100644--- a/src/agent-detail.js+++ b/src/agent-detail.js@@ -238,6 +238,11 @@ function wireWalkMode(agent) {const cta = document.getElementById('ad-walk-link');if (cta) cta.href = walkAppHref(agent);+ // Watch-live CTA → the agent's dedicated live screen viewer (self-handles the+ // idle/offline state when the agent isn't currently broadcasting).+ const watch = document.getElementById('ad-watch-live');+ if (watch && agent?.id) watch.href = `/agent-screen?agentId=${encodeURIComponent(agent.id)}`;+const card = document.getElementById('ad-walk-card');const frame = document.getElementById('ad-walk-frame');const skeleton = document.getElementById('ad-walk-skeleton');diff --git a/src/agent-screen.js b/src/agent-screen.jsindex 806c9f714..74119fbca 100644--- a/src/agent-screen.js+++ b/src/agent-screen.js@@ -496,8 +496,12 @@ async function boot(id) {if (!frame?.data) return;const img = new Image();img.onload = () => {- screenCanvas.width = img.naturalWidth || 1280;- screenCanvas.height = img.naturalHeight || 720;+ const w = img.naturalWidth || 1280;+ const h = img.naturalHeight || 720;+ // Reassigning canvas dimensions clears + reallocates the backing store;+ // only do it when the frame size actually changes.+ if (screenCanvas.width !== w) screenCanvas.width = w;+ if (screenCanvas.height !== h) screenCanvas.height = h;screenCtx.drawImage(img, 0, 0);lastFrameImg = img;};diff --git a/src/create-agent.js b/src/create-agent.jsindex 07fb5b76b..3baba0062 100644--- a/src/create-agent.js+++ b/src/create-agent.js@@ -1096,9 +1096,13 @@ function succeed(agent) {const open = $('success-open');open.href = agent.home_url || `/agent/${agent.id}`;$('success-edit').href = `/agent/${agent.id}/edit`;- // Lead the user straight into funding the agent's new self-custodied wallet —- // the Deposit tab of the wallet hub (QR + copy + live confirmation lands here- // via the epic's task 02).+ // Lead with "Go live" — the highest-value first step. The activation tab claims+ // the one-time on-chain welcome grant that funds the wallet AND lands the agent+ // on the Money Pulse in a single transaction.+ const activate = $('success-activate');+ if (activate) activate.href = `/agent/${agent.id}/wallet#activate`;+ // Funding by hand stays one tap away — the Deposit tab (QR + copy + live+ // confirmation) for owners who'd rather send their own SOL.const fund = $('success-fund');if (fund) fund.href = `/agent/${agent.id}/wallet#deposit`;diff --git a/src/marketplace-gallery-data.js b/src/marketplace-gallery-data.jsindex 7598cd12d..b79f61c85 100644--- a/src/marketplace-gallery-data.js+++ b/src/marketplace-gallery-data.js@@ -10,8 +10,8 @@export const PAGE_SIZE = 18;-export const TYPE_ACCENT = { agent: '#8b5cf6', avatar: '#22d3ee', skill: '#34d399' };-export const TYPE_LABEL = { agent: 'Agent', avatar: 'Avatar', skill: 'Skill' };+// TYPE_ACCENT / TYPE_LABEL live in marketplace-gallery.js: they are presentation+// (the monochrome brightness tiers of the platform design system), not data.export const FILTERS = [{ key: 'all', label: 'All' },diff --git a/src/marketplace-gallery.js b/src/marketplace-gallery.jsindex d703727b2..267c28448 100644--- a/src/marketplace-gallery.js+++ b/src/marketplace-gallery.js@@ -37,6 +37,17 @@ import {MathUtils,} from 'three';+import {+ PAGE_SIZE,+ FILTERS,+ normalizeFilterKey,+ normalizeAgent,+ normalizeAvatar,+ normalizeSkill,+ interleave,+ fmtCount,+} from './marketplace-gallery-data.js';+// ── Layout (metres) ─────────────────────────────────────────────────────────const SPACING = 4; // a plinth every 4m down the hallconst START_Z = 4; // first plinth sits 4m ahead of the anchor@@ -49,7 +60,6 @@ const ENTER_RANGE = 2.0; // step within 2m → reveal the listingconst RELEASE_RANGE = 3.4; // step past this → dismiss (hysteresis stops flicker)const REBASE_AT = 500; // fold belt offset back near 0 to preserve float precision-const PAGE_SIZE = 18;// Monochrome brightness tiers — matches the platform's monochrome design system// (public/tokens.css). Type identity is carried by brightness (and the explicit// TYPE_LABEL text drawn on every plinth + the panel badge), never a brand hue, so@@ -57,13 +67,6 @@ const PAGE_SIZE = 18;const TYPE_ACCENT = { agent: '#fafafa', avatar: '#c8c8d0', skill: '#9a9aa3' };const TYPE_LABEL = { agent: 'Agent', avatar: 'Avatar', skill: 'Skill' };-const FILTERS = [- { key: 'all', label: 'All' },- { key: 'agent', label: 'Agents' },- { key: 'avatar', label: 'Avatars' },- { key: 'skill', label: 'Skills' },-];-const STYLE_ID = 'marketplace-gallery-styles';function ensureStyles() {@@ -71,8 +74,10 @@ function ensureStyles() {const s = document.createElement('style');s.id = STYLE_ID;s.textContent = `-.mwg-chips{position:fixed;top:calc(env(safe-area-inset-top,0) + 116px);left:50%;- transform:translateX(-50%);z-index:6;display:flex;gap:6px;padding:5px;border-radius:999px;+.mwg-top{position:fixed;top:calc(env(safe-area-inset-top,0) + 110px);left:50%;+ transform:translateX(-50%);z-index:6;display:flex;flex-direction:column;align-items:center;+ gap:8px;max-width:calc(100vw - 24px);}+.mwg-chips{display:flex;gap:6px;padding:5px;border-radius:999px;background:rgba(10,10,12,.72);border:1px solid rgba(255,255,255,.1);backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);box-shadow:0 8px 28px rgba(0,0,0,.4);}.mwg-chip{appearance:none;border:0;background:transparent;color:#a1a1aa;font:inherit;font-size:13px;@@ -82,6 +87,21 @@ function ensureStyles() {.mwg-chip[aria-pressed="true"]{color:#0a0a0a;background:#fafafa;}.mwg-chip:focus-visible{outline:2px solid rgba(255,255,255,.6);outline-offset:2px;}+.mwg-search{display:flex;align-items:center;gap:8px;padding:0 12px;height:38px;border-radius:999px;+ background:rgba(10,10,12,.72);border:1px solid rgba(255,255,255,.1);width:min(340px,72vw);+ backdrop-filter:blur(12px);-webkit-backdrop-filter:blur(12px);box-shadow:0 8px 28px rgba(0,0,0,.4);+ transition:border-color .15s ease;}+.mwg-search:focus-within{border-color:rgba(255,255,255,.35);}+.mwg-search svg{flex:0 0 auto;color:#a1a1aa;}+.mwg-search input{flex:1;min-width:0;appearance:none;border:0;background:transparent;color:#fafafa;+ font:inherit;font-size:13px;outline:none;}+.mwg-search input::placeholder{color:#71717a;}+.mwg-search-clear{flex:0 0 auto;appearance:none;border:0;background:transparent;color:#a1a1aa;+ font:inherit;font-size:16px;line-height:1;cursor:pointer;padding:2px 4px;display:none;border-radius:50%;}+.mwg-search-clear:hover{color:#fafafa;}+.mwg-search[data-has-query="1"] .mwg-search-clear{display:block;}+.mwg-search-clear:focus-visible{outline:2px solid rgba(255,255,255,.6);outline-offset:1px;}+.mwg-panel{position:fixed;top:50%;right:max(16px,env(safe-area-inset-right,0));transform:translate(calc(100% + 32px),-50%);z-index:7;width:min(340px,calc(100vw - 32px));max-height:min(78vh,640px);overflow:hidden auto;border-radius:18px;@@ -103,16 +123,33 @@ function ensureStyles() {.mwg-panel-author{margin:0 0 10px;font-size:12px;color:#a1a1aa;}.mwg-panel-desc{margin:0 0 14px;font-size:13px;line-height:1.5;color:#c8c8d0;display:-webkit-box;-webkit-line-clamp:5;-webkit-box-orient:vertical;overflow:hidden;}+.mwg-panel-stats{display:flex;flex-wrap:wrap;align-items:center;gap:5px 14px;margin:0 0 12px;+ font-size:12.5px;color:#a1a1aa;}+.mwg-panel-stat{display:inline-flex;align-items:center;gap:5px;}+.mwg-panel-stat b{color:#fafafa;font-weight:700;font-variant-numeric:tabular-nums;}+.mwg-panel-stat .star{color:#fafafa;font-size:13px;line-height:1;}+.mwg-panel-tags{display:flex;flex-wrap:wrap;gap:6px;margin:0 0 14px;}+.mwg-panel-tag{font-size:11px;color:#c8c8d0;background:rgba(255,255,255,.06);+ border:1px solid rgba(255,255,255,.08);border-radius:999px;padding:3px 9px;white-space:nowrap;}.mwg-panel-meta{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:14px;}.mwg-panel-price{font-size:17px;font-weight:700;}.mwg-panel-cat{font-size:11px;font-weight:600;color:#a1a1aa;text-transform:capitalize;padding:4px 9px;border-radius:999px;background:rgba(255,255,255,.06);}-.mwg-panel-cta{display:flex;align-items:center;justify-content:center;gap:8px;width:100%;+.mwg-panel-actions{display:flex;gap:8px;align-items:stretch;}+.mwg-panel-cta{flex:1;display:flex;align-items:center;justify-content:center;gap:8px;appearance:none;border:0;border-radius:12px;padding:12px 16px;font:inherit;font-size:14px;- font-weight:700;color:#0a0a0a;cursor:pointer;transition:filter .15s ease,transform .1s ease;}+ font-weight:700;color:#0a0a0a;background:#fafafa;text-decoration:none;cursor:pointer;+ transition:filter .15s ease,transform .1s ease;}.mwg-panel-cta:hover{filter:brightness(1.08);}.mwg-panel-cta:active{transform:scale(.98);}.mwg-panel-cta:focus-visible{outline:2px solid #fff;outline-offset:2px;}+.mwg-panel-share{flex:0 0 auto;display:flex;align-items:center;justify-content:center;width:44px;+ appearance:none;border:1px solid rgba(255,255,255,.14);border-radius:12px;background:rgba(255,255,255,.04);+ color:#fafafa;cursor:pointer;transition:background .15s ease,border-color .15s ease;}+.mwg-panel-share:hover{background:rgba(255,255,255,.1);border-color:rgba(255,255,255,.3);}+.mwg-panel-share:active{transform:scale(.96);}+.mwg-panel-share:focus-visible{outline:2px solid #fff;outline-offset:2px;}+.mwg-panel-share[data-copied="1"]{color:#0a0a0a;background:#fafafa;border-color:#fafafa;}.mwg-panel-hint{margin:9px 0 0;text-align:center;font-size:11px;color:#71717a;}.mwg-panel-hint kbd{font-family:ui-monospace,Menlo,monospace;font-size:10.5px;padding:1px 5px;border-radius:4px;background:rgba(255,255,255,.1);border:1px solid rgba(255,255,255,.14);}@@ -137,69 +174,21 @@ function ensureStyles() {border:0;font:inherit;cursor:pointer;padding:0;white-space:nowrap;}@media (hover:none),(max-width:640px){- .mwg-chips{top:calc(env(safe-area-inset-top,0) + 104px);}+ .mwg-top{top:calc(env(safe-area-inset-top,0) + 100px);}+ .mwg-search{width:min(340px,82vw);}.mwg-panel{top:auto;bottom:calc(150px + env(safe-area-inset-bottom,0));right:50%;transform:translate(50%,calc(100% + 40px));width:min(360px,calc(100vw - 24px));max-height:46vh;}.mwg-panel[data-show="1"]{transform:translate(50%,0);}.mwg-prompt{bottom:calc(150px + env(safe-area-inset-bottom,0));}}@media (prefers-reduced-motion:reduce){- .mwg-panel,.mwg-prompt,.mwg-chip,.mwg-panel-cta{transition:none;}+ .mwg-panel,.mwg-prompt,.mwg-chip,.mwg-panel-cta,.mwg-search,.mwg-panel-share{transition:none;}}-body.is-zen .mwg-chips,body.is-zen .mwg-panel,body.is-zen .mwg-prompt,body.is-zen .mwg-toast{display:none !important;}+body.is-zen .mwg-top,body.is-zen .mwg-panel,body.is-zen .mwg-prompt,body.is-zen .mwg-toast{display:none !important;}`;document.head.appendChild(s);}-// ── Listing normalisation ───────────────────────────────────────────────────-function fmtTokenPrice(price) {- if (!price || price.amount == null) return 'Free';- const dec = Number(price.mint_decimals ?? 6);- const v = Number(price.amount) / Math.pow(10, dec);- if (!Number.isFinite(v) || v <= 0) return 'Free';- return `$${v >= 1 ? v.toLocaleString(undefined, { maximumFractionDigits: 2 }) : v.toFixed(2)}`;-}--function normalizeAgent(a) {- return {- type: 'agent',- name: a.name || 'Untitled agent',- description: a.description || '',- image: a.thumbnail_url || null,- price: fmtTokenPrice(a.price),- category: a.category || '',- author: null,- href: `/marketplace/agents/${encodeURIComponent(a.id)}`,- };-}--function normalizeAvatar(a) {- return {- type: 'avatar',- name: a.name || 'Untitled avatar',- description: a.description || '',- image: a.image || null,- price: fmtTokenPrice(a.price),- category: a.modelCategory || 'avatar',- author: a.author?.displayName || a.author?.handle || null,- href: `/marketplace/avatars/${encodeURIComponent(a.avatarId)}`,- };-}--function normalizeSkill(s) {- const usd = Number(s.price_per_call_usd);- return {- type: 'skill',- name: s.name || 'Untitled skill',- description: s.description || '',- image: null,- price: usd > 0 ? `$${usd}/call` : 'Free',- category: s.category || '',- author: s.author?.display_name || null,- href: `/marketplace/skills/${encodeURIComponent(s.slug || s.id)}`,- };-}-/*** @param {object} cfg* @param {import('three').Scene} cfg.scene@@ -298,14 +287,17 @@ export function createMarketplaceGallery({ scene, getLocalPosition }) {}if (name !== (listing.name || '')) name = name.trimEnd() + '…';ctx.fillText(name, 36, H * 0.36);- // price + type+ // price (left) + rating·type (right) — rating only when it carries votes,+ // so an unrated plinth simply reads its type.ctx.font = '700 44px Inter, system-ui, sans-serif';ctx.fillStyle = accentHex;ctx.fillText(listing.price, 36, H * 0.74);ctx.font = '600 32px Inter, system-ui, sans-serif';ctx.fillStyle = '#a1a1aa';ctx.textAlign = 'right';- ctx.fillText(TYPE_LABEL[listing.type] || '', W - 36, H * 0.74);+ const typeText = TYPE_LABEL[listing.type] || '';+ const rightText = listing.rating ? `★ ${listing.rating.avg} · ${typeText}` : typeText;+ ctx.fillText(rightText, W - 36, H * 0.74);}function coverFit(tex, imgW, imgH, planeAspect) {@@ -391,7 +383,7 @@ export function createMarketplaceGallery({ scene, getLocalPosition }) {function assignListing(slot, listing) {slot.listing = listing;slot.group.visible = true;- const accent = TYPE_ACCENT[listing.type] || '#8b5cf6';+ const accent = TYPE_ACCENT[listing.type] || '#fafafa';slot.ring.material.color.set(accent);drawLabel(slot.labelCanvas, listing, accent);slot.labelTex.needsUpdate = true;@@ -430,7 +422,12 @@ export function createMarketplaceGallery({ scene, getLocalPosition }) {avatar: { cursor: null, done: false, fetch: fetchAvatars },skill: { cursor: null, done: false, fetch: fetchSkills },};- let filter = 'all';+ // Deep-link state: ?type=skill (or skills/agent/avatar) picks the opening+ // filter, ?q= seeds an in-hall search — so a shared link lands on exactly the+ // slice of the marketplace it points at.+ const bootParams = new URLSearchParams(location.search);+ let filter = normalizeFilterKey(bootParams.get('type') || bootParams.get('filter')) || 'all';+ let query = (bootParams.get('q') || '').trim().slice(0, 80);let buffer = []; // normalised listings waiting for a plinthlet served = []; // everything seen this filter — replayed once pages run outlet loading = false;@@ -441,6 +438,7 @@ export function createMarketplaceGallery({ scene, getLocalPosition }) {const u = new URL('/api/marketplace/agents', location.origin);u.searchParams.set('limit', String(PAGE_SIZE));u.searchParams.set('sort', 'recommended');+ if (query) u.searchParams.set('q', query);if (cursor) u.searchParams.set('cursor', cursor);const r = await fetch(u);if (!r.ok) throw new Error(`agents ${r.status}`);@@ -454,6 +452,7 @@ export function createMarketplaceGallery({ scene, getLocalPosition }) {u.searchParams.set('source', 'avatar');u.searchParams.set('quality', 'high');u.searchParams.set('limit', String(PAGE_SIZE));+ if (query) u.searchParams.set('q', query);if (cursor) u.searchParams.set('cursor', cursor);const r = await fetch(u);if (!r.ok) throw new Error(`avatars ${r.status}`);@@ -466,6 +465,7 @@ export function createMarketplaceGallery({ scene, getLocalPosition }) {const u = new URL('/api/skills', location.origin);u.searchParams.set('limit', String(PAGE_SIZE));u.searchParams.set('sort', 'popular');+ if (query) u.searchParams.set('q', query);if (cursor) u.searchParams.set('cursor', cursor);const r = await fetch(u);if (!r.ok) throw new Error(`skills ${r.status}`);@@ -498,10 +498,7 @@ export function createMarketplaceGallery({ scene, getLocalPosition }) {if (!res.next) sources[k].done = true;return res.items;});- const merged = [];- for (let i = 0; lanes.some((l) => i < l.length); i++) {- for (const lane of lanes) if (i < lane.length) merged.push(lane[i]);- }+ const merged = interleave(lanes);if (merged.length) {loadedAny = true;buffer.push(...merged);@@ -667,7 +664,52 @@ export function createMarketplaceGallery({ scene, getLocalPosition }) {location.href = activeSlot.listing.href;}- // ── DOM: chips, panel, prompt, toast ────────────────────────────────────────+ // ── DOM: search + chips (top bar), panel, prompt, toast ──────────────────────+ const top = document.createElement('div');+ top.className = 'mwg-top';++ // Search field — jump straight to a named skill/agent/avatar instead of+ // walking the whole hall. Debounced; each source filters server-side on ?q.+ const search = document.createElement('div');+ search.className = 'mwg-search';+ search.innerHTML = `+ <svg viewBox="0 0 16 16" width="15" height="15" fill="none" stroke="currentColor" stroke-width="1.6" stroke-linecap="round"><circle cx="7" cy="7" r="4.5"/><path d="M10.5 10.5l3 3"/></svg>+ <input type="search" enterkeyhint="search" autocomplete="off" autocapitalize="off"+ spellcheck="false" maxlength="80" aria-label="Search the marketplace"+ placeholder="Search agents, avatars, skills…" />+ <button type="button" class="mwg-search-clear" aria-label="Clear search" title="Clear">×</button>`;+ const searchInput = search.querySelector('input');+ const searchClear = search.querySelector('.mwg-search-clear');+ searchInput.value = query;+ if (query) search.setAttribute('data-has-query', '1');+ let searchTimer = 0;+ function flushSearch() {+ clearTimeout(searchTimer);+ applyQuery(searchInput.value);+ }+ searchInput.addEventListener('input', () => {+ search.toggleAttribute('data-has-query', !!searchInput.value.trim());+ clearTimeout(searchTimer);+ searchTimer = setTimeout(flushSearch, 300);+ });+ searchInput.addEventListener('keydown', (e) => {+ if (e.key === 'Enter') {+ e.preventDefault();+ flushSearch();+ } else if (e.key === 'Escape' && searchInput.value) {+ e.preventDefault();+ searchInput.value = '';+ search.removeAttribute('data-has-query');+ flushSearch();+ }+ });+ searchClear.addEventListener('click', () => {+ searchInput.value = '';+ search.removeAttribute('data-has-query');+ flushSearch();+ searchInput.focus();+ });+const chips = document.createElement('div');chips.className = 'mwg-chips';chips.setAttribute('role', 'tablist');@@ -678,11 +720,26 @@ export function createMarketplaceGallery({ scene, getLocalPosition }) {b.type = 'button';b.textContent = f.label;b.dataset.filter = f.key;+ b.setAttribute('role', 'tab');b.setAttribute('aria-pressed', String(f.key === filter));b.addEventListener('click', () => setFilter(f.key));chips.appendChild(b);}- document.body.appendChild(chips);+ // Roving arrow-key navigation across the filter tablist (auto-activates).+ chips.addEventListener('keydown', (e) => {+ if (e.key !== 'ArrowRight' && e.key !== 'ArrowLeft') return;+ const btns = [...chips.children];+ const i = btns.indexOf(document.activeElement);+ if (i === -1) return;+ e.preventDefault();+ const ni = (i + (e.key === 'ArrowRight' ? 1 : -1) + btns.length) % btns.length;+ btns[ni].focus();+ setFilter(btns[ni].dataset.filter);+ });++ top.appendChild(search);+ top.appendChild(chips);+ document.body.appendChild(top);const panel = document.createElement('aside');panel.className = 'mwg-panel';@@ -722,48 +779,125 @@ export function createMarketplaceGallery({ scene, getLocalPosition }) {function maybeShowEmpty() {if (loadedAny || loading || !allDone()) return;const label = FILTERS.find((f) => f.key === filter)?.label || 'listings';+ if (query) {+ showToast(`No ${label.toLowerCase()} match “${query}”.`, 'Clear search', () => {+ searchInput.value = '';+ search.removeAttribute('data-has-query');+ flushSearch();+ searchInput.focus();+ });+ return;+ }showToast(`No ${label.toLowerCase()} listed yet.`, 'Browse the grid →', () => {location.href = '/marketplace';});}function showPanel(listing) {- const accent = TYPE_ACCENT[listing.type] || '#8b5cf6';+ const accent = TYPE_ACCENT[listing.type] || '#fafafa';const media = listing.image? `<img src="${escapeAttr(listing.image)}" alt="" loading="lazy" />`: `<div class="mwg-panel-fallback" style="background:linear-gradient(160deg,${accent},#0c0c0e)">${escapeHtml((listing.name || '?').charAt(0).toUpperCase())}</div>`;++ // Trust signals — ratings + adoption counts pulled straight from the same+ // listing rows the grid uses, so a number never disagrees across surfaces.+ const stats = [];+ if (listing.rating) {+ const votes = fmtCount(listing.rating.count) || String(listing.rating.count);+ stats.push(+ `<span class="mwg-panel-stat"><span class="star">★</span><b>${listing.rating.avg}</b> <span>(${votes})</span></span>`,+ );+ }+ if (listing.uses) {+ const c = fmtCount(listing.uses.count);+ if (c) stats.push(`<span class="mwg-panel-stat"><b>${c}</b> ${escapeHtml(listing.uses.label)}</span>`);+ }+ const statsRow = stats.length ? `<div class="mwg-panel-stats">${stats.join('')}</div>` : '';++ const tagsRow = listing.tags?.length+ ? `<div class="mwg-panel-tags">${listing.tags+ .slice(0, 3)+ .map((t) => `<span class="mwg-panel-tag">${escapeHtml(t)}</span>`)+ .join('')}</div>`+ : '';++ const featuredBadge = listing.featured+ ? `<span class="mwg-panel-badge" style="background:${accent};left:auto;right:12px">Featured</span>`+ : '';+panel.innerHTML = `<div class="mwg-panel-media">${media}<span class="mwg-panel-badge" style="background:${accent}">${TYPE_LABEL[listing.type] || ''}</span>+ ${featuredBadge}</div><div class="mwg-panel-body"><h2 class="mwg-panel-title">${escapeHtml(listing.name)}</h2>${listing.author ? `<p class="mwg-panel-author">by ${escapeHtml(listing.author)}</p>` : ''}+ ${statsRow}${listing.description ? `<p class="mwg-panel-desc">${escapeHtml(listing.description)}</p>` : ''}+ ${tagsRow}<div class="mwg-panel-meta"><span class="mwg-panel-price" style="color:${accent}">${escapeHtml(listing.price)}</span>${listing.category ? `<span class="mwg-panel-cat">${escapeHtml(listing.category)}</span>` : ''}</div>- <button class="mwg-panel-cta" type="button" style="background:#fafafa">View listing →</button>+ <div class="mwg-panel-actions">+ <a class="mwg-panel-cta" href="${escapeAttr(listing.href)}">View listing →</a>+ <button class="mwg-panel-share" type="button" aria-label="Copy link to this listing" title="Copy link">+ <svg viewBox="0 0 16 16" width="16" height="16" fill="none" stroke="currentColor" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round"><path d="M6.5 9.5l3-3"/><path d="M7.2 4.3l.9-.9a2.4 2.4 0 0 1 3.4 3.4l-.9.9"/><path d="M8.8 11.7l-.9.9a2.4 2.4 0 0 1-3.4-3.4l.9-.9"/></svg>+ </button>+ </div><p class="mwg-panel-hint">Press <kbd>E</kbd> to open</p></div>`;- panel.querySelector('.mwg-panel-cta')?.addEventListener('click', navigateActive);++ // Plain left-click routes through the shared nav guard; modified clicks+ // (⌘/ctrl/middle → new tab) fall through to the native anchor.+ panel.querySelector('.mwg-panel-cta')?.addEventListener('click', (e) => {+ if (e.metaKey || e.ctrlKey || e.shiftKey || e.altKey || e.button !== 0) return;+ e.preventDefault();+ navigateActive();+ });+ panel.querySelector('.mwg-panel-share')?.addEventListener('click', (e) => shareListing(e.currentTarget, listing));panel.setAttribute('data-show', '1');prompt.querySelector('.mwg-prompt-text').textContent = listing.name;prompt.setAttribute('data-show', '1');}+ let shareResetTimer = 0;+ async function shareListing(btn, listing) {+ const url = new URL(listing.href, location.origin).href;+ try {+ if (navigator.clipboard?.writeText) {+ await navigator.clipboard.writeText(url);+ } else {+ const ta = document.createElement('textarea');+ ta.value = url;+ ta.style.cssText = 'position:fixed;top:0;left:0;opacity:0;pointer-events:none';+ document.body.appendChild(ta);+ ta.select();+ document.execCommand('copy');+ ta.remove();+ }+ btn.setAttribute('data-copied', '1');+ btn.setAttribute('title', 'Link copied');+ clearTimeout(shareResetTimer);+ shareResetTimer = setTimeout(() => {+ btn.removeAttribute('data-copied');+ btn.setAttribute('title', 'Copy link');+ }, 1600);+ } catch {+ showToast('Copy failed — long-press the link to copy it.');+ }+ }+function hidePanel() {panel.removeAttribute('data-show');prompt.removeAttribute('data-show');}- async function setFilter(next) {- if (next === filter) return;- filter = next;- for (const b of chips.children) b.setAttribute('aria-pressed', String(b.dataset.filter === filter));- // Reset the stream and the hall, then rebuild from the live position.+ // Tear the stream + hall back to a clean slate so a new filter or query+ // rebuilds the catalogue from the avatar's live position.+ function resetStream() {buffer = [];served = [];loadedAny = false;@@ -781,6 +915,41 @@ export function createMarketplaceGallery({ scene, getLocalPosition }) {}belt.position.z = 0;hideToast();+ }++ // Reflect the current filter + query back into the address bar so the hall is+ // always shareable/bookmarkable at exactly what's on screen. Default state+ // (All, no query) keeps the URL clean.+ function syncUrl() {+ try {+ const u = new URL(location.href);+ if (filter && filter !== 'all') u.searchParams.set('type', filter);+ else u.searchParams.delete('type');+ u.searchParams.delete('filter');+ if (query) u.searchParams.set('q', query);+ else u.searchParams.delete('q');+ history.replaceState(null, '', u.pathname + u.search + u.hash);+ } catch {+ /* replaceState can throw in sandboxed frames — non-fatal */+ }+ }++ async function setFilter(next) {+ if (next === filter) return;+ filter = next;+ for (const b of chips.children) b.setAttribute('aria-pressed', String(b.dataset.filter === filter));+ syncUrl();+ resetStream();+ await loadPage();+ fillEmptySlots();+ }++ async function applyQuery(next) {+ const v = (next || '').trim().slice(0, 80);+ if (v === query) return;+ query = v;+ syncUrl();+ resetStream();await loadPage();fillEmptySlots();}@@ -799,6 +968,7 @@ export function createMarketplaceGallery({ scene, getLocalPosition }) {window.addEventListener('keydown', onKeyDown, true);// ── Boot ────────────────────────────────────────────────────────────────────+ syncUrl(); // canonicalise a deep-linked URL (?type=skills → ?type=skill, etc.)for (let i = 0; i < SLOT_COUNT; i++) slots.push(buildSlot(i));loadPage().then(fillEmptySlots);@@ -806,7 +976,9 @@ export function createMarketplaceGallery({ scene, getLocalPosition }) {update,destroy() {window.removeEventListener('keydown', onKeyDown, true);- chips.remove();+ clearTimeout(searchTimer);+ clearTimeout(shareResetTimer);+ top.remove();panel.remove();prompt.remove();toast.remove();diff --git a/src/marketplace.js b/src/marketplace.jsindex 79f7bf43b..c0d24ca0c 100644--- a/src/marketplace.js+++ b/src/marketplace.js@@ -4629,6 +4629,7 @@ function renderCard(a) {</div><div class="desc">${escapeHtml(a.description || '')}</div><div class="stats">+ ${a.activated ? '<span class="stat-pill live-badge" title="Live — funded and active on the Money Pulse">◉ Live</span>' : ''}${onchainBadge}${pedigreeBadge}${coinChipHTML(a)}diff --git a/src/pointcloud-viewer.js b/src/pointcloud-viewer.jsindex a9145eb31..94baaddf4 100644--- a/src/pointcloud-viewer.js+++ b/src/pointcloud-viewer.js@@ -4,7 +4,7 @@// LingBot-Map): a binary PLY of world-space points with per-vertex RGB. This is a// plain point cloud, NOT a Gaussian splat — so it renders with THREE.Points, not// the splat engine. Render-on-demand (no idle rAF) keeps it efficient: the loop-// only paints while the user is interacting or an animation is settling.+// only paints while interacting, auto-rotating, or settling.import {Scene,@@ -22,12 +22,20 @@ import {import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';import { PLYLoader } from 'three/examples/jsm/loaders/PLYLoader.js';+export const COLOR_MODES = ['rgb', 'mono', 'height', 'depth'];+export class PointCloudViewer {constructor(host, { background = '#0a0a0a' } = {}) {this.host = host;this._disposed = false;this._needsRender = true;this._settleUntil = 0;+ this._autoRotate = false;+ this._colorMode = 'rgb';+ this._fps = 0;+ this._frames = 0;+ this._fpsT0 = performance.now();+ this._onFps = null;this.scene = new Scene();this.scene.background = new Color(background);@@ -35,7 +43,8 @@ export class PointCloudViewer {this.camera = new PerspectiveCamera(55, 1, 0.01, 5000);this.camera.position.set(0, 0, 4);- this.renderer = new WebGLRenderer({ antialias: false, powerPreference: 'high-performance' });+ // preserveDrawingBuffer so screenshot()/toDataURL reliably capture the frame.+ this.renderer = new WebGLRenderer({ antialias: false, powerPreference: 'high-performance', preserveDrawingBuffer: true });this.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));host.appendChild(this.renderer.domElement);@@ -47,8 +56,10 @@ export class PointCloudViewer {this.points = null;this.material = new PointsMaterial({ size: 0.012, sizeAttenuation: true, vertexColors: true });+ this._rgb = null; // original colours (Float32, 0..1), kept for colour-mode swapsthis._home = { position: new Vector3(0, 0, 4), target: new Vector3(0, 0, 0) };this._radius = 1;+ this._baseSize = 0.012;this._onResize = this._resize.bind(this);window.addEventListener('resize', this._onResize);@@ -69,11 +80,23 @@ export class PointCloudViewer {_tick() {if (this._disposed) return;requestAnimationFrame(this._loop);- const damping = this.controls.enableDamping && performance.now() < this._settleUntil;+ const now = performance.now();+ const damping = this.controls.enableDamping && now < this._settleUntil;+ if (this._autoRotate && this.points) {+ this.points.rotation.y += 0.0032;+ this._needsRender = true;+ }if (this._needsRender || damping) {this.controls.update();this.renderer.render(this.scene, this.camera);this._needsRender = false;+ // FPS sampling — only counts painted frames, reported ~2×/sec.+ this._frames++;+ if (now - this._fpsT0 >= 500) {+ this._fps = Math.round((this._frames * 1000) / (now - this._fpsT0));+ this._frames = 0; this._fpsT0 = now;+ this._onFps?.(this._fps);+ }}}@@ -96,8 +119,6 @@ export class PointCloudViewer {this.points.geometry.dispose();}if (!geom.getAttribute('color')) {- // No per-vertex colour (rare) — fall back to a neutral monochrome grey so- // the cloud is still legible against the dark stage.const n = geom.getAttribute('position').count;const grey = new Float32Array(n * 3).fill(0.78);geom.setAttribute('color', new BufferAttribute(grey, 3));@@ -106,18 +127,20 @@ export class PointCloudViewer {const box = geom.boundingBox || new Box3();const sphere = box.getBoundingSphere(new Sphere());const center = sphere.center.clone();- // Recenter the cloud on the origin so orbit pivots feel natural regardless- // of where the reconstruction placed its world frame.geom.translate(-center.x, -center.y, -center.z);this._radius = Math.max(sphere.radius, 0.001);-- // Scale point size to the scene extent so dense and sparse clouds both read.this.material.size = this._radius * 0.006;this._baseSize = this.material.size;+ // Snapshot original colours as 0..1 floats so colour modes can restore/derive.+ const col = geom.getAttribute('color');+ this._rgb = new Float32Array(col.count * 3);+ const norm = col.normalized ? 1 / 255 : 1;+ for (let i = 0; i < this._rgb.length; i++) this._rgb[i] = col.array[i] * norm;+this.points = new Points(geom, this.material);this.scene.add(this.points);-+ this._applyColorMode();this._frame();return { count: geom.getAttribute('position').count };}@@ -127,6 +150,7 @@ export class PointCloudViewer {const dist = r * 2.6;this._home.position.set(dist * 0.5, dist * 0.35, dist);this._home.target.set(0, 0, 0);+ if (this.points) this.points.rotation.set(0, 0, 0);this.camera.position.copy(this._home.position);this.controls.target.copy(this._home.target);this.camera.near = Math.max(r / 1000, 0.001);@@ -138,18 +162,90 @@ export class PointCloudViewer {recenter() {if (!this.points) return;+ this.points.rotation.set(0, 0, 0);this.camera.position.copy(this._home.position);this.controls.target.copy(this._home.target);this._settle();}- // Multiplier (0.25–4) on the auto-scaled base point size.setPointScale(mult) {if (!this._baseSize) return;this.material.size = this._baseSize * mult;this._needsRender = true;}+ setAutoRotate(on) {+ this._autoRotate = Boolean(on);+ this._needsRender = true;+ }+ toggleAutoRotate() { this.setAutoRotate(!this._autoRotate); return this._autoRotate; }+ get autoRotate() { return this._autoRotate; }++ get colorMode() { return this._colorMode; }+ setColorMode(mode) {+ if (!COLOR_MODES.includes(mode)) return;+ this._colorMode = mode;+ this._applyColorMode();+ }+ cycleColorMode() {+ const i = COLOR_MODES.indexOf(this._colorMode);+ this.setColorMode(COLOR_MODES[(i + 1) % COLOR_MODES.length]);+ return this._colorMode;+ }++ // Derive the active colour buffer from the original RGB + point positions.+ _applyColorMode() {+ if (!this.points || !this._rgb) return;+ const col = this.points.geometry.getAttribute('color');+ const pos = this.points.geometry.getAttribute('position');+ const out = col.array;+ const n = pos.count;+ if (this._colorMode === 'rgb') {+ out.set(this._rgb);+ } else if (this._colorMode === 'mono') {+ for (let i = 0; i < n; i++) {+ const l = 0.299 * this._rgb[i * 3] + 0.587 * this._rgb[i * 3 + 1] + 0.114 * this._rgb[i * 3 + 2];+ out[i * 3] = out[i * 3 + 1] = out[i * 3 + 2] = l;+ }+ } else {+ // height (Y) or depth (distance from origin), mapped through a mono ramp.+ let lo = Infinity, hi = -Infinity;+ const val = new Float32Array(n);+ for (let i = 0; i < n; i++) {+ const x = pos.array[i * 3], y = pos.array[i * 3 + 1], z = pos.array[i * 3 + 2];+ const v = this._colorMode === 'height' ? y : Math.hypot(x, y, z);+ val[i] = v; if (v < lo) lo = v; if (v > hi) hi = v;+ }+ const span = hi - lo || 1;+ for (let i = 0; i < n; i++) {+ const t = 0.12 + 0.83 * ((val[i] - lo) / span);+ out[i * 3] = out[i * 3 + 1] = out[i * 3 + 2] = t;+ }+ }+ col.normalized = false;+ col.needsUpdate = true;+ this._needsRender = true;+ }++ // Capture the current frame as a PNG data URL (preserveDrawingBuffer makes this+ // reliable). Forces a fresh render first so the latest state is captured.+ screenshot() {+ if (!this.points) return null;+ this.controls.update();+ this.renderer.render(this.scene, this.camera);+ return this.renderer.domElement.toDataURL('image/png');+ }++ stats() {+ return {+ points: this.points ? this.points.geometry.getAttribute('position').count : 0,+ fps: this._fps,+ colorMode: this._colorMode,+ autoRotate: this._autoRotate,+ };+ }+ onFps(cb) { this._onFps = cb; }+_settle() {this._settleUntil = performance.now() + 600;this._needsRender = true;@@ -184,7 +280,6 @@ export function sampleRoomCloud(count = 90_000) {i++;};const rnd = (seed) => {- // Deterministic hash-based pseudo-random — no Math.random (keeps samples stable).const s = Math.sin(seed * 12.9898) * 43758.5453;return s - Math.floor(s);};@@ -193,16 +288,12 @@ export function sampleRoomCloud(count = 90_000) {const region = rnd(k * 1.7 + 3);const jitter = (rnd(k * 2.3 + 7) - 0.5) * 0.04;if (region < 0.34) {- // floorput((rnd(k * 3.1 + 1) - 0.5) * 4, -1 + jitter, (rnd(k * 4.7 + 2) - 0.5) * 4, 0.22 + r * 0.12);} else if (region < 0.56) {- // back wallput((rnd(k * 5.3 + 4) - 0.5) * 4, (rnd(k * 6.1 + 5)) * 2.4 - 1, -2 + jitter, 0.38 + r * 0.14);} else if (region < 0.78) {- // side wallput(-2 + jitter, (rnd(k * 7.9 + 6)) * 2.4 - 1, (rnd(k * 8.3 + 7) - 0.5) * 4, 0.32 + r * 0.14);} else {- // centre object — a rounded columnconst t = rnd(k * 9.1 + 8);const theta = rnd(k * 10.7 + 9) * Math.PI * 2;const rad = 0.5 + 0.12 * Math.sin(t * 9);diff --git a/src/pulse.css b/src/pulse.cssindex d8e59d782..35943e1e7 100644--- a/src/pulse.css+++ b/src/pulse.css@@ -141,6 +141,7 @@border-radius: var(--radius-pill, 999px); padding: 4px 11px; white-space: nowrap; margin-left: auto;transition: color .14s ease, border-color .14s ease, background .14s ease; }.px-market-action:hover { color: var(--ink-bright, #fff); border-color: var(--stroke-strong, rgba(255,255,255,.22)); background: var(--surface-2, rgba(255,255,255,.05)); }+.px-market-action:active { background: var(--surface-3, rgba(255,255,255,.10)); transform: translateY(0.5px); }.px-market-action:focus-visible { outline: 2px solid var(--ink-bright, #fff); outline-offset: 2px; }/* One-line plain-language readout under the KPIs — the human summary of the week. */.px-trade-insight { margin: 0 0 var(--space-md, 16px); font-size: var(--text-sm, .8rem); line-height: 1.45; color: var(--ink-dim, #aaa); }@@ -191,7 +192,8 @@ink ramp so tips/trades/launches read as one calm monochrome stream. */.px-shell .mp { --mp-accent: var(--ink-bright, #fff); --mp-accent-soft: rgba(255,255,255,.08); }.px-shell .mp-k-tip .mp-glyph,-.px-shell .mp-k-launch .mp-glyph { color: var(--ink-bright, #fff); }+.px-shell .mp-k-launch .mp-glyph,+.px-shell .mp-k-purchase .mp-glyph { color: var(--ink-bright, #fff); }.px-shell .mp-k-snipe .mp-glyph { color: var(--ink, #e8e8e8); }.px-shell .mp-k-trade .mp-glyph,.px-shell .mp-k-pay .mp-glyph { color: var(--ink-dim, #888); }diff --git a/src/pulse.js b/src/pulse.jsindex 1566e7e9e..181c36b9b 100644--- a/src/pulse.js+++ b/src/pulse.js@@ -416,7 +416,18 @@ function renderTrading(d) {// One honest, plain-language readout of the week — what ran, what it cost, and// whether anything has closed yet. Sells carry no SOL out, so cost is over buys.- const insight = $('px-trade-insight');+ // The element is created once, just after the KPI grid, if the markup omits it.+ let insight = $('px-trade-insight');+ if (!insight) {+ const kpis = panel.querySelector('.px-market-kpis');+ if (kpis) {+ insight = document.createElement('p');+ insight.id = 'px-trade-insight';+ insight.className = 'px-trade-insight';+ insight.hidden = true;+ kpis.insertAdjacentElement('afterend', insight);+ }+ }if (insight) {if ((w7.trades || 0) > 0) {let line = `Agents ran ${fmtNum(w7.trades)} trade${w7.trades === 1 ? '' : 's'} this week, deploying ${fmtSol(w7.deployed_sol)} into buys (${fmtSol(w7.avg_trade_sol)} avg).`;@@ -431,7 +442,9 @@ function renderTrading(d) {}// Reveal the in-panel "show trades in feed" action only when there's something to- // show. It carries data-filter="trades", so the shared counter wiring drives it.+ // show. It carries data-filter="trades" so the shared counter wiring drives it —+ // matching the headline Trades counter exactly (both count category='trade' and+ // reveal the trades+snipes feed slice, the platform-wide "Trades" convention).const filterBtn = $('px-trade-filter');if (filterBtn) filterBtn.hidden = !((w24.trades || 0) > 0 || (w7.trades || 0) > 0);@@ -457,6 +470,9 @@ function renderTradeSpark(series) {const days = Array.isArray(series) ? series : [];const total = days.reduce((s, d) => s + (d.trades || 0), 0);if (totalEl) totalEl.textContent = `${fmtNum(total)} trade${total === 1 ? '' : 's'}`;+ // Fold the live total into the chart's accessible name so a screen reader hears+ // the number, not just "Daily trade count" — the bars themselves are decorative.+ host.setAttribute('aria-label', `Daily trades, last 7 days — ${total} total`);if (!days.length) { host.innerHTML = `<p class="px-lb-empty">No activity yet.</p>`; return; }const peak = Math.max(1, ...days.map((d) => d.trades || 0));host.innerHTML = daysdiff --git a/src/scene-capture.js b/src/scene-capture.jsindex 600564f58..826d51a3a 100644--- a/src/scene-capture.js+++ b/src/scene-capture.js@@ -19,11 +19,28 @@ const STAGE = () => $('#pc-stage');const HOST = () => $('#pc-host');// ── viewer lifecycle ──────────────────────────────────────────────────────────+const COLOR_LABELS = { rgb: 'Colour', mono: 'Mono', height: 'Height', depth: 'Depth' };+let baseLabel = '';+function ensureViewer() {- if (!viewer) viewer = new PointCloudViewer(HOST(), { background: '#0a0a0a' });+ if (!viewer) {+ viewer = new PointCloudViewer(HOST(), { background: '#0a0a0a' });+ viewer.onFps(() => refreshStats());+ }return viewer;}+function refreshStats() {+ if (!viewer || !baseLabel) return;+ const s = viewer.stats();+ const bits = [baseLabel];+ // fps is only meaningful under continuous render (auto-rotate); render-on-demand+ // idles by design, so a static reading would misrepresent performance.+ if (s.autoRotate && s.fps) bits.push(`${s.fps} fps`);+ if (s.colorMode && s.colorMode !== 'rgb') bits.push(COLOR_LABELS[s.colorMode]);+ $('#pc-hud-label').textContent = bits.join(' · ');+}+// ── overlay states ────────────────────────────────────────────────────────────function showOnly(id) {for (const k of ['pc-idle', 'pc-loading', 'pc-error']) {@@ -43,9 +60,13 @@ function setError(title, sub) {showOnly('pc-error');}function setLive(label) {+ baseLabel = label;$('#pc-hud-label').textContent = label;$('#pc-hud').hidden = false;for (const k of ['pc-idle', 'pc-loading', 'pc-error']) $(`#${k}`).hidden = true;+ for (const id of ['pc-size', 'pc-color', 'pc-rotate', 'pc-shot', 'pc-recenter']) {+ const el = $(`#${id}`); if (el) el.disabled = false;+ }}function setDownload(url, filename) {@@ -100,6 +121,15 @@ async function loadFromFile(file) {}}+function saveScreenshot() {+ const url = viewer?.screenshot();+ if (!url) return;+ const a = document.createElement('a');+ a.href = url;+ a.download = `scene-${Date.now()}.png`;+ a.click();+}+function loadSample() {setLoading('Building sample cloud…', 'Synthetic interior · monochrome');const v = ensureViewer();@@ -125,6 +155,48 @@ function processingCopy(seconds, eta) {setLoading(`Reconstructing · ${seconds}s`, `${stage}${etaTxt}`);}+// Upload a local video to R2 via a presigned PUT, then return its public URL so+// the capture job can be submitted with it. Mirrors the forge-upload flow.+async function uploadVideo(file) {+ setLoading('Uploading video…', `${file.name} · ${(file.size / 1024 / 1024).toFixed(1)} MB`);+ const presignRes = await fetch('/api/scene-upload', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ content_type: file.type, size_bytes: file.size }),+ });+ const presign = await presignRes.json().catch(() => ({}));+ if (presignRes.status === 503) {+ throw new Error(presign.message || 'Video upload is not configured here. Paste a public video URL instead.');+ }+ if (!presignRes.ok) throw new Error(presign.message || `Upload could not start (HTTP ${presignRes.status}).`);++ const put = await fetch(presign.upload_url, {+ method: 'PUT',+ headers: presign.headers || { 'content-type': file.type },+ body: file,+ });+ if (!put.ok) throw new Error(`Upload failed (HTTP ${put.status}).`);+ return presign.public_url;+}++async function startCaptureFromFile(file) {+ stopPolling();+ $('#pc-run').disabled = true;+ $('#pc-video-pick').disabled = true;+ let url;+ try {+ url = await uploadVideo(file);+ } catch (err) {+ setError('Couldn’t upload that video', err.message);+ $('#pc-run').disabled = false;+ $('#pc-video-pick').disabled = false;+ return;+ }+ $('#pc-url').value = url;+ $('#pc-video-pick').disabled = false;+ startCapture();+}+async function startCapture() {const url = $('#pc-url').value.trim();if (!url) { $('#pc-url').focus(); return; }@@ -204,6 +276,12 @@ function init() {$('#pc-run').addEventListener('click', startCapture);$('#pc-url').addEventListener('keydown', (e) => { if (e.key === 'Enter') startCapture(); });+ $('#pc-video-pick').addEventListener('click', () => $('#pc-video-file').click());+ $('#pc-video-file').addEventListener('change', (e) => {+ const file = e.target.files?.[0];+ if (file) startCaptureFromFile(file);+ e.target.value = '';+ });$('#pc-load-url').addEventListener('click', () => {const u = $('#pc-ply-url').value.trim();@@ -225,6 +303,29 @@ function init() {$('#pc-error-retry').addEventListener('click', loadSample);$('#pc-recenter').addEventListener('click', () => viewer?.recenter());$('#pc-size').addEventListener('input', (e) => viewer?.setPointScale(Number(e.target.value)));+ $('#pc-color').addEventListener('click', () => { viewer?.cycleColorMode(); refreshStats(); });+ $('#pc-rotate').addEventListener('click', () => {+ const on = viewer?.toggleAutoRotate();+ $('#pc-rotate').classList.toggle('is-active', !!on);+ });+ $('#pc-shot').addEventListener('click', saveScreenshot);++ // Keyboard shortcuts (ignored while typing in an input/select).+ window.addEventListener('keydown', (e) => {+ const tag = (e.target.tagName || '').toLowerCase();+ if (tag === 'input' || tag === 'select' || tag === 'textarea' || e.metaKey || e.ctrlKey) return;+ if (!viewer || $('#pc-hud').hidden) return;+ const k = e.key.toLowerCase();+ if (k === 'r') viewer.recenter();+ else if (k === ' ') { e.preventDefault(); $('#pc-rotate').click(); }+ else if (k === 'c') $('#pc-color').click();+ else if (k === 's') saveScreenshot();+ else if (k === '[' || k === ']') {+ const s = $('#pc-size');+ s.value = String(Math.min(4, Math.max(0.25, Number(s.value) + (k === ']' ? 0.25 : -0.25))));+ s.dispatchEvent(new Event('input', { bubbles: true }));+ }+ });// Drag & drop a .ply onto the stage.const stage = STAGE();@@ -239,7 +340,9 @@ function init() {});// Deep links: ?src=<ply-url> renders directly; ?video=<url> pre-fills capture.+ // ?embed=1 strips the chrome for the MCP / agent point-cloud artifact iframe.const p = new URLSearchParams(location.search);+ if (p.get('embed') === '1') document.body.classList.add('pc-embed');if (p.get('src')) { $('#pc-ply-url').value = p.get('src'); loadFromUrl(p.get('src'), p.get('name') || undefined); }if (p.get('video')) $('#pc-url').value = p.get('video');diff --git a/src/shared/agent-screen-client.js b/src/shared/agent-screen-client.jsindex 4ea18aeea..927cdecbe 100644--- a/src/shared/agent-screen-client.js+++ b/src/shared/agent-screen-client.js@@ -51,20 +51,9 @@ export function createAgentScreenClient(agentId, handlers = {}) {} catch { /* malformed event */ }});- es.addEventListener('open-info', (e) => {- // Note: 'open' is a native EventSource event; we use 'open-info' for our- // custom payload but the SSE sends event: open — handle both.- try {- onOpen?.(JSON.parse(e.data));- } catch { /* malformed event */ }- });-- // The SSE spec fires 'open' for the HTTP connection; we name our custom- // open-metadata event 'open' in the stream. EventSource conflates them, so- // we listen on the 'message' handler for untyped events and on named event- // listeners for typed ones. The server sends `event: open` for our custom- // metadata — this will NOT fire the native 'open' listener, it fires the- // named 'open' listener below.+ // The server sends `event: open` carrying { agentId, agentName, ts }. The+ // native EventSource 'open' (connection established) has no `.data`, so the+ // `if (e.data)` guard below distinguishes the two on the same listener.es.addEventListener('open', (e) => {if (e.data) {try { onOpen?.(JSON.parse(e.data)); } catch { /* ok */ }diff --git a/src/shared/agent-watch-panel.js b/src/shared/agent-watch-panel.jsindex 26c1ff1e0..332e51e83 100644--- a/src/shared/agent-watch-panel.js+++ b/src/shared/agent-watch-panel.js@@ -150,6 +150,31 @@ function injectStyles() {}.wp-screen-wrap:hover .wp-screen-expand { opacity: 1; }.wp-screen-expand:hover { background: rgba(255,255,255,0.14); color: #fff; }+.wp-screen-fullview {+ position: absolute;+ bottom: 10px;+ right: 50px;+ z-index: 4;+ display: inline-flex;+ align-items: center;+ gap: 4px;+ background: rgba(0,0,0,0.52);+ backdrop-filter: blur(10px);+ -webkit-backdrop-filter: blur(10px);+ border: 1px solid rgba(255,255,255,0.1);+ border-radius: 6px;+ color: rgba(255,255,255,0.6);+ font-size: 11px;+ font-weight: 600;+ line-height: 1;+ padding: 6px 9px;+ text-decoration: none;+ cursor: pointer;+ opacity: 0;+ transition: opacity 0.2s, background 0.12s, color 0.12s;+}+.wp-screen-wrap:hover .wp-screen-fullview { opacity: 1; }+.wp-screen-fullview:hover { background: rgba(255,255,255,0.14); color: #fff; }/* ── Webcam pane ──────────────────────────────────────────────── */.wp-cam-wrap {@@ -813,6 +838,7 @@ class WatchPanel {<div class="wp-screen-badge-dot offline" id="wp-dot"></div><span id="wp-badge-label">Connecting</span></div>+ <a class="wp-screen-fullview" href="/agent-screen?agentId=${encodeURIComponent(this.agentId)}" aria-label="Open the full live viewer" title="Open full view">⤢ Full view</a><button class="wp-screen-expand" aria-label="Fullscreen">⛶</button></div><div class="wp-cam-wrap" id="wp-cw">diff --git a/src/shared/money-pulse.js b/src/shared/money-pulse.jsindex 2ccb8ad98..1d9254640 100644--- a/src/shared/money-pulse.js+++ b/src/shared/money-pulse.js@@ -32,6 +32,7 @@ const KIND_META = {trade: { glyph: '⇄', label: 'Trade', verb: 'traded', cls: 'mp-k-trade' },snipe: { glyph: '⚡', label: 'Snipe', verb: 'sniped', cls: 'mp-k-snipe' },payment: { glyph: '→', label: 'Payment', verb: 'paid', cls: 'mp-k-pay' },+ purchase:{ glyph: '⊕', label: 'Purchase',verb: 'bought a skill', cls: 'mp-k-purchase' },launch: { glyph: '✦', label: 'Launch', verb: 'launched', cls: 'mp-k-launch' },};@@ -41,6 +42,7 @@ const FILTERS = [{ id: 'launches', label: 'Launches' },{ id: 'trades', label: 'Trades' },{ id: 'payments', label: 'Payments' },+ { id: 'purchases', label: 'Purchases' },];let _stylesInjected = false;@@ -88,6 +90,7 @@ function injectStyles() {.mp-k-launch .mp-glyph { color: var(--mp-accent); }.mp-k-snipe .mp-glyph { color: var(--warn, #fbbf24); }.mp-k-trade .mp-glyph, .mp-k-pay .mp-glyph { color: var(--ink-dim, #9aa); }+.mp-k-purchase .mp-glyph { color: var(--mp-accent); }.mp-body { flex: 1 1 auto; min-width: 0; }.mp-line { font-size: var(--text-md, .84rem); line-height: 1.3; color: var(--ink, #e8e8e8); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }.mp-name { font-weight: 600; color: var(--ink-bright, #fff); }@@ -160,7 +163,13 @@ function fmtAmount(ev) {return `◎${s}`;}if (ev.amount_raw != null) {- // USDC (6dp) is the only non-SOL asset we record a price for; show $ when priced.+ // $THREE-denominated rows (skill purchases) show the token amount, compacted.+ if (ev.asset === 'THREE' || ev.kind === 'purchase') {+ const t = Number(ev.amount_raw) / 1e6;+ const s = t >= 1000 ? `${(t / 1000).toFixed(1)}k` : (t >= 1 ? String(Math.round(t)) : t.toFixed(2));+ return `${s} $THREE`;+ }+ // USDC (6dp) is the only other non-SOL asset we price; show $ when priced.if (ev.usd != null) return `$${Number(ev.usd).toFixed(2)}`;return `${(Number(ev.amount_raw) / 1e6).toFixed(2)}`;}@@ -191,6 +200,10 @@ function sentenceHTML(ev) {return `<span class="mp-name">${name}</span> sniped${amtHTML}${usdHTML}`;case 'payment':return `<span class="mp-name">${name}</span> paid${amtHTML}${usdHTML}`;+ case 'purchase': {+ const skill = ev.skill ? `<span class="mp-amount">${esc(ev.skill)}</span>` : 'a skill';+ return `<span class="mp-name">${name}</span> bought ${skill}${amtHTML ? ` for${amtHTML}` : ''}`;+ }case 'trade':default:return `<span class="mp-name">${name}</span> traded${amtHTML}${usdHTML}`;diff --git a/src/user-launcher.css b/src/user-launcher.cssnew file mode 100644index 000000000..1e688fdca--- /dev/null+++ b/src/user-launcher.css@@ -0,0 +1,61 @@+/* /launcher — personal Memetic Launcher. Additive to admin-launcher.css (shared+ monochrome .ml-* atoms). Only the few user-only pieces live here: the preview+ badge, the explainer note, and the synthesized-coin sample card. */++/* preview badge in the hero */+.ul-badge {+ font-size: var(--text-2xs, 0.66rem);+ font-weight: 700;+ text-transform: uppercase;+ letter-spacing: 0.1em;+ color: var(--ink-dim, #999);+ border: 1px solid var(--stroke-strong, rgba(255, 255, 255, 0.18));+ border-radius: var(--radius-pill, 999px);+ padding: 5px 12px;+ white-space: nowrap;+}++/* honest explainer */+.ul-note {+ display: flex;+ align-items: flex-start;+ gap: 12px;+ background: var(--surface-1, rgba(255, 255, 255, 0.03));+ border: 1px solid var(--stroke, rgba(255, 255, 255, 0.08));+ border-radius: var(--radius-md, 12px);+ padding: 14px 16px;+ margin-bottom: var(--space-lg, 24px);+}+.ul-note-ico { font-size: 1rem; color: var(--ink, #ccc); line-height: 1.5; }+.ul-note p { margin: 0; font-size: var(--text-sm, 0.82rem); line-height: 1.55; color: var(--ink-dim, #aaa); }+.ul-note strong { color: var(--ink-bright, #fff); font-weight: 700; }++/* 4-up stats (vs admin's 6) */+.ul-stats { grid-template-columns: repeat(4, 1fr); }+.ul-s-mode { text-transform: capitalize; }++.ul-net-row { margin-top: var(--space-md, 16px); }++/* preview-a-coin card */+.ul-preview-card .ml-console-h { margin-bottom: 6px; }+.ul-preview-btn { padding: 6px 14px; }+.ul-sample {+ margin-top: var(--space-md, 14px);+ background: var(--surface-2, rgba(255, 255, 255, 0.05));+ border: 1px solid var(--stroke-strong, rgba(255, 255, 255, 0.14));+ border-radius: var(--radius-md, 12px);+ padding: 16px;+ animation: ml-in 0.24s ease;+}+.ul-sample-head { display: flex; align-items: baseline; gap: 10px; flex-wrap: wrap; }+.ul-sample-name { font-family: var(--font-display, sans-serif); font-size: 1.15rem; font-weight: 700; color: var(--ink-bright, #fff); }+.ul-sample-sym { font-family: var(--font-mono, monospace); font-size: var(--text-sm, 0.82rem); color: var(--ink-dim, #999); }+.ul-sample-desc { margin: 8px 0 0; font-size: var(--text-sm, 0.82rem); line-height: 1.5; color: var(--ink-dim, #aaa); }+.ul-sample-meta { margin-top: 12px; font-size: var(--text-2xs, 0.7rem); color: var(--ink-dim, #888); display: flex; align-items: center; gap: 7px; flex-wrap: wrap; }+.ul-sample-meta strong { color: var(--ink, #e8e8e8); font-weight: 700; }+.ul-sample-empty { margin-top: var(--space-md, 14px); color: var(--ink-dim, #888); font-size: var(--text-xs, 0.78rem); line-height: 1.5; }+.ul-sample-empty p { margin: 0; }+.ul-sample-empty strong { color: var(--ink, #e8e8e8); }++@media (max-width: 940px) { .ul-stats { grid-template-columns: repeat(2, 1fr); } }+@media (prefers-reduced-motion: reduce) { .ul-sample { animation: none; } }diff --git a/src/user-launcher.js b/src/user-launcher.jsnew file mode 100644index 000000000..edf891311--- /dev/null+++ b/src/user-launcher.js@@ -0,0 +1,391 @@+// /launcher — your personal Memetic Launcher (the per-user scope).+//+// Talks only to /api/launcher/me (session or bearer). The launcher is preview-only+// (server hard-locks dry-run), so there is no arm modal and no real-SOL surface —+// "On" simply lets the cron pick coins from your agents and record them. All+// API-sourced strings are escaped before they touch the DOM.++const API = '/api/launcher/me';+const REFRESH_MS = 6000;++const MODES = [+ { id: 'hybrid', name: 'Hybrid', desc: 'Trend first, meme + random filler to hold cadence.' },+ { id: 'trend', name: 'Trend', desc: 'Only ride live cultural narratives.' },+ { id: 'meme', name: 'Meme', desc: 'Coins original memes from culture.' },+ { id: 'random', name: 'Random', desc: 'Wordlist salad. No LLM, pure volume.' },+ { id: 'off', name: 'Off', desc: 'Selected but idle. Picks nothing.' },+];+const SOURCES = [+ { id: 'coin_intel', label: 'Coin intel' },+ { id: 'trending', label: 'Trending' },+ { id: 'knowyourmeme', label: 'Know Your Meme' },+ { id: 'x', label: 'X' },+ { id: 'hackernews', label: 'Hacker News' },+ { id: 'reddit', label: 'Reddit' },+ { id: 'wikipedia', label: 'Wikipedia' },+];+const EDITABLE = ['enabled', 'mode', 'sources', 'target_cadence_seconds', 'max_per_hour', 'network'];++let loaded = null;+let draft = null;+let refreshTimer = null;+let built = false;++const $ = (id) => document.getElementById(id);+const esc = (s) =>+ String(s == null ? '' : s).replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));++// ── API ──────────────────────────────────────────────────────────────────────+async function api(method, body) {+ const r = await fetch(API, {+ method,+ headers: { 'content-type': 'application/json' },+ credentials: 'same-origin',+ body: body ? JSON.stringify(body) : undefined,+ });+ if (r.status === 401) { showGate(); throw new Error('unauthorized'); }+ const j = await r.json().catch(() => null);+ if (!r.ok) throw new Error(j?.error_description || j?.error || `HTTP ${r.status}`);+ return j;+}++function safeJson(s, d) { try { return JSON.parse(s); } catch { return d; } }+function normalize(c) {+ c = c || {};+ const arr = (v) => (Array.isArray(v) ? v : typeof v === 'string' ? safeJson(v, []) : []);+ return {+ enabled: !!c.enabled,+ paused: !!c.paused,+ pause_reason: c.pause_reason || '',+ mode: c.mode || 'hybrid',+ sources: arr(c.sources),+ target_cadence_seconds: Number(c.target_cadence_seconds ?? 60),+ max_per_hour: Number(c.max_per_hour ?? 30),+ network: c.network || 'mainnet',+ };+}++// ── gate ──────────────────────────────────────────────────────────────────────+function showGate() {+ $('ul-panel').hidden = true;+ $('ul-gate').hidden = false;+ $('ul-root').setAttribute('aria-busy', 'false');+ stopRefresh();+}++// ── load + render ──────────────────────────────────────────────────────────────+async function load() {+ const state = await api('GET');+ loaded = normalize(state.config);+ draft = { ...loaded };+ $('ul-gate').hidden = true;+ $('ul-panel').hidden = false;+ $('ul-root').setAttribute('aria-busy', 'false');+ buildStaticControls();+ renderForm();+ renderState(state);+ updateDirty();+ startRefresh();+}++async function refresh() {+ if (document.hidden) return;+ try {+ const state = await api('GET');+ const fresh = normalize(state.config);+ if (!isDirty()) { loaded = fresh; draft = { ...fresh }; renderForm(); updateDirty(); }+ else { loaded.paused = fresh.paused; loaded.pause_reason = fresh.pause_reason; }+ renderState(state);+ } catch { /* transient */ }+}+function startRefresh() { stopRefresh(); refreshTimer = setInterval(refresh, REFRESH_MS); }+function stopRefresh() { if (refreshTimer) clearInterval(refreshTimer); refreshTimer = null; }+document.addEventListener('visibilitychange', () => { if (!document.hidden) refresh(); });++// ── static controls (built once) ───────────────────────────────────────────────+function buildStaticControls() {+ if (built) return;+ built = true;++ $('ul-modes').innerHTML = MODES.map(+ (m) => `+ <label class="ml-mode">+ <input type="radio" name="ul-mode" value="${m.id}" />+ <span class="ml-mode-ui">+ <span class="ml-mode-name">${esc(m.name)}</span>+ <span class="ml-mode-desc">${esc(m.desc)}</span>+ </span>+ </label>`,+ ).join('');+ $('ul-modes').addEventListener('change', (e) => { if (e.target.name === 'ul-mode') { draft.mode = e.target.value; onEdit(); } });++ $('ul-sources').innerHTML = SOURCES.map(+ (s) => `<button type="button" class="ml-chip" data-src="${s.id}" aria-pressed="false">${esc(s.label)}</button>`,+ ).join('');+ $('ul-sources').addEventListener('click', (e) => {+ const btn = e.target.closest('.ml-chip');+ if (!btn) return;+ const set = new Set(draft.sources);+ set.has(btn.dataset.src) ? set.delete(btn.dataset.src) : set.add(btn.dataset.src);+ draft.sources = [...set];+ onEdit();+ });++ $('ul-network').addEventListener('click', (e) => {+ const btn = e.target.closest('.ml-seg-btn');+ if (!btn) return;+ draft.network = btn.dataset.net;+ onEdit();+ });++ bindNum('ul-cadence', 'target_cadence_seconds');+ bindNum('ul-maxhour', 'max_per_hour');++ $('ul-enable').addEventListener('click', () => { draft.enabled = !draft.enabled; onEdit(); });+ $('ul-config').addEventListener('submit', (e) => e.preventDefault());+ $('ul-save').addEventListener('click', save);+ $('ul-discard').addEventListener('click', () => { draft = { ...loaded }; renderForm(); updateDirty(); });+ $('ul-resume').addEventListener('click', resumeBreaker);+ $('ul-preview-btn').addEventListener('click', previewCoin);++ // ⌘/Ctrl+S saves pending edits.+ document.addEventListener('keydown', (e) => {+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') {+ if (loaded && !$('ul-panel').hidden && isDirty()) { e.preventDefault(); save(); }+ }+ });+}++function bindNum(id, key) {+ $(id).addEventListener('input', () => {+ const n = Number($(id).value);+ if (Number.isFinite(n)) { draft[key] = n; onEdit(false); }+ });+}+function onEdit(rerender = true) { if (rerender) renderForm(); updateDirty(); renderStatusFromDraft(); }++// ── render form ────────────────────────────────────────────────────────────────+function renderForm() {+ for (const el of document.querySelectorAll('input[name="ul-mode"]')) el.checked = el.value === draft.mode;+ const set = new Set(draft.sources);+ for (const btn of document.querySelectorAll('#ul-sources .ml-chip')) {+ btn.setAttribute('aria-pressed', set.has(btn.dataset.src) ? 'true' : 'false');+ }+ $('ul-sources-card').style.opacity = draft.mode === 'trend' || draft.mode === 'hybrid' ? '1' : '0.5';+ for (const btn of document.querySelectorAll('#ul-network .ml-seg-btn')) btn.classList.toggle('active', btn.dataset.net === draft.network);+ setVal('ul-cadence', draft.target_cadence_seconds);+ setVal('ul-maxhour', draft.max_per_hour);+ $('ul-cadence-hint').textContent = cadenceHint(draft.target_cadence_seconds);+ renderStatusFromDraft();+}+function setVal(id, v) { const el = $(id); if (el && document.activeElement !== el) el.value = v; }+function cadenceHint(sec) { if (!sec) return ''; return `≈ ${Math.floor(3600 / sec).toLocaleString()} coins / hour at full tilt`; }++function renderStatusFromDraft() {+ $('ul-enable').setAttribute('aria-pressed', draft.enabled ? 'true' : 'false');+ $('ul-enable-lbl').textContent = draft.enabled ? 'On' : 'Off';+ const dot = $('ul-status-dot');+ dot.className = 'ml-dot';+ let line;+ if (loaded.paused) { dot.classList.add('is-paused'); line = `Paused — ${esc(loaded.pause_reason || 'too many misses')}.`; }+ else if (loaded.enabled) { dot.classList.add('is-dry'); line = `Previewing — coining on ${esc(loaded.mode)} mode every ${loaded.target_cadence_seconds}s. No SOL moves.`; }+ else { line = 'Off — idle. Turn on to watch it design your rotation.'; }+ if (isDirty()) line += ' • Unsaved changes.';+ $('ul-status-line').textContent = line;+ $('ul-s-mode').textContent = draft.mode;+}++// ── server state ────────────────────────────────────────────────────────────────+function renderState(state) {+ const s = state.stats || {};+ $('ul-s-dry').textContent = num(s.dry_runs_today);+ $('ul-s-queue').textContent = num(state.queue_enabled);+ $('ul-s-eligible').textContent = num(state.eligible_agents);++ const breaker = $('ul-breaker');+ if (loaded.paused) { breaker.hidden = false; $('ul-breaker-txt').textContent = `Paused: ${loaded.pause_reason || 'too many misses'}.`; }+ else breaker.hidden = true;++ renderConsole(state.console || [], state.config?.network || draft.network);+ $('ul-console-meta').textContent = `updated ${new Date().toLocaleTimeString()}`;+ renderNarratives(state.narratives);+}++// ── narratives ──────────────────────────────────────────────────────────────────+let lastNarrSig = null;+function renderNarratives(narr) {+ const terms = (narr && Array.isArray(narr.terms)) ? narr.terms : [];+ const sig = (narr?.top?.term || '') + '|' + terms.map((t) => `${t.term}:${Math.round(t.score)}`).join(',');+ if (sig === lastNarrSig) return;+ lastNarrSig = sig;++ const list = $('ul-narr-list');+ const empty = $('ul-narr-empty');+ const lead = $('ul-narr-lead');+ const meta = $('ul-narr-meta');++ if (!terms.length) {+ list.innerHTML = '';+ empty.hidden = false;+ lead.hidden = true;+ meta.textContent = (draft.mode === 'trend' || draft.mode === 'hybrid') ? 'no signal' : 'trend off';+ return;+ }+ empty.hidden = true;+ meta.textContent = `${terms.length} live · ${(narr.providers || []).length} sources`;+ if (narr.top) {+ lead.hidden = false;+ lead.innerHTML = `Riding <strong>${esc(narr.top.term)}</strong>${narr.top.kind ? ` <span class="ml-narr-kind">${esc(narr.top.kind)}</span>` : ''} next.`;+ } else lead.hidden = true;++ const max = terms[0]?.score || 1;+ list.innerHTML = terms.slice(0, 12).map((t) => {+ const pct = Math.max(6, Math.round((Number(t.score) / max) * 100));+ const srcs = Array.isArray(t.sources) ? t.sources.length : 0;+ return `+ <li class="ml-narr-row" title="${esc((t.sources || []).join(', '))}">+ <span class="ml-narr-bar" style="width:${pct}%"></span>+ <span class="ml-narr-term">${esc(t.term)}</span>+ <span class="ml-narr-tags">${t.kind ? `<span class="ml-narr-kind">${esc(t.kind)}</span>` : ''}${srcs > 1 ? `<span class="ml-narr-conf">×${srcs}</span>` : ''}</span>+ </li>`;+ }).join('');+}++// ── console (keyed/incremental — flicker-free, scroll-stable) ─────────────────────+function runRowHtml(r, network) {+ const status = String(r.status || 'pending');+ const name = r.mint+ ? `<a href="${solscan(r.mint, network)}" target="_blank" rel="noopener">${esc(r.name || r.symbol || 'coin')}</a>`+ : esc(r.name || r.symbol || '—');+ const rode = topNarrative(r.trigger_detail);+ const meta = `<span class="ml-kind">${esc(r.kind || '')}</span>${rode ? ' · rode ' + esc(rode) : (r.trigger_source ? ' · ' + esc(r.trigger_source) : '')}`;+ return (+ `<span class="ml-pill s-${esc(status)}">${esc(statusLabel(status))}</span>` ++ `<span class="ml-run-main">` ++ `<span class="ml-run-name">${name} <span class="ml-run-sym">${esc(r.symbol || '')}</span></span>` ++ `<span class="ml-run-meta">${meta}</span>` ++ `</span>` ++ `<span class="ml-run-r"><span class="ml-run-time">${esc(reltime(r.created_at))}</span></span>`+ );+}+function runSig(r) { return `${r.status}|${r.mint || ''}|${reltime(r.created_at)}`; }+const _rows = new Map();+function renderConsole(runs, network) {+ const list = $('ul-runs');+ const empty = $('ul-runs-empty');+ if (!runs.length) { list.replaceChildren(); _rows.clear(); empty.hidden = false; return; }+ empty.hidden = true;+ const seen = new Set();+ let prev = null;+ for (const r of runs.slice(0, 50)) {+ const id = String(r.id);+ seen.add(id);+ const sig = runSig(r);+ let entry = _rows.get(id);+ if (!entry) {+ const li = document.createElement('li');+ li.className = 'ml-run ml-run--new';+ li.innerHTML = runRowHtml(r, network);+ setTimeout(() => li.classList.remove('ml-run--new'), 1100);+ entry = { el: li, sig };+ _rows.set(id, entry);+ } else if (entry.sig !== sig) {+ entry.el.innerHTML = runRowHtml(r, network);+ entry.sig = sig;+ }+ const ref = prev ? prev.nextSibling : list.firstChild;+ if (entry.el !== ref) list.insertBefore(entry.el, ref);+ prev = entry.el;+ }+ for (const [id, entry] of _rows) { if (!seen.has(id)) { entry.el.remove(); _rows.delete(id); } }+}++// ── preview a coin ──────────────────────────────────────────────────────────────+async function previewCoin() {+ const btn = $('ul-preview-btn');+ btn.disabled = true;+ btn.textContent = 'Synthesizing…';+ try {+ const r = await api('POST', { action: 'preview', mode: draft.mode });+ const s = r.sample;+ $('ul-sample-empty').hidden = true;+ $('ul-sample').hidden = false;+ $('ul-sample-name').textContent = s.name || 'Untitled';+ $('ul-sample-sym').textContent = s.symbol ? `$${s.symbol}` : '';+ $('ul-sample-desc').textContent = s.description || '';+ const bits = [];+ if (s.kind) bits.push(`<span class="ml-narr-kind">${esc(s.kind)}</span>`);+ if (s.top_narrative) bits.push(`rode <strong>${esc(s.top_narrative)}</strong>`);+ else if (s.trigger_source) bits.push(esc(s.trigger_source));+ $('ul-sample-meta').innerHTML = bits.join(' · ');+ } catch (err) {+ if (err.message !== 'unauthorized') toast(err.message, true);+ } finally {+ btn.disabled = false;+ btn.textContent = 'Synthesize';+ }+}++// ── dirty + save ───────────────────────────────────────────────────────────────+function pickEditable(o) { const r = {}; for (const k of EDITABLE) r[k] = o[k]; r.sources = [...(o.sources || [])].sort(); return r; }+function isDirty() { return JSON.stringify(pickEditable(draft)) !== JSON.stringify(pickEditable(loaded)); }+function updateDirty() { $('ul-savebar').hidden = !isDirty(); }++async function save() {+ const payload = {};+ for (const k of EDITABLE) payload[k] = draft[k];+ $('ul-save').disabled = true;+ try {+ const resp = await api('POST', payload);+ loaded = normalize(resp.config);+ draft = { ...loaded };+ renderForm();+ updateDirty();+ toast(loaded.enabled ? 'Saved — launcher is previewing' : 'Saved');+ refresh();+ } catch (err) {+ if (err.message !== 'unauthorized') toast(err.message, true);+ } finally {+ $('ul-save').disabled = false;+ }+}+async function resumeBreaker() {+ try { await api('POST', { action: 'resume' }); toast('Resumed'); refresh(); }+ catch (err) { if (err.message !== 'unauthorized') toast(err.message, true); }+}++// ── toast ──────────────────────────────────────────────────────────────────────+let toastTimer = null;+function toast(msg, isErr) {+ const t = $('ul-toast');+ t.textContent = msg;+ t.classList.toggle('is-err', !!isErr);+ t.hidden = false;+ clearTimeout(toastTimer);+ toastTimer = setTimeout(() => { t.hidden = true; }, 3200);+}++// ── formatters ─────────────────────────────────────────────────────────────────+function num(n) { return Number(n || 0).toLocaleString(); }+function trunc(s, n) { s = String(s || ''); return s.length > n ? s.slice(0, n - 1) + '…' : s; }+function statusLabel(s) { return { dry_run: 'preview', confirmed: 'live', launched: 'live' }[s] || s; }+function topNarrative(detail) {+ let d = detail;+ if (typeof d === 'string') { try { d = JSON.parse(d); } catch { return ''; } }+ const t = d && typeof d === 'object' ? d.top_narrative : '';+ return t ? trunc(String(t), 28) : '';+}+function solscan(mint, network) { return `https://solscan.io/token/${encodeURIComponent(mint)}${network === 'devnet' ? '?cluster=devnet' : ''}`; }+function reltime(iso) {+ if (!iso) return '';+ const d = (Date.now() - new Date(iso).getTime()) / 1000;+ if (d < 60) return `${Math.max(0, Math.floor(d))}s`;+ if (d < 3600) return `${Math.floor(d / 60)}m`;+ if (d < 86400) return `${Math.floor(d / 3600)}h`;+ return `${Math.floor(d / 86400)}d`;+}++// ── boot ───────────────────────────────────────────────────────────────────────+(async function boot() {+ try { await load(); } catch (err) { if (err.message !== 'unauthorized') showGate(); }+})();diff --git a/src/walk-agent-desk.js b/src/walk-agent-desk.jsindex 8a67f15df..c0e98b64a 100644--- a/src/walk-agent-desk.js+++ b/src/walk-agent-desk.js@@ -137,7 +137,10 @@ function createDesk(scene, opts = {}) {new MeshBasicMaterial({ map: tex, side: DoubleSide, toneMapped: false }),);screen.position.set(0, monY, -DESK_D / 2 + 0.15 + 0.023);- screen.userData.agentScreen = true; // raycast tag+ // Raycast tags — carry the agentId so a crosshair/raycast hit can deep-link+ // straight to /agent-screen?agentId=… (the proximity HUD already does this).+ screen.userData.agentScreen = true;+ screen.userData.agentId = agentId;group.add(screen);// ── avatar seated behind desk ────────────────────────────────────────diff --git a/tests/agent-activation.test.js b/tests/agent-activation.test.jsindex 187b44161..8108511da 100644--- a/tests/agent-activation.test.js+++ b/tests/agent-activation.test.js@@ -9,7 +9,7 @@*/import { describe, it, expect } from 'vitest';-import { activationConfig } from '../api/_lib/agent-activation.js';+import { activationConfig, evaluateActivation } from '../api/_lib/agent-activation.js';const SOL = 1_000_000_000;@@ -61,3 +61,42 @@ describe('activationConfig', () => {expect(activationConfig({ CIRCULATION_NETWORK: 'whatever' }).network).toBe('mainnet');});});++describe('evaluateActivation (pure decision matrix)', () => {+ const base = { owner: true, circulation: false, status: null, enabled: true, configured: true };++ it('proceeds for a real, owned, eligible agent on a live platform', () => {+ expect(evaluateActivation(base)).toEqual({ decision: 'proceed', reason: null });+ });++ it('blocks a non-owner before anything else', () => {+ // non-owner outranks every other condition, including already-activated+ expect(evaluateActivation({ ...base, owner: false, status: 'confirmed' }))+ .toEqual({ decision: 'forbidden', reason: 'not_owner' });+ });++ it('treats circulation (platform) agents as already live', () => {+ expect(evaluateActivation({ ...base, circulation: true }))+ .toEqual({ decision: 'platform_agent', reason: 'platform_agent' });+ });++ it('is idempotent — confirmed returns "already", never re-grants', () => {+ expect(evaluateActivation({ ...base, status: 'confirmed' }))+ .toEqual({ decision: 'already', reason: 'already_activated' });+ });++ it('reports an in-flight pending claim rather than racing a second grant', () => {+ expect(evaluateActivation({ ...base, status: 'pending' }))+ .toEqual({ decision: 'pending', reason: 'in_progress' });+ });++ it('is not_configured when disabled OR when no treasury is set', () => {+ expect(evaluateActivation({ ...base, enabled: false }).decision).toBe('not_configured');+ expect(evaluateActivation({ ...base, configured: false }).decision).toBe('not_configured');+ });++ it('orders checks so ownership and idempotency win over config', () => {+ // already-confirmed beats not_configured (don't tell an activated owner it's off)+ expect(evaluateActivation({ ...base, status: 'confirmed', enabled: false }).decision).toBe('already');+ });+});diff --git a/tests/agent-screen-frame-validation.test.js b/tests/agent-screen-frame-validation.test.jsnew file mode 100644index 000000000..ba5388b20--- /dev/null+++ b/tests/agent-screen-frame-validation.test.js@@ -0,0 +1,41 @@+/**+ * Frame-data validation for /api/agent-screen-push.+ *+ * Screen frames are pushed by an agent's own worker and then rendered to every+ * watcher's <img>. A frame's data URL must therefore be a base64 RASTER image+ * only. SVG is rejected: it can carry scripts / external fetches that would run+ * the instant a frame were ever inline-rendered instead of set as an <img src>.+ * This pins the allow/deny contract so the validator can't loosen unnoticed.+ */++import { describe, it, expect } from 'vitest';+import { isRasterDataUrl } from '../api/agent-screen-push.js';++// A minimal-but-valid base64 tail for the shapes under test.+const B64 = 'iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAAAAAA6fptVAAAACklEQVR4nGNgAAAAAgAB';++describe('isRasterDataUrl', () => {+ it('accepts png / jpeg / webp / gif raster data URLs', () => {+ expect(isRasterDataUrl(`data:image/png;base64,${B64}`)).toBe(true);+ expect(isRasterDataUrl(`data:image/jpeg;base64,${B64}`)).toBe(true);+ expect(isRasterDataUrl(`data:image/webp;base64,${B64}`)).toBe(true);+ expect(isRasterDataUrl(`data:image/gif;base64,${B64}`)).toBe(true);+ });++ it('rejects SVG data URLs (active-content vector)', () => {+ const svg = 'data:image/svg+xml;base64,' + Buffer.from(+ '<svg xmlns="http://www.w3.org/2000/svg" onload="alert(1)"></svg>',+ ).toString('base64');+ expect(isRasterDataUrl(svg)).toBe(false);+ });++ it('rejects non-image, non-base64, and non-string inputs', () => {+ expect(isRasterDataUrl('data:text/html;base64,' + B64)).toBe(false);+ expect(isRasterDataUrl('data:image/png,not-base64!!')).toBe(false);+ expect(isRasterDataUrl('https://evil.example/x.png')).toBe(false);+ expect(isRasterDataUrl('javascript:alert(1)')).toBe(false);+ expect(isRasterDataUrl(null)).toBe(false);+ expect(isRasterDataUrl(undefined)).toBe(false);+ expect(isRasterDataUrl(12345)).toBe(false);+ });+});diff --git a/tests/agent-screen-worker-compliance.test.js b/tests/agent-screen-worker-compliance.test.jsnew file mode 100644index 000000000..d58347d9c--- /dev/null+++ b/tests/agent-screen-worker-compliance.test.js@@ -0,0 +1,59 @@+/**+ * $THREE single-coin compliance guard for the agent-screen browser worker.+ *+ * The worker drives a real browser on the agent's behalf and narrates what it+ * does into the public live-screen feed. A previous revision shipped a default+ * "autonomous" mission that navigated to pump.fun, scanned trending tokens, and+ * pushed their names / symbols / market caps into that public feed — i.e. the+ * platform's own agents surfacing and ranking arbitrary third-party coins. That+ * violates the platform rule that $THREE is the only coin three.ws promotes.+ *+ * The idle loop must stay neutral: it may rest on a home page and say it's+ * standing by, but it must never scan, rank, extract, or narrate third-party+ * tokens or markets. This test pins that invariant at the source level so the+ * token-scanning mission can't quietly come back.+ */++import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, resolve } from 'node:path';++const __dir = dirname(fileURLToPath(import.meta.url));+const WORKER_DIR = resolve(__dir, '../workers/agent-screen-worker');++function workerSource() {+ return ['index.js', 'config.js', 'capture.js', 'task-runner.js']+ .map((f) => readFileSync(resolve(WORKER_DIR, f), 'utf8'))+ .join('\n');+}++describe('agent-screen worker — $THREE single-coin compliance', () => {+ const src = workerSource();++ it('does not hardcode a pump.fun autonomous navigation target', () => {+ // A user-supplied trade task may still resolve a runtime URL, but the worker+ // must not ship a baked-in pump.fun scan as its default behaviour.+ expect(src).not.toMatch(/PUMP_FUN_URL\s*=/);+ expect(src).not.toMatch(/goto\(\s*PUMP_FUN_URL/);+ });++ it('does not scan, extract, or narrate trending tokens / market caps', () => {+ const forbidden = [+ /trending token/i,+ /top\s+\d*\s*trending/i,+ /market\s*cap/i,+ /marketCap/,+ /holder count/i,+ ];+ for (const pattern of forbidden) {+ expect(src, `worker source must not contain ${pattern}`).not.toMatch(pattern);+ }+ });++ it('keeps a neutral idle mission that stands by for a user task', () => {+ // The idle cycle should exist and be content-agnostic.+ expect(src).toMatch(/Standing by/i);+ expect(src).toMatch(/HOME_URL/);+ });+});diff --git a/tests/api/scene-capture.test.js b/tests/api/scene-capture.test.jsnew file mode 100644index 000000000..5665c5037--- /dev/null+++ b/tests/api/scene-capture.test.js@@ -0,0 +1,218 @@+// Scene Capture (video → 3D point cloud) — provider routing + endpoint contract.+//+// Covers the path added for streaming video reconstruction:+// • The GCP provider's `video2scene` mode posts the video URL + sampling+// params to the LingBot-Map worker's /infer, forwards only set knobs, and+// resolves the finished .ply (resultPointCloudUrl) + telemetry on poll.+// • The /api/scene-capture endpoint validates input, degrades to a clean 503+// when the worker isn't configured, and proxies submit/poll through the+// provider.+//+// global fetch is stubbed to capture the worker submit body and model the+// worker's task responses; no network, no mocked product data.++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++const ORIGINAL_FETCH = globalThis.fetch;+const ENV_KEYS = ['GCP_VIDEO2SCENE_URL', 'GCP_RECONSTRUCTION_KEY'];+const ORIGINAL_ENV = Object.fromEntries(ENV_KEYS.map((k) => [k, process.env[k]]));+const WORKER_URL = 'https://model-video2scene-test.a.run.app';++beforeEach(() => {+ process.env.GCP_VIDEO2SCENE_URL = WORKER_URL;+ process.env.GCP_RECONSTRUCTION_KEY = 'test-shared-key';+});++afterEach(() => {+ globalThis.fetch = ORIGINAL_FETCH;+ for (const k of ENV_KEYS) {+ if (ORIGINAL_ENV[k] === undefined) delete process.env[k];+ else process.env[k] = ORIGINAL_ENV[k];+ }+});++async function freshProvider() {+ const mod = await import('../../api/_providers/gcp.js');+ return mod.createRegenProvider();+}++describe('gcp provider — video2scene mode routing', () => {+ it('supports video2scene only when GCP_VIDEO2SCENE_URL is set', async () => {+ let provider = await freshProvider();+ expect(provider.supportsMode('video2scene')).toBe(true);+ delete process.env.GCP_VIDEO2SCENE_URL;+ provider = await freshProvider();+ expect(provider.supportsMode('video2scene')).toBe(false);+ });++ it('posts the video_url + only-set params to /infer with the shared bearer', async () => {+ const calls = [];+ globalThis.fetch = vi.fn(async (url, opts) => {+ calls.push({ url: String(url), body: JSON.parse(opts.body), headers: opts.headers });+ return new Response(JSON.stringify({ task_id: 'task-xyz', status: 'queued' }), {+ status: 202,+ headers: { 'content-type': 'application/json' },+ });+ });++ const provider = await freshProvider();+ const job = await provider.submit({+ mode: 'video2scene',+ sourceUrl: 'https://cdn.example.com/walk.mp4',+ params: { mode: 'streaming', fps: 8, keyframe_interval: 4, mask_sky: true, max_points: 1_500_000, voxel_size: 0.02 },+ });++ expect(calls).toHaveLength(1);+ expect(calls[0].url).toBe(`${WORKER_URL}/infer`);+ expect(calls[0].headers.authorization).toBe('Bearer test-shared-key');+ expect(calls[0].body).toEqual({+ video_url: 'https://cdn.example.com/walk.mp4',+ mode: 'streaming',+ fps: 8,+ keyframe_interval: 4,+ max_points: 1_500_000,+ voxel_size: 0.02,+ mask_sky: true,+ });+ expect(job.extJobId).toBeTruthy();+ expect(job.backend).toBe('gcp');+ expect(job.eta).toBe(240);+ });++ it('sends an images[] array instead of video_url when frames are supplied', async () => {+ const calls = [];+ globalThis.fetch = vi.fn(async (url, opts) => {+ calls.push(JSON.parse(opts.body));+ return new Response(JSON.stringify({ task_id: 't', status: 'queued' }), { status: 202 });+ });+ const provider = await freshProvider();+ await provider.submit({+ mode: 'video2scene',+ sourceUrl: 'https://cdn.example.com/walk.mp4',+ params: { images: ['https://x/a.jpg', 'https://x/b.jpg'], fps: 8 },+ });+ expect(calls[0].images).toEqual(['https://x/a.jpg', 'https://x/b.jpg']);+ expect(calls[0].video_url).toBeUndefined();+ });++ it('resolves the finished point cloud + telemetry from result_gcs_url on poll', async () => {+ globalThis.fetch = vi.fn(async () =>+ new Response(JSON.stringify({ task_id: 'task-xyz', status: 'queued' }), { status: 202 }),+ );+ const provider = await freshProvider();+ const job = await provider.submit({+ mode: 'video2scene',+ sourceUrl: 'https://cdn.example.com/walk.mp4',+ params: {},+ });++ const ply = 'https://storage.googleapis.com/bucket/scenes/video2scene/task-xyz.ply';+ globalThis.fetch = vi.fn(async (url) => {+ expect(String(url)).toBe(`${WORKER_URL}/tasks/task-xyz`);+ return new Response(+ JSON.stringify({ task_id: 'task-xyz', status: 'done', result_gcs_url: ply, num_points: 1_234_567, frames: 240, bytes: 9999 }),+ { status: 200, headers: { 'content-type': 'application/json' } },+ );+ });++ const status = await provider.status(job.extJobId);+ expect(status.status).toBe('done');+ expect(status.resultPointCloudUrl).toBe(ply);+ expect(status.numPoints).toBe(1_234_567);+ expect(status.frames).toBe(240);+ // A point cloud is NOT a GLB mesh — the GLB field must stay unset.+ expect(status.resultGlbUrl).toBeUndefined();+ });++ it('reports a designed failure when the worker errors the task', async () => {+ globalThis.fetch = vi.fn(async () =>+ new Response(JSON.stringify({ task_id: 'task-xyz', status: 'queued' }), { status: 202 }),+ );+ const provider = await freshProvider();+ const job = await provider.submit({ mode: 'video2scene', sourceUrl: 'https://cdn.example.com/walk.mp4', params: {} });++ globalThis.fetch = vi.fn(async () =>+ new Response(JSON.stringify({ task_id: 'task-xyz', status: 'failed', error: 'no points above floor' }), { status: 200 }),+ );+ const status = await provider.status(job.extJobId);+ expect(status.status).toBe('failed');+ expect(status.error).toContain('no points');+ });+});++// ── Endpoint contract (api/scene-capture.js) ──────────────────────────────────++function mockReq({ method = 'POST', url = '/api/scene-capture', body = null } = {}) {+ const payload = body == null ? '' : JSON.stringify(body);+ const req = {+ method,+ url,+ headers: { 'content-type': 'application/json', 'x-forwarded-for': '203.0.113.7' },+ on(event, cb) {+ if (event === 'data' && payload) cb(Buffer.from(payload));+ if (event === 'end') cb();+ },+ };+ return req;+}++function mockRes() {+ return {+ statusCode: 200,+ headers: {},+ body: undefined,+ ended: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ getHeader(k) { return this.headers[k.toLowerCase()]; },+ end(b) { this.body = b; this.ended = true; this.writableEnded = true; },+ get headersSent() { return this.ended; },+ };+}++async function callEndpoint(req) {+ const mod = await import('../../api/scene-capture.js');+ const res = mockRes();+ await mod.default(req, res);+ let json = null;+ try { json = JSON.parse(res.body); } catch { /* non-json */ }+ return { res, json };+}++describe('/api/scene-capture endpoint', () => {+ it('rejects a missing video_url with 400', async () => {+ const { res, json } = await callEndpoint(mockReq({ body: {} }));+ expect(res.statusCode).toBe(400);+ expect(json.error).toBe('missing_video_url');+ });++ it('rejects a non-http(s) / private video_url before dispatch', async () => {+ const { res, json } = await callEndpoint(mockReq({ body: { video_url: 'http://169.254.169.254/latest' } }));+ expect(res.statusCode).toBe(400);+ expect(json.error).toBe('invalid_video_url');+ });++ it('degrades to a clean 503 when the worker is not configured', async () => {+ delete process.env.GCP_VIDEO2SCENE_URL;+ delete process.env.GCP_RECONSTRUCTION_KEY;+ const { res, json } = await callEndpoint(mockReq({ body: { video_url: 'https://93.184.216.34/walk.mp4' } }));+ expect(res.statusCode).toBe(503);+ expect(json.error).toBe('unconfigured');+ });++ it('starts a job and returns a job_id when configured', async () => {+ globalThis.fetch = vi.fn(async () =>+ new Response(JSON.stringify({ task_id: 'task-xyz', status: 'queued' }), { status: 202 }),+ );+ const { res, json } = await callEndpoint(mockReq({ body: { video_url: 'https://93.184.216.34/walk.mp4', mode: 'windowed' } }));+ expect(res.statusCode).toBe(202);+ expect(json.job_id).toBeTruthy();+ expect(json.status).toBe('queued');+ expect(json.eta_seconds).toBe(240);+ });++ it('rejects a malformed job id on poll', async () => {+ const { res, json } = await callEndpoint(mockReq({ method: 'GET', url: '/api/scene-capture?job=%20%20' }));+ expect(res.statusCode).toBe(400);+ expect(json.error).toBe('missing_job');+ });+});diff --git a/tests/launcher-trends-endpoint.test.js b/tests/launcher-trends-endpoint.test.jsnew file mode 100644index 000000000..da5743a45--- /dev/null+++ b/tests/launcher-trends-endpoint.test.js@@ -0,0 +1,82 @@+import { describe, it, expect, vi } from 'vitest';++// Mock the thin glue deps so we test the endpoint's COMPOSITION logic (narratives+// + launch feed shaping), not the network/DB beneath it.+vi.mock('../api/_lib/http.js', () => ({+ wrap: (fn) => fn,+ cors: () => false,+ method: () => true,+ rateLimited: (res) => { res._rateLimited = true; },+ json: (res, status, body) => { res._json = { status, body }; return res; },+}));+vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: { publicIp: vi.fn(async () => ({ success: true })) },+ clientIp: () => '1.2.3.4',+}));+vi.mock('../api/_lib/cache.js', () => ({+ cacheGet: vi.fn(async () => null),+ cacheSet: vi.fn(async () => {}),+}));+vi.mock('../api/_lib/launcher-trends.js', () => ({+ PROVIDER_IDS: ['coin_intel', 'trending', 'knowyourmeme', 'googletrends', 'x', 'hackernews', 'reddit', 'wikipedia'],+ rankNarratives: vi.fn(async () => ({+ terms: [+ { term: 'drooling cat', score: 9.1, sources: ['knowyourmeme', 'reddit'], kind: 'meme' },+ { term: 'train dog', score: 4.2, sources: ['x'], kind: 'meme' },+ ],+ top: { term: 'drooling cat', score: 9.1, sources: ['knowyourmeme', 'reddit'], kind: 'meme' },+ providers: ['knowyourmeme', 'reddit', 'x'],+ })),+}));+vi.mock('../api/_lib/db.js', () => ({+ sql: () => Promise.resolve([+ { name: 'Drool Lord', symbol: 'DROOL', mint: 'MINT111', kind: 'trend', trigger_source: 'knowyourmeme', trigger_detail: { top_narrative: 'drooling cat' }, created_at: '2026-06-27T00:00:00Z' },+ ]),+}));++import handler from '../api/launcher/trends.js';+import { rankNarratives } from '../api/_lib/launcher-trends.js';++function fakeRes() { return { setHeader() {}, end() {}, statusCode: 200 }; }++describe('GET /api/launcher/trends', () => {+ it('returns ranked narratives + the autonomous launch feed', async () => {+ const res = fakeRes();+ await handler({ method: 'GET', url: '/api/launcher/trends?network=mainnet&limit=10', headers: {} }, res);++ expect(res._json.status).toBe(200);+ const b = res._json.body;+ expect(b.network).toBe('mainnet');+ expect(b.narratives.count).toBe(2);+ expect(b.narratives.top.term).toBe('drooling cat');+ expect(b.narratives.terms[0]).toMatchObject({ term: 'drooling cat', momentum: 2 });+ expect(b.narratives.providers).toContain('knowyourmeme');+ // launch feed maps trigger_detail.top_narrative → rode+ expect(b.launches[0]).toMatchObject({ symbol: 'DROOL', mint: 'MINT111', rode: 'drooling cat' });+ });++ it('honours launches=0 (narratives only)', async () => {+ const res = fakeRes();+ await handler({ method: 'GET', url: '/api/launcher/trends?launches=0', headers: {} }, res);+ expect(res._json.body.launches).toEqual([]);+ expect(res._json.body.narratives.count).toBe(2);+ });++ it('validates ?sources, drops unknown ids, and forwards a sorted filter', async () => {+ rankNarratives.mockClear();+ const res = fakeRes();+ await handler({ method: 'GET', url: '/api/launcher/trends?sources=knowyourmeme,bogus,googletrends', headers: {} }, res);+ expect(rankNarratives).toHaveBeenCalledWith(+ expect.objectContaining({ sources: ['googletrends', 'knowyourmeme'] }),+ );+ });++ it('omits the sources filter entirely when none are valid (uses defaults)', async () => {+ rankNarratives.mockClear();+ const res = fakeRes();+ await handler({ method: 'GET', url: '/api/launcher/trends?sources=bogus', headers: {} }, res);+ expect(rankNarratives).toHaveBeenCalledWith(+ expect.objectContaining({ sources: undefined }),+ );+ });+});diff --git a/tests/launcher-trends.test.js b/tests/launcher-trends.test.jsindex 2f9a5a7e8..3fa3e0e94 100644--- a/tests/launcher-trends.test.js+++ b/tests/launcher-trends.test.js@@ -1,5 +1,5 @@import { describe, it, expect } from 'vitest';-import { decodeEntities, parseRssItems, normTerm } from '../api/_lib/launcher-trends.js';+import { decodeEntities, parseRssItems, normTerm, parseGoogleTrends, isSensitive } from '../api/_lib/launcher-trends.js';describe('decodeEntities', () => {it('unwraps CDATA', () => {@@ -64,3 +64,55 @@ describe('KYM theme extraction shape', () => {expect(normTerm(m[1].replace(/-/g, ' '))).toBe('chimptopia');});});++describe('parseGoogleTrends', () => {+ const item = (title, traffic, news) => `+ <item>+ <title>${title}</title>+ <ht:approx_traffic>${traffic}</ht:approx_traffic>+ ${(news || []).map((n) => `<ht:news_item><ht:news_item_title>${n}</ht:news_item_title></ht:news_item>`).join('')}+ </item>`;+ const wrap = (items) => `<?xml version="1.0"?><rss xmlns:ht="https://trends.google.com/trending/rss"><channel><title>Daily Search Trends</title>${items}</channel></rss>`;++ it('extracts clean trends as lowercased event themes', () => {+ const rows = parseGoogleTrends(wrap(item('Labubu Craze', '50,000+', ['Labubu dolls sell out worldwide'])));+ expect(rows).toHaveLength(1);+ expect(rows[0]).toMatchObject({ term: 'labubu craze', kind: 'event' });+ expect(rows[0].weight).toBeGreaterThan(0.6);+ expect(rows[0].weight).toBeLessThanOrEqual(1.6);+ });++ it('weights higher traffic above lower traffic', () => {+ const hi = parseGoogleTrends(wrap(item('Big Wave', '2,000,000+', ['Big Wave goes viral'])))[0];+ const lo = parseGoogleTrends(wrap(item('Small Wave', '1,000+', ['Small Wave noticed'])))[0];+ expect(hi.weight).toBeGreaterThan(lo.weight);+ });++ it('drops a trend whose NEWS context is sensitive even when the term is clean', () => {+ // Bare "John Smith" passes normTerm; the news reveals a tragedy → must be dropped.+ const rows = parseGoogleTrends(wrap(item('John Smith', '20,000+', ['John Smith dies in fatal car crash'])));+ expect(rows).toHaveLength(0);+ });++ it('drops sensitive bare terms', () => {+ const rows = parseGoogleTrends(wrap(item('Earthquake', '100,000+', ['Magnitude 7 earthquake hits'])));+ expect(rows).toHaveLength(0);+ });++ it('returns [] for empty / malformed input, never throws', () => {+ expect(parseGoogleTrends('')).toEqual([]);+ expect(parseGoogleTrends(null)).toEqual([]);+ });+});++describe('isSensitive', () => {+ it('catches death/disaster words and naive plurals', () => {+ expect(isSensitive('a deadly shooting')).toBe(true);+ expect(isSensitive('earthquakes today')).toBe(true);+ expect(isSensitive('celebrity dies')).toBe(true);+ });+ it('passes ordinary culture terms', () => {+ expect(isSensitive('drooling cat')).toBe(false);+ expect(isSensitive('labubu craze')).toBe(false);+ });+});diff --git a/tests/marketplace-gallery-data.test.js b/tests/marketplace-gallery-data.test.jsnew file mode 100644index 000000000..161c54abd--- /dev/null+++ b/tests/marketplace-gallery-data.test.js@@ -0,0 +1,197 @@+/**+ * marketplace-gallery-data — unit tests for the Walk-Browse data layer.+ *+ * These pure helpers normalise three different marketplace APIs+ * (/api/marketplace/agents, /api/explore, /api/skills) into ONE listing shape+ * the 3D hall (src/marketplace-gallery.js) and the deep-link router consume. A+ * regression here silently corrupts every plinth — a wrong detail href dead-ends+ * the "View listing" CTA, a mis-formatted price shows "$NaN" floating in the+ * hall, a broken alias map drops shared ?type links to the default tab. Pin the+ * contract.+ */++import { describe, it, expect } from 'vitest';+import {+ PAGE_SIZE,+ FILTERS,+ normalizeFilterKey,+ fmtTokenPrice,+ isPaidToken,+ fmtCount,+ makeRating,+ normalizeAgent,+ normalizeAvatar,+ normalizeSkill,+ interleave,+} from '../src/marketplace-gallery-data.js';++describe('config', () => {+ it('exposes a sane page size and the four canonical filters', () => {+ expect(PAGE_SIZE).toBeGreaterThan(0);+ expect(FILTERS.map((f) => f.key)).toEqual(['all', 'agent', 'avatar', 'skill']);+ });+});++describe('normalizeFilterKey — shared-link ?type alias map', () => {+ it('maps singular and plural forms to the canonical key', () => {+ expect(normalizeFilterKey('skill')).toBe('skill');+ expect(normalizeFilterKey('skills')).toBe('skill');+ expect(normalizeFilterKey('agents')).toBe('agent');+ expect(normalizeFilterKey('avatars')).toBe('avatar');+ expect(normalizeFilterKey('all')).toBe('all');+ });+ it('is case- and whitespace-insensitive', () => {+ expect(normalizeFilterKey(' Skills ')).toBe('skill');+ expect(normalizeFilterKey('AGENT')).toBe('agent');+ });+ it('returns null for unknown / empty so the caller defaults to all', () => {+ expect(normalizeFilterKey('widgets')).toBeNull();+ expect(normalizeFilterKey('')).toBeNull();+ expect(normalizeFilterKey(undefined)).toBeNull();+ expect(normalizeFilterKey(null)).toBeNull();+ });+});++describe('fmtTokenPrice — base-unit integer + mint decimals', () => {+ it('formats whole and sub-dollar amounts', () => {+ expect(fmtTokenPrice({ amount: '1000000', mint_decimals: 6 })).toBe('$1');+ expect(fmtTokenPrice({ amount: '500000', mint_decimals: 6 })).toBe('$0.50');+ expect(fmtTokenPrice({ amount: '2500000000', mint_decimals: 6 })).toBe('$2,500');+ });+ it('defaults to 6 decimals when mint_decimals is absent', () => {+ expect(fmtTokenPrice({ amount: '1000000' })).toBe('$1');+ });+ it('reads missing / zero / unparseable as Free, never "$0" or "$NaN"', () => {+ expect(fmtTokenPrice(null)).toBe('Free');+ expect(fmtTokenPrice({})).toBe('Free');+ expect(fmtTokenPrice({ amount: 0, mint_decimals: 6 })).toBe('Free');+ expect(fmtTokenPrice({ amount: 'xyz', mint_decimals: 6 })).toBe('Free');+ });+});++describe('isPaidToken', () => {+ it('is true only for a positive amount', () => {+ expect(isPaidToken({ amount: '1' })).toBe(true);+ expect(isPaidToken({ amount: 0 })).toBe(false);+ expect(isPaidToken(null)).toBe(false);+ expect(isPaidToken({})).toBe(false);+ });+});++describe('fmtCount — compact human counts', () => {+ it('passes small counts through', () => {+ expect(fmtCount(340)).toBe('340');+ expect(fmtCount(1)).toBe('1');+ });+ it('compacts thousands and millions at the right boundaries', () => {+ expect(fmtCount(1240)).toBe('1.2k');+ expect(fmtCount(1000)).toBe('1k');+ expect(fmtCount(99_900)).toBe('99.9k');+ expect(fmtCount(120_000)).toBe('120k');+ expect(fmtCount(2_300_000)).toBe('2.3M');+ });+ it('returns null for nothing-to-show so the chip is omitted', () => {+ expect(fmtCount(0)).toBeNull();+ expect(fmtCount(-5)).toBeNull();+ expect(fmtCount('nope')).toBeNull();+ });+});++describe('makeRating — social proof gating', () => {+ it('requires at least one rater', () => {+ expect(makeRating(4.7, 0)).toBeNull();+ expect(makeRating(5, 12)).toEqual({ avg: 5, count: 12 });+ });+ it('rounds the average to one decimal', () => {+ expect(makeRating(4.66, 3)).toEqual({ avg: 4.7, count: 3 });+ });+ it('drops zero / unparseable averages', () => {+ expect(makeRating(0, 4)).toBeNull();+ expect(makeRating('x', 4)).toBeNull();+ });+});++describe('normalizers — one listing shape across three APIs', () => {+ it('normalizeAgent maps to the agent detail route and owner count', () => {+ const out = normalizeAgent({+ id: 'a 1/b',+ name: 'Risk Auditor 9',+ description: 'Tracks grants',+ thumbnail_url: 'https://x/y.png',+ price: { amount: '1000000', mint_decimals: 6 },+ category: 'trading',+ rating_avg: 4.5,+ rating_count: 2,+ buyers_total: 1240,+ tags: ['nft-lookup', ' trending ', '', 'a', 'b', 'c'],+ });+ expect(out.type).toBe('agent');+ expect(out.href).toBe('/marketplace/agents/a%201%2Fb'); // encoded, no dead link+ expect(out.price).toBe('$1');+ expect(out.paid).toBe(true);+ expect(out.rating).toEqual({ avg: 4.5, count: 2 });+ expect(out.uses).toEqual({ label: 'owners', count: 1240 });+ expect(out.tags).toEqual(['nft-lookup', 'trending', 'a', 'b']); // trimmed, blanks dropped, capped at 4+ });++ it('normalizeAgent falls back gracefully on a sparse record', () => {+ const out = normalizeAgent({ id: 'x' });+ expect(out.name).toBe('Untitled agent');+ expect(out.price).toBe('Free');+ expect(out.paid).toBe(false);+ expect(out.rating).toBeNull();+ expect(out.uses).toBeNull();+ expect(out.tags).toEqual([]);+ });++ it('normalizeAvatar uses avatarId for id + href and author display name', () => {+ const out = normalizeAvatar({+ avatarId: 'av-9',+ name: 'Nova',+ image: 'https://x/n.png',+ modelCategory: 'humanoid',+ author: { displayName: 'Dana' },+ viewCount: 2_300_000,+ featured: true,+ });+ expect(out.href).toBe('/marketplace/avatars/av-9');+ expect(out.author).toBe('Dana');+ expect(out.uses).toEqual({ label: 'views', count: 2_300_000 });+ expect(out.featured).toBe(true);+ expect(out.category).toBe('humanoid');+ });++ it('normalizeSkill prefers slug for the detail route and prices per call', () => {+ const paid = normalizeSkill({+ slug: 'whale-tracking',+ id: 'uuid-1',+ name: 'Whale Tracking',+ price_per_call_usd: 0.25,+ avg_rating: 5,+ rating_count: 1,+ install_count: 8,+ });+ expect(paid.id).toBe('whale-tracking');+ expect(paid.href).toBe('/marketplace/skills/whale-tracking');+ expect(paid.price).toBe('$0.25/call');+ expect(paid.paid).toBe(true);+ expect(paid.uses).toEqual({ label: 'installs', count: 8 });++ const free = normalizeSkill({ id: 'uuid-2', name: 'Free Skill', price_per_call_usd: 0 });+ expect(free.id).toBe('uuid-2'); // falls back to id when no slug+ expect(free.href).toBe('/marketplace/skills/uuid-2');+ expect(free.price).toBe('Free');+ expect(free.paid).toBe(false);+ });+});++describe('interleave — varied "All" hall', () => {+ it('round-robins across lanes and skips empties', () => {+ expect(interleave([[1, 2, 3], ['a', 'b'], []])).toEqual([1, 'a', 2, 'b', 3]);+ });+ it('handles a single lane and no lanes', () => {+ expect(interleave([[1, 2]])).toEqual([1, 2]);+ expect(interleave([])).toEqual([]);+ expect(interleave(null)).toEqual([]);+ });+});diff --git a/tests/marketplace-gallery.test.js b/tests/marketplace-gallery.test.jsnew file mode 100644index 000000000..da86968d1--- /dev/null+++ b/tests/marketplace-gallery.test.js@@ -0,0 +1,206 @@+import { describe, it, expect } from 'vitest';+import {+ fmtTokenPrice,+ isPaidToken,+ fmtCount,+ makeRating,+ normalizeFilterKey,+ normalizeAgent,+ normalizeAvatar,+ normalizeSkill,+ interleave,+ FILTERS,+ PAGE_SIZE,+} from '../src/marketplace-gallery-data.js';++describe('fmtTokenPrice', () => {+ it('reads missing / zero / unparseable amounts as Free', () => {+ expect(fmtTokenPrice(null)).toBe('Free');+ expect(fmtTokenPrice({})).toBe('Free');+ expect(fmtTokenPrice({ amount: 0, mint_decimals: 6 })).toBe('Free');+ expect(fmtTokenPrice({ amount: 'nope', mint_decimals: 6 })).toBe('Free');+ });++ it('formats sub-$1 amounts to two decimals', () => {+ expect(fmtTokenPrice({ amount: '500000', mint_decimals: 6 })).toBe('$0.50');+ });++ it('formats whole amounts with thousands separators and trimmed decimals', () => {+ expect(fmtTokenPrice({ amount: '1500000', mint_decimals: 6 })).toBe('$1.5');+ expect(fmtTokenPrice({ amount: '1000000000', mint_decimals: 6 })).toBe('$1,000');+ });++ it('defaults to 6 decimals when none provided', () => {+ expect(fmtTokenPrice({ amount: '2000000' })).toBe('$2');+ });+});++describe('isPaidToken', () => {+ it('is true only for a positive on-chain amount', () => {+ expect(isPaidToken({ amount: '1', mint_decimals: 6 })).toBe(true);+ expect(isPaidToken({ amount: 0 })).toBe(false);+ expect(isPaidToken(null)).toBe(false);+ expect(isPaidToken({})).toBe(false);+ });+});++describe('fmtCount', () => {+ it('omits empty counts', () => {+ expect(fmtCount(0)).toBe(null);+ expect(fmtCount(-5)).toBe(null);+ expect(fmtCount('x')).toBe(null);+ });++ it('passes through small counts and compacts large ones', () => {+ expect(fmtCount(340)).toBe('340');+ expect(fmtCount(1240)).toBe('1.2k');+ expect(fmtCount(12000)).toBe('12k');+ expect(fmtCount(150000)).toBe('150k');+ expect(fmtCount(2300000)).toBe('2.3M');+ });+});++describe('makeRating', () => {+ it('requires both a positive average and at least one vote', () => {+ expect(makeRating(0, 10)).toBe(null);+ expect(makeRating(4.5, 0)).toBe(null);+ expect(makeRating(null, 3)).toBe(null);+ });++ it('rounds the average to one decimal and keeps the vote count', () => {+ expect(makeRating(4.84, 12)).toEqual({ avg: 4.8, count: 12 });+ expect(makeRating('4.2', '7')).toEqual({ avg: 4.2, count: 7 });+ });+});++describe('normalizeFilterKey', () => {+ it('maps singular and plural aliases to a canonical key', () => {+ expect(normalizeFilterKey('skill')).toBe('skill');+ expect(normalizeFilterKey('skills')).toBe('skill');+ expect(normalizeFilterKey('Agents')).toBe('agent');+ expect(normalizeFilterKey('AVATAR')).toBe('avatar');+ expect(normalizeFilterKey('all')).toBe('all');+ });++ it('returns null for unknown or empty input', () => {+ expect(normalizeFilterKey('tools')).toBe(null);+ expect(normalizeFilterKey('')).toBe(null);+ expect(normalizeFilterKey(null)).toBe(null);+ expect(normalizeFilterKey(undefined)).toBe(null);+ });+});++describe('normalizeAgent', () => {+ it('maps fields, trust signals, and an encoded detail href', () => {+ const out = normalizeAgent({+ id: 'a 1/b',+ name: 'Trader',+ description: 'Trades',+ thumbnail_url: 'https://x/t.png',+ price: { amount: '5000000', mint_decimals: 6 },+ category: 'finance',+ rating_avg: 4.7,+ rating_count: 9,+ buyers_total: 1200,+ tags: [' defi ', '', 'solana', 'a', 'b', 'c'],+ });+ expect(out.type).toBe('agent');+ expect(out.id).toBe('a 1/b');+ expect(out.price).toBe('$5');+ expect(out.paid).toBe(true);+ expect(out.rating).toEqual({ avg: 4.7, count: 9 });+ expect(out.uses).toEqual({ label: 'owners', count: 1200 });+ expect(out.tags).toEqual(['defi', 'solana', 'a', 'b']); // trimmed, blanks dropped, capped at 4+ expect(out.href).toBe('/marketplace/agents/a%201%2Fb');+ });++ it('falls back to a placeholder name and Free price', () => {+ const out = normalizeAgent({ id: 'x' });+ expect(out.name).toBe('Untitled agent');+ expect(out.price).toBe('Free');+ expect(out.paid).toBe(false);+ expect(out.rating).toBe(null);+ expect(out.uses).toBe(null);+ expect(out.tags).toEqual([]);+ });+});++describe('normalizeAvatar', () => {+ it('maps explore fields including views, featured, and author', () => {+ const out = normalizeAvatar({+ avatarId: 'av9',+ name: 'Nova',+ image: 'https://x/a.png',+ modelCategory: 'humanoid',+ viewCount: 5400,+ featured: true,+ price: { amount: '0', mint_decimals: 6 },+ author: { displayName: 'Mia', handle: 'mia' },+ });+ expect(out.type).toBe('avatar');+ expect(out.price).toBe('Free');+ expect(out.uses).toEqual({ label: 'views', count: 5400 });+ expect(out.featured).toBe(true);+ expect(out.rating).toBe(null);+ expect(out.author).toBe('Mia');+ expect(out.href).toBe('/marketplace/avatars/av9');+ });++ it('falls back to the handle when no display name', () => {+ const out = normalizeAvatar({ avatarId: 'av1', author: { handle: 'solo' } });+ expect(out.author).toBe('solo');+ expect(out.featured).toBe(false);+ });+});++describe('normalizeSkill', () => {+ it('formats a per-call price and maps installs + rating', () => {+ const out = normalizeSkill({+ slug: 'web-search',+ name: 'Web Search',+ description: 'Searches',+ category: 'research',+ price_per_call_usd: 0.01,+ avg_rating: 4.9,+ rating_count: 40,+ install_count: 880,+ author: { display_name: 'Dev' },+ });+ expect(out.type).toBe('skill');+ expect(out.price).toBe('$0.01/call');+ expect(out.paid).toBe(true);+ expect(out.uses).toEqual({ label: 'installs', count: 880 });+ expect(out.rating).toEqual({ avg: 4.9, count: 40 });+ expect(out.author).toBe('Dev');+ expect(out.image).toBe(null);+ expect(out.href).toBe('/marketplace/skills/web-search');+ });++ it('reads a zero price as Free and falls back to id for the href', () => {+ const out = normalizeSkill({ id: 'sk-7', name: 'Free Tool', price_per_call_usd: 0 });+ expect(out.price).toBe('Free');+ expect(out.paid).toBe(false);+ expect(out.href).toBe('/marketplace/skills/sk-7');+ });+});++describe('interleave', () => {+ it('round-robins across lanes so types alternate', () => {+ expect(interleave([['a1', 'a2'], ['b1', 'b2'], ['c1']])).toEqual([+ 'a1', 'b1', 'c1', 'a2', 'b2',+ ]);+ });++ it('skips empty / non-array lanes', () => {+ expect(interleave([[], ['b1', 'b2'], null, undefined])).toEqual(['b1', 'b2']);+ expect(interleave([])).toEqual([]);+ expect(interleave(null)).toEqual([]);+ });+});++describe('module constants', () => {+ it('exposes the four canonical filters and a sane page size', () => {+ expect(FILTERS.map((f) => f.key)).toEqual(['all', 'agent', 'avatar', 'skill']);+ expect(PAGE_SIZE).toBeGreaterThan(0);+ });+});diff --git a/tests/pipeline-summary.test.js b/tests/pipeline-summary.test.jsnew file mode 100644index 000000000..cc53788b4--- /dev/null+++ b/tests/pipeline-summary.test.js@@ -0,0 +1,101 @@+// Contract for the recording-pipeline guidance derivation (api/_lib/pipeline-summary.js).+//+// The endpoint and the /pipeline page both surface `health`, `summary`, and+// `next_action` from this pure function. These tests pin the "what should+// happen next" ladder so a regression can't silently tell an operator (or an+// agent reading /api/pipeline) the wrong move.++import { describe, it, expect } from 'vitest';+import { summarize, MIN_TRAINING_SAMPLES } from '../api/_lib/pipeline-summary.js';++/** Build a full stages object, overriding only what a case cares about. */+function stages(over = {}) {+ return {+ recorder: { state: 'live', mode: 'simulate', feedLive: true },+ intel: { observed_24h: 0, observed_1h: 0, avg_quality: null, smart_money_touched: 0 },+ outcomes: { labeled: 0, graduated: 0, rugged: 0, pumped: 0 },+ oracle: { scored_total: 0, scored_24h: 0, prime: 0, strong: 0, open_actions: 0 },+ reputation: { wallets: 0, smart_money: 0 },+ learning: { sample_size: 0, trained_at: null, weights: [] },+ trading: { strategies_armed: 0, open_positions: 0, snipes_24h: 0, trades_24h: 0 },+ ...over,+ };+}++describe('pipeline summarize() — health', () => {+ it('is idle when the recorder is not live', () => {+ expect(summarize('mainnet', stages({ recorder: { state: 'offline' } })).health).toBe('idle');+ expect(summarize('mainnet', stages({ recorder: { state: 'down' } })).health).toBe('idle');+ });++ it('is recording when the worker is live but no launches in the last hour', () => {+ const r = summarize('mainnet', stages({ recorder: { state: 'live' }, intel: { observed_1h: 0 } }));+ expect(r.health).toBe('recording');+ });++ it('is flowing when the worker is live and launches are arriving', () => {+ const r = summarize('mainnet', stages({ recorder: { state: 'live' }, intel: { observed_1h: 3 } }));+ expect(r.health).toBe('flowing');+ });+});++describe('pipeline summarize() — next_action ladder', () => {+ it('a cold recorder blocks everything → deploy_recorder (with command)', () => {+ for (const state of ['offline', 'down', 'unknown']) {+ const na = summarize('mainnet', stages({ recorder: { state } })).next_action;+ expect(na.step).toBe('deploy_recorder');+ expect(na.command).toBe('npm run deploy:sniper');+ }+ });++ it('a live-but-silent feed → check_feed', () => {+ const na = summarize('mainnet', stages({ recorder: { state: 'degraded' } })).next_action;+ expect(na.step).toBe('check_feed');+ });++ it('recording but under the training threshold → accumulate (no action)', () => {+ const na = summarize('mainnet', stages({+ recorder: { state: 'live' }, intel: { observed_1h: 2 },+ outcomes: { labeled: MIN_TRAINING_SAMPLES - 1 },+ })).next_action;+ expect(na.step).toBe('accumulate');+ expect(na.command).toBeUndefined();+ });++ it('enough labels but no trained weights yet → await_training', () => {+ const na = summarize('mainnet', stages({+ recorder: { state: 'live' }, intel: { observed_1h: 2 },+ outcomes: { labeled: MIN_TRAINING_SAMPLES }, learning: { sample_size: 0 },+ })).next_action;+ expect(na.step).toBe('await_training');+ });++ it('trained but no agents armed → arm_agents (with command)', () => {+ const na = summarize('mainnet', stages({+ recorder: { state: 'live' }, intel: { observed_1h: 2 },+ outcomes: { labeled: 120 }, learning: { sample_size: 120 },+ trading: { strategies_armed: 0 },+ })).next_action;+ expect(na.step).toBe('arm_agents');+ expect(na.command).toBe('POST /api/sniper/strategy');+ });++ it('fully wired loop → running', () => {+ const na = summarize('mainnet', stages({+ recorder: { state: 'live' }, intel: { observed_1h: 5 },+ outcomes: { labeled: 200 }, learning: { sample_size: 200 },+ trading: { strategies_armed: 3, snipes_24h: 4 },+ })).next_action;+ expect(na.step).toBe('running');+ });+});++describe('pipeline summarize() — summary string', () => {+ it('names the network and is non-empty in every health state', () => {+ for (const recorder of [{ state: 'offline' }, { state: 'live' }]) {+ const r = summarize('devnet', stages({ recorder, intel: { observed_1h: recorder.state === 'live' ? 1 : 0 } }));+ expect(r.summary).toContain('devnet');+ expect(r.summary.length).toBeGreaterThan(20);+ }+ });+});diff --git a/tests/sdk/agent-client.test.js b/tests/sdk/agent-client.test.jsindex a7982406b..eed782bd1 100644--- a/tests/sdk/agent-client.test.js+++ b/tests/sdk/agent-client.test.js@@ -197,3 +197,42 @@ describe('AgentClient.invokeSkill', () => {).rejects.toThrow(/paid intent id/);});});++describe('AgentClient.activate', () => {+ it('POSTs to /api/agents/:id/activate with the bearer header and unwraps { data }', async () => {+ const data = { ok: true, signature: 'sig123', explorer: 'https://x/sig123', sol: 0.004, network: 'mainnet' };+ const fetchImpl = makeFetch([res(200, { data })]);+ const client = new AgentClient({ baseUrl: 'https://three.ws', apiKey: 'sk_live', fetch: fetchImpl });++ const out = await client.activate('agent_1');++ expect(out).toEqual(data);+ const call = fetchImpl.calls[0];+ expect(call.url).toBe('https://three.ws/api/agents/agent_1/activate');+ expect(call.opts.method).toBe('POST');+ expect(call.opts.headers.authorization).toBe('Bearer sk_live');+ });++ it('resolves the existing receipt when already live (idempotent)', async () => {+ const data = { ok: true, already: true, signature: 'sigOld', sol: 0.004 };+ const client = new AgentClient({ fetch: makeFetch([res(200, { data })]) });+ expect(await client.activate('agent_1')).toEqual(data);+ });++ it('throws a clear error when activation is not configured (503)', async () => {+ const client = new AgentClient({ fetch: makeFetch([res(503, { error: 'not_configured' })]) });+ await expect(client.activate('agent_1')).rejects.toThrow(/activate failed: 503/);+ });++ it('reads activation status via GET and unwraps { data }', async () => {+ const data = { enabled: true, eligible: true, activated: false, pending: false, grant_sol: 0.004, network: 'mainnet' };+ const fetchImpl = makeFetch([res(200, { data })]);+ const client = new AgentClient({ baseUrl: 'https://three.ws', fetch: fetchImpl });++ const out = await client.getActivationStatus('agent_1');++ expect(out).toEqual(data);+ expect(fetchImpl.calls[0].url).toBe('https://three.ws/api/agents/agent_1/activate');+ expect(fetchImpl.calls[0].opts.method).toBeUndefined(); // GET+ });+});diff --git a/tests/user-launcher.test.js b/tests/user-launcher.test.jsnew file mode 100644index 000000000..c155a90ad--- /dev/null+++ b/tests/user-launcher.test.js@@ -0,0 +1,102 @@+// Unit tests for the per-user Memetic Launcher endpoint's pure logic.+// The handler's I/O (auth, SQL) is exercised separately; here we lock down the+// safety-critical invariants: the dry-run lock, range validation, and clamping.++import { describe, it, expect } from 'vitest';+import { validateAndBuildPatch, shapeConfig, FORCE_DRY_RUN, MODES, KNOWN_SOURCES } from '../api/launcher/me.js';++const baseCur = {+ enabled: false,+ dry_run: true,+ mode: 'hybrid',+ sources: ['coin_intel', 'trending'],+ categories: [],+ target_cadence_seconds: 60,+ max_per_hour: 30,+ network: 'mainnet',+};++describe('user launcher — dry-run lock (safety)', () => {+ it('forces dry_run on even when the client asks to disable it', () => {+ const r = validateAndBuildPatch({ dry_run: false, enabled: true }, baseCur);+ expect(r.ok).toBe(true);+ expect(r.next.dry_run).toBe(true);+ });++ it('shapeConfig never reports armed and always dry_run when locked', () => {+ const shaped = shapeConfig({ ...baseCur, enabled: true, dry_run: false });+ expect(FORCE_DRY_RUN).toBe(true);+ expect(shaped.dry_run).toBe(true);+ expect(shaped.armed).toBe(false);+ });++ it('shapeConfig returns null for a missing row', () => {+ expect(shapeConfig(null)).toBe(null);+ });+});++describe('user launcher — validation', () => {+ it('rejects an unknown mode', () => {+ const r = validateAndBuildPatch({ mode: 'nuke' }, baseCur);+ expect(r.ok).toBe(false);+ expect(r.code).toBe('invalid_mode');+ });++ it('accepts every supported mode', () => {+ for (const mode of MODES) expect(validateAndBuildPatch({ mode }, baseCur).ok).toBe(true);+ });++ it('rejects an unknown network', () => {+ expect(validateAndBuildPatch({ network: 'testnet' }, baseCur).code).toBe('invalid_network');+ });++ it('rejects a source outside the known set', () => {+ const r = validateAndBuildPatch({ sources: ['coin_intel', 'tiktok'] }, baseCur);+ expect(r.ok).toBe(false);+ expect(r.code).toBe('invalid_sources');+ });++ it('accepts the full known source set', () => {+ expect(validateAndBuildPatch({ sources: [...KNOWN_SOURCES] }, baseCur).ok).toBe(true);+ });++ it('rejects non-array categories', () => {+ expect(validateAndBuildPatch({ categories: 'memes' }, baseCur).code).toBe('invalid_categories');+ });++ it('rejects a cadence below the 60s floor', () => {+ expect(validateAndBuildPatch({ target_cadence_seconds: 5 }, baseCur).code).toBe('invalid_cadence');+ });++ it('rejects a max_per_hour above the 60 ceiling', () => {+ expect(validateAndBuildPatch({ max_per_hour: 999 }, baseCur).code).toBe('invalid_max_per_hour');+ });+});++describe('user launcher — clamping + partial patch', () => {+ it('clamps cadence into [60, 86400] and rounds', () => {+ const r = validateAndBuildPatch({ target_cadence_seconds: 90.7 }, baseCur);+ expect(r.ok).toBe(true);+ expect(r.next.target_cadence_seconds).toBe(91);+ });++ it('clamps max_per_hour into [0, 60]', () => {+ // 60 is the ceiling and is accepted; the clamp guards rounding edge cases.+ const r = validateAndBuildPatch({ max_per_hour: 60 }, baseCur);+ expect(r.ok).toBe(true);+ expect(r.next.max_per_hour).toBe(60);+ });++ it('leaves unspecified fields untouched (partial update)', () => {+ const r = validateAndBuildPatch({ enabled: true }, baseCur);+ expect(r.next.mode).toBe('hybrid');+ expect(r.next.network).toBe('mainnet');+ expect(r.next.sources).toEqual(['coin_intel', 'trending']);+ expect(r.next.enabled).toBe(true);+ });++ it('coerces a jsonb-string current value into an array', () => {+ const r = validateAndBuildPatch({ enabled: true }, { ...baseCur, sources: '["x","oracle"]' });+ expect(r.next.sources).toEqual(['x', 'oracle']);+ });+});diff --git a/vercel.json b/vercel.jsonindex a847bd479..6f6251da0 100644--- a/vercel.json+++ b/vercel.json@@ -79,6 +79,9 @@"api/cron/launcher-tick.js": {"maxDuration": 120},+ "api/cron/launcher-claimer.js": {+ "maxDuration": 60+ },"api/cron/avaturn-seed-cron.js": {"maxDuration": 300},@@ -733,6 +736,10 @@"src": "/deployments/?","dest": "/deployments.html"},+ {+ "src": "/launcher/?",+ "dest": "/launcher.html"+ },{"src": "/watchlist/?","dest": "/watchlist.html"@@ -4681,6 +4688,10 @@{"path": "/api/cron/cosmetic-splits-sweep","schedule": "15 * * * *"+ },+ {+ "path": "/api/cron/launcher-claimer",+ "schedule": "*/5 * * * *"}]}diff --git a/vite.config.js b/vite.config.jsindex cbf26aaec..456d609d1 100644--- a/vite.config.js+++ b/vite.config.js@@ -380,6 +380,7 @@ const appConfig = {pulse: resolve(__dirname, 'pages/pulse.html'),deployments: resolve(__dirname, 'pages/deployments.html'),'admin-launcher': resolve(__dirname, 'pages/admin/launcher.html'),+ launcher: resolve(__dirname, 'pages/launcher.html'),'launch-detail': resolve(__dirname, 'pages/launch-detail.html'),watchlist: resolve(__dirname, 'pages/watchlist.html'),leaderboard: resolve(__dirname, 'pages/leaderboard.html'),@@ -845,6 +846,8 @@ support: resolve(__dirname, 'pages/support.html'),'/deployments/': resolve(root, 'pages/deployments.html'),'/admin/launcher': resolve(root, 'pages/admin/launcher.html'),'/admin/launcher/': resolve(root, 'pages/admin/launcher.html'),+ '/launcher': resolve(root, 'pages/launcher.html'),+ '/launcher/': resolve(root, 'pages/launcher.html'),'/clash': resolve(root, 'pages/clash.html'),'/clash/': resolve(root, 'pages/clash.html'),'/watchlist': resolve(root, 'pages/watchlist.html'),diff --git a/workers/agent-screen-worker/config.js b/workers/agent-screen-worker/config.jsindex 1e4fb3646..70a70b104 100644--- a/workers/agent-screen-worker/config.js+++ b/workers/agent-screen-worker/config.js@@ -16,6 +16,9 @@ export function loadConfig() {AGENT_JWT: process.env.AGENT_JWT,PUSH_URL: process.env.PUSH_URL || 'https://three.ws/api/agent-screen-push',TASK_URL: process.env.TASK_URL || 'https://three.ws/api/agent-task',+ // Neutral home the agent rests on while idle (no task queued). Coin-agnostic+ // by design — defaults to the platform home.+ HOME_URL: process.env.HOME_URL || 'https://three.ws',BROWSERBASE_API_KEY,BROWSERBASE_PROJECT_ID,CYCLE_MS: Number(process.env.CYCLE_MS || 30_000),diff --git a/workers/agent-screen-worker/task-runner.js b/workers/agent-screen-worker/task-runner.jsindex d654931bc..4605a84ff 100644--- a/workers/agent-screen-worker/task-runner.js+++ b/workers/agent-screen-worker/task-runner.js@@ -147,17 +147,6 @@ function breakTaskIntoSteps(taskText, taskType) {];}- if (taskType === 'trade') {- return [- { action: 'observe', narration: 'Scanning trending tokens', instruction: 'Look at the trending tokens on this page' },- {- action: 'extract',- narration: 'Reading token data',- instruction: 'Extract the top trending token names, symbols, and market caps visible',- },- ];- }-return [{ action: 'observe', narration: `Looking for: ${taskText}`, instruction: taskText },{@@ -173,84 +162,37 @@ function breakTaskIntoSteps(taskText, taskType) {];}-// ── Autonomous cycle (default: pump.fun scan) ─────────────────────────────────+// ── Autonomous idle cycle ─────────────────────────────────────────────────────+//+// Default behaviour when no user task is queued. Intentionally neutral: the+// agent rests on its three.ws home presence and signals that it is standing by.+// It performs NO market/token discovery and narrates NO third-party assets —+// every real action is user-directed through the queued-task path above.async function runAutonomousCycle({ page, cfg, push }) {- const { agentId } = cfg;+ const { agentId, HOME_URL } = cfg;try {- await push({ agentId, page, activity: 'Navigating to pump.fun…', type: 'activity' });- await page.goto(PUMP_FUN_URL, { waitUntil: 'domcontentloaded', timeout: 30_000 });- await push({ agentId, page, activity: 'Scanning pump.fun for trending tokens', type: 'screenshot' });-- let trending = { tokens: [] };- try {- trending = await page.extract({- instruction: 'Extract the top 5 trending token names, symbols, and market caps visible on this page',- schema: TokenListSchema,- });- } catch (err) {- console.warn('[task] extract failed:', err.message);- }-- const count = trending.tokens?.length ?? 0;- await push({- agentId,- page,- activity:- count > 0- ? `Found ${count} trending token${count !== 1 ? 's' : ''}: ${trending.tokens- .slice(0, 3)- .map((t) => (t.symbol ? `$${t.symbol}` : t.name))- .join(', ')}`- : 'No trending tokens extracted — page may still be loading',- type: 'analysis',- });-- if (trending.tokens.length > 0) {- const pick = trending.tokens[0];- const label = pick.symbol ? `$${pick.symbol}` : pick.name;- await push({- agentId,- page,- activity: `Evaluating ${label} — market cap ${pick.marketCap || 'unknown'}`,- type: 'analysis',- });-- try {- await page.act({ action: `Click on the token named "${pick.name}"` });- await push({ agentId, page, activity: `Opened ${label} detail page`, type: 'screenshot' });-- const DetailSchema = z.object({- price: z.string().optional(),- holders: z.string().optional(),- volume: z.string().optional(),- });- const detail = await page.extract({- instruction: 'Extract price, holder count, and recent transaction volume if visible',- schema: DetailSchema,- });-- const parts = [];- if (detail.price) parts.push(`price ${detail.price}`);- if (detail.holders) parts.push(`${detail.holders} holders`);- if (detail.volume) parts.push(`vol ${detail.volume}`);- if (parts.length) {- await push({ agentId, page, activity: `${label}: ${parts.join(' · ')}`, type: 'trade' });- }- } catch {- await push({ agentId, page, activity: `Could not open token detail page`, type: 'activity' });- }+ // Only (re)navigate home if we've drifted away during a prior task, so the+ // idle loop doesn't reload every cycle and burn bandwidth.+ const onHome = (() => {+ try { return new URL(page.url()).origin === new URL(HOME_URL).origin; }+ catch { return false; }+ })();++ if (!onHome) {+ await push({ agentId, page, activity: 'Returning to three.ws home', type: 'activity' });+ await page.goto(HOME_URL, { waitUntil: 'domcontentloaded', timeout: 30_000 });}await push({agentId,page,- activity: `Cycle complete — checking for new tasks in ${TASK_POLL_MS / 1000}s`,- type: 'activity',+ activity: 'Standing by — send a task to put this agent to work',+ type: 'screenshot',});} catch (err) {- console.error('[task] autonomous cycle error:', err);+ console.error('[task] idle cycle error:', err);await push({ agentId, page: null, activity: `Error: ${err.message}`, type: 'activity' });await sleep(5_000);}diff --git a/workers/model-video2scene/main.py b/workers/model-video2scene/main.pyindex 86c4cf4b9..522a67419 100644--- a/workers/model-video2scene/main.py+++ b/workers/model-video2scene/main.py@@ -206,16 +206,46 @@ def _to_np(x) -> np.ndarray:return np.asarray(x)+def _voxel_downsample(+ pts: np.ndarray, cols: np.ndarray, voxel: float+) -> tuple[np.ndarray, np.ndarray]:+ """Merge points sharing a voxel cell into one averaged, colour-averaged point.++ Far higher quality than blind stride subsampling: it removes the redundant+ overlap where many frames re-observe the same surface, evens out density, and+ suppresses single-frame noise — while preserving the true shape. Deterministic+ (no RNG). ``voxel`` is the cell edge length in world units.+ """+ if voxel <= 0 or pts.shape[0] == 0:+ return pts, cols+ keys = np.floor(pts / voxel).astype(np.int64)+ # Order points by voxel cell, then reduce each contiguous run to its mean.+ order = np.lexsort((keys[:, 2], keys[:, 1], keys[:, 0]))+ keys, pts, cols = keys[order], pts[order], cols[order]+ boundaries = np.any(np.diff(keys, axis=0) != 0, axis=1)+ starts = np.concatenate(([0], np.nonzero(boundaries)[0] + 1))+ ends = np.concatenate((starts[1:], [pts.shape[0]]))+ out_pts = np.empty((starts.shape[0], 3), dtype=np.float32)+ out_cols = np.empty((starts.shape[0], 3), dtype=np.uint8)+ colf = cols.astype(np.float32)+ for i, (s, e) in enumerate(zip(starts, ends)):+ out_pts[i] = pts[s:e].mean(axis=0)+ out_cols[i] = np.clip(colf[s:e].mean(axis=0), 0, 255).astype(np.uint8)+ return out_pts, out_cols++def _fuse_point_cloud(predictions: dict,conf_percentile: float,max_points: int,+ voxel_size: float = 0.0,) -> tuple[np.ndarray, np.ndarray]:"""Flatten per-frame world points + RGB into one coloured cloud.LingBot-Map returns world_points (..., 3) in a shared world frame, an alignedworld_points_conf, and the source images. We drop the low-confidence tail,- colour each surviving point from its pixel, and cap the total at max_points.+ colour each surviving point from its pixel, optionally voxel-downsample to+ de-duplicate overlapping observations, and cap the total at max_points."""pts = _to_np(predictions["world_points"]).reshape(-1, 3)@@ -243,6 +273,10 @@ def _fuse_point_cloud(mask &= conf >= threshpts, cols = pts[mask], cols[mask]+ # Voxel-merge overlapping observations first (quality), then hard-cap.+ if voxel_size > 0:+ pts, cols = _voxel_downsample(pts.astype(np.float32), cols, voxel_size)+if pts.shape[0] > max_points:# Deterministic stride subsample — preserves spatial spread without RNG.idx = np.linspace(0, pts.shape[0] - 1, max_points).astype(np.int64)@@ -311,7 +345,9 @@ def _run(req: "InferRequest", dst_dir: str) -> tuple[bytes, int, int]:)predictions, _ = postprocess(predictions, images.to("cpu"))- pts, cols = _fuse_point_cloud(predictions, req.conf_percentile, req.max_points)+ pts, cols = _fuse_point_cloud(+ predictions, req.conf_percentile, req.max_points, req.voxel_size+ )if pts.shape[0] == 0:raise ValueError("reconstruction produced no points above the confidence floor")return _write_ply(pts, cols), pts.shape[0], frames@@ -378,6 +414,7 @@ class InferRequest(BaseModel):mask_sky: bool = Trueconf_percentile: float = Field(default=30.0, ge=0.0, le=95.0)max_points: int = Field(default=1_500_000, ge=10_000, le=MAX_POINT_BUDGET)+ voxel_size: float = Field(default=0.0, ge=0.0, le=10.0)job_id: str | None = None