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
feat: scene capture pipeline, model worker, and launcher hardening
nirholas9db5831f4534
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 3be488bf0..bb02eade9 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -10,6 +10,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Live Agents** (`/agents-live`) — Mission control — real-time grid of all AI agents with active screen streams. Watch their screens and avatar feeds live.- **On-chain Deployments** (`/deployments`) — A live, cross-chain feed of every agent registered on the ERC-8004 Identity Registry — the moment each registration lands on-chain. Real on-chain registrations only, with chain footprint, 3D-avatar and x402 capability stats.- **Partner Ecosystem** (`/partners`) — three.ws partner ecosystem — AWS, IBM, Google Cloud, Alibaba Cloud, Intel, NVIDIA, Microsoft, Oracle. The cloud and AI platforms powering 3D AI agents at enterprise scale.+- **Recording Pipeline — the data loop, live** (`/pipeline`) — One-glance health of the closed loop that turns every pump.fun launch into a trade signal: the launch recorder, signal intel, ground-truth outcomes, Oracle conviction, the wallet reputation graph, trained weights, and the agents trading on the result — every stage, in real time.- **three.ws Joins the Alibaba Cloud Partner Network** (`/blog/three-ws-alibaba-cloud-partnership`) — three.ws is now an Alibaba Cloud Partner, bringing Qwen foundation models and Asia-Pacific cloud infrastructure to the three.ws 3D AI agent platform.- **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]`- **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]`diff --git a/api/_lib/circulation.js b/api/_lib/circulation.jsindex c6b4f53ac..8e0fd8b26 100644--- a/api/_lib/circulation.js+++ b/api/_lib/circulation.js@@ -33,6 +33,7 @@ import { CHAIN_BY_ID } from './erc8004-chains.js';import { publicUrl as r2PublicUrl } from './r2.js';import { pinToIPFS } from './ipfs-pin.js';import { confirmSkillPurchase, resolvePayoutAddress } from './purchase-confirm.js';+import { resolveMarketplaceFee } from './marketplace-platform-fee.js';import { submitProtected } from './execution-engine.js';import { insertNotification } from './notify.js';import { invalidateSkillPriceCache } from './skill-price-cache.js';@@ -501,7 +502,12 @@ async function ensureThree(ctx, agent, needAtomic) {// to `toAddress`, tagging it with a Solana-Pay `referenceKey` so confirm/validate// can find it on-chain. Buyer pays the seller-ATA rent idempotently. Returns the// confirmed signature.-async function transferThreeWithReference(conn, fromKp, toAddress, atomic, referenceKey, network) {+// Transfer $THREE to a recipient, tagging the leg with a Solana-Pay reference so+// confirmSkillPurchase can find it. When `feeLeg` is supplied ({ wallet, atomics }),+// a SECOND transferChecked routes the platform fee to the treasury in the SAME+// transaction — the exact split confirmSkillPurchase verifies. `atomic` is the+// CREATOR leg (price − fee); pass the full price with no feeLeg for a plain transfer.+async function transferThreeWithReference(conn, fromKp, toAddress, atomic, referenceKey, network, feeLeg = null) {const { PublicKey } = await import('@solana/web3.js');const {getAssociatedTokenAddressSync,@@ -525,6 +531,16 @@ async function transferThreeWithReference(conn, fromKp, toAddress, atomic, refercreateAssociatedTokenAccountIdempotentInstruction(fromKp.publicKey, toAta, recipKey, mintKey),transferIx,];++ if (feeLeg && feeLeg.atomics > 0n && feeLeg.wallet) {+ const feeKey = new PublicKey(feeLeg.wallet);+ const feeAta = getAssociatedTokenAddressSync(mintKey, feeKey);+ ixs.push(createAssociatedTokenAccountIdempotentInstruction(fromKp.publicKey, feeAta, feeKey, mintKey));+ ixs.push(createTransferCheckedInstruction(+ fromAta, mintKey, feeAta, fromKp.publicKey, feeLeg.atomics, mintInfo.decimals,+ ));+ }+const { signature } = await submitProtected({ network, connection: conn, payer: fromKp, instructions: ixs });return signature;}@@ -847,24 +863,47 @@ async function actionBuySkill(ctx) {const recipient = await resolvePayoutAddress(listing.agent_id, 'solana').catch(() => null);if (!recipient) throw new Skip('seller payout wallet missing');+ // Platform fee — the same take-rate the real /marketplace purchase path charges,+ // so the demo loop validates true unit economics. When the fee is OFF (default)+ // resolveMarketplaceFee returns 0 and this degrades to a plain full-price transfer+ // (today's behaviour, no risk). When ON, the buyer's single tx splits creator-net+ // to the seller and the fee to the treasury — exactly what confirmSkillPurchase+ // verifies — and the fee is persisted so the Pulse take-rate reads real on-chain fees.+ let feeAtomics = 0n;+ let feeWallet = null;+ try {+ const fee = await resolveMarketplaceFee({ grossAtomics: amountAtomic });+ if (fee?.feeAtomics > 0n && fee.recipient && fee.feeAtomics < amountAtomic) {+ feeAtomics = fee.feeAtomics;+ feeWallet = fee.recipient.toBase58();+ }+ } catch { /* fee is best-effort; a resolution miss never blocks the sale */ }+ const creatorAtomic = amountAtomic - feeAtomics;+const { Keypair } = await import('@solana/web3.js');const referenceKp = Keypair.generate();const reference = referenceKp.publicKey.toBase58();const [pur] = await sql`insert into skill_purchases- (user_id, agent_id, skill, status, reference, amount, currency_mint, chain, expires_at, kind)+ (user_id, agent_id, skill, status, reference, amount, currency_mint, chain, expires_at, kind,+ platform_fee_amount, platform_fee_wallet)values(${buyer.userId}, ${listing.agent_id}, ${listing.skill}, 'pending', ${reference},- ${listing.amount}, ${THREE_MINT()}, 'solana', now() + interval '15 minutes', 'purchase')- returning id, user_id, agent_id, skill, status, amount, currency_mint, chain, reference, expires_at+ ${listing.amount}, ${THREE_MINT()}, 'solana', now() + interval '15 minutes', 'purchase',+ ${feeAtomics.toString()}, ${feeWallet})+ returning id, user_id, agent_id, skill, status, amount, currency_mint, chain, reference, expires_at,+ platform_fee_amount, platform_fee_wallet`;pur.mint_decimals = THREE_DECIMALS;const buyerKp = await senderKeypair(buyer, 'circulation_skill_purchase');let txSig;try {- txSig = await transferThreeWithReference(conn, buyerKp, recipient, amountAtomic, referenceKp.publicKey, network);+ txSig = await transferThreeWithReference(+ conn, buyerKp, recipient, creatorAtomic, referenceKp.publicKey, network,+ feeAtomics > 0n ? { wallet: feeWallet, atomics: feeAtomics } : null,+ );} catch (e) {await sql`update skill_purchases set status = 'failed' where id = ${pur.id} and status = 'pending'`.catch(() => {});throw new Skip(`skill payment failed: ${e?.message?.slice(0, 160)}`);@@ -1204,19 +1243,24 @@ async function planActions(cfg, poolSize) {where ap.is_active = true and ap.currency_mint = ${THREE_MINT()} and ap.item_type = 'avatar'and exists (select 1 from agent_identities ai where ai.user_id = ap.owner_user_id and (ai.meta->>'circulation') = 'true')`;- if (listedSkillCount < poolSize * 2) plan.push('list_skill');+ // Keep marketplace inventory ahead of demand — buy_skill is now the dominant+ // action, so each agent should average ~3 active listings so a buyer can always+ // find a fresh skill it doesn't already own.+ if (listedSkillCount < poolSize * 3) plan.push('list_skill');if (listedAssetCount < Math.floor(poolSize / 2)) plan.push('list_asset');- // Fill the remaining budget with light actions — including real marketplace- // purchases, trials, and asset buys alongside the p2p tip/pay/trade/review mix.+ // Fill the remaining budget with light actions. Weighted HARD toward real+ // marketplace purchases (value delivered + take-rate earned) — the honest signal+ // we want to grow — and away from the bare p2p `payment` transfer, which moves+ // SOL but delivers nothing and only padded the x402 counter.const weighted = [- ['tip', 26],- ['buy_skill', 22],- ['payment', 12],+ ['buy_skill', 34],+ ['tip', 18],['trade', 12],- ['trial', 10],+ ['trial', 12],['buy_asset', 8],- ['review', 10],+ ['review', 8],+ ['payment', 6],];const total = weighted.reduce((s, [, w]) => s + w, 0);while (plan.length < cfg.actionsPerTick) {diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex 561f3c28d..7cc139953 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -343,6 +343,13 @@ export const limits = {getLimiter('vanity:gallery:read:ip', { limit: 240, window: '5 m' }).limit(ip),mcpUser: (userId) => getLimiter('mcp:user', { limit: 1200, window: '1 m' }).limit(userId),mcpIp: (ip) => getLimiter('mcp:ip', { limit: 600, window: '1 m' }).limit(ip),+ // Generic per-IP bucket for authenticated app endpoints (agent screen feed,+ // task queue, etc.). Callers pass an override to size the bucket to their+ // traffic shape — a screenshot push stream needs hundreds/min, a roster poll+ // only a handful. getLimiter keys its cache by name+limit+window, so each+ // distinct override gets its own isolated bucket under the rl:api:ip prefix.+ apiIp: (ip, opts = {}) =>+ getLimiter('api:ip', { limit: 120, window: '1 m', ...opts }).limit(ip),// Free, unauthenticated 3D Studio (api/mcp-studio.js) abuse protection. The// studio runs generation operator-funded for anonymous ChatGPT users, so each// generation call costs the platform real GPU/provider spend. These are thediff --git a/api/_providers/gcp.js b/api/_providers/gcp.jsindex 9f91992d8..1660ae2fa 100644--- a/api/_providers/gcp.js+++ b/api/_providers/gcp.js@@ -19,6 +19,9 @@// segment → GCP_SEGMENT_URL (workers/segment)// sketch → GCP_TRIPOSG_URL (workers/model-triposg, scribble mode)// rerig → GCP_RECONSTRUCTION_URL (avatar-pipeline-controller, /rig endpoint)+// video2scene → GCP_VIDEO2SCENE_URL (workers/model-video2scene, LingBot-Map)+// Streaming video → 3D point cloud. Standard /infer + /tasks/:id+// shape; the result is a .ply point cloud, not a GLB mesh.//// All workers share the same bearer secret (GCP_RECONSTRUCTION_KEY).// Each worker exposes the same task shape:@@ -81,6 +84,10 @@ function serviceUrlForMode(mode) {return readEnv('MODEL_TRELLIS_URL');case 'text2motion':return readEnv('GCP_TEXT2MOTION_URL');+ case 'video2scene':+ // Streaming video → 3D point-cloud worker (workers/model-video2scene,+ // LingBot-Map). Standard /infer + /tasks/:id task shape; result is a PLY.+ return readEnv('GCP_VIDEO2SCENE_URL');case 'rerig':// Rigging is handled by the pipeline controller via its /rig endpoint.return readEnv('GCP_RECONSTRUCTION_URL');@@ -240,6 +247,31 @@ function buildWorkerRequest(request) {};}+ if (mode === 'video2scene') {+ // Streaming video → 3D point cloud (workers/model-video2scene, LingBot-Map).+ // The source is a public video URL; an `images` array of frames is the+ // alternate input. Reconstruction params (sampling/quality) ride in `params`+ // and are forwarded only when set so the worker's defaults stand otherwise.+ const body = {};+ if (Array.isArray(params?.images) && params.images.length) {+ body.images = params.images;+ } else {+ body.video_url = sourceUrl;+ }+ for (const key of [+ 'mode', 'fps', 'keyframe_interval', 'num_scale_frames',+ 'window_size', 'overlap_size', 'conf_percentile', 'max_points',+ ]) {+ if (params?.[key] !== undefined && params[key] !== null) body[key] = params[key];+ }+ if (params?.mask_sky !== undefined) body.mask_sky = Boolean(params.mask_sky);+ return {+ path: '/infer',+ resultKey: 'result_gcs_url',+ body,+ };+ }+if (mode === 'rerig') {return {path: '/rig',@@ -282,6 +314,7 @@ const MODE_ETA = {sketch: 45,text2motion: 30,rerig: 45,+ video2scene: 240,};// `reconstructUrl` overrides where `reconstruct` jobs go — the forge Hunyuan3D@@ -431,6 +464,13 @@ export function createRegenProvider({ reconstructUrl } = {}) {result.resultClipUrl = url;if (typeof data.frames === 'number') result.frames = data.frames;if (typeof data.fps === 'number') result.fps = data.fps;+ } else if (mode === 'video2scene') {+ // The result is a .ply point cloud, not a GLB mesh. Surface the+ // reconstruction telemetry so the client can show point/frame counts.+ result.resultPointCloudUrl = url;+ if (typeof data.num_points === 'number') result.numPoints = data.num_points;+ if (typeof data.frames === 'number') result.frames = data.frames;+ if (typeof data.bytes === 'number') result.bytes = data.bytes;} else {result.resultGlbUrl = url;}diff --git a/api/admin/launcher.js b/api/admin/launcher.jsindex 5478bed07..56a296842 100644--- a/api/admin/launcher.js+++ b/api/admin/launcher.js@@ -17,6 +17,7 @@ import { cors, json, error, method, readJson, wrap } from '../_lib/http.js';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';function isCronAuth(req) {const auth = req.headers.authorization || '';@@ -27,6 +28,13 @@ function isCronAuth(req) {const MODES = ['off', 'trend', 'meme', 'random', 'hybrid'];const KNOWN_SOURCES = ['coin_intel', 'trending', 'x', 'oracle', 'knowyourmeme', 'hackernews', 'reddit', 'wikipedia'];+// 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 ensureGlobalRow() {await sql`insert into launcher_config (scope, enabled, dry_run, mode)@@ -56,7 +64,7 @@ async function getState(res) {const [recent, stats, queue, master] = await Promise.all([sql`- select id, agent_id, kind, trigger_source, name, symbol, mint, network,+ select id, agent_id, kind, trigger_source, trigger_detail, name, symbol, mint, network,sol_spent, status, dry_run, tx_signature, error, created_atfrom launcher_runswhere scope = 'global'@@ -80,6 +88,18 @@ async function getState(res) {const spentToday = await dailySpentSol('global', null).catch(() => 0);+ // 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+ // admin refresh) and never throws — degrades to null if intelligence is dark.+ 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: config || null,console: recent,@@ -89,6 +109,9 @@ async function getState(res) {},queue_enabled: queue[0]?.enabled ?? 0,master_balance_sol: master,+ narratives: narratives+ ? { terms: narratives.terms || [], top: narratives.top || null, providers: narratives.providers || [] }+ : null,armed: !!(config?.enabled && !config?.dry_run && !config?.paused),});}diff --git a/api/agent-screen-active.js b/api/agent-screen-active.jsindex 49d6bb8bc..1757c70f5 100644--- a/api/agent-screen-active.js+++ b/api/agent-screen-active.js@@ -43,11 +43,15 @@ export default async function handleAgentScreenActive(req, res) {// absent so cold starts don't error.let agentIds = [];try {- // ZRANGEBYSCORE on active set — agents that pushed a frame in the last 120s+ // ZRANGE … BYSCORE on the active set — agents that pushed a frame in the+ // last 120s. (@upstash/redis exposes range-by-score as zrange with the+ // byScore option, not a zrangebyscore method.)const now = Date.now();const minScore = now - 120_000;- const raw = await r.zrangebyscore('agent:screen:active', minScore, now, {- limit: { offset: 0, count: MAX_DESKS },+ const raw = await r.zrange('agent:screen:active', minScore, now, {+ byScore: true,+ offset: 0,+ count: MAX_DESKS,});agentIds = Array.isArray(raw) ? raw.slice(0, MAX_DESKS) : [];} catch {diff --git a/api/pipeline.js b/api/pipeline.jsnew file mode 100644index 000000000..e0ead3688--- /dev/null+++ b/api/pipeline.js@@ -0,0 +1,233 @@+// @ts-check+/**+ * Recording pipeline — one-call health of the whole data→signal→trade loop.+ *+ * GET /api/pipeline?network=mainnet+ *+ * The platform's edge is a closed feedback loop. A long-lived worker+ * (workers/agent-sniper) sits on the pump.fun new-mint feed and records every+ * launch's first-90s signals; cron jobs then score conviction, fold a wallet+ * reputation graph, label outcomes, and train per-signal weights; armed agents+ * trade on the result. Each link lives in a different table, so "is the loop+ * actually running?" otherwise takes six queries across six surfaces.+ *+ * This endpoint answers it in one round-trip. Every stage is queried+ * independently and degrades on its own — a table that doesn't exist yet+ * (fresh DB) or a worker that has never booted reports an honest zero/offline+ * state rather than failing the whole response. The frontend (/pipeline)+ * renders this as a live flow: all-dark until the recorder boots, then lighting+ * up stage by stage as data flows downstream.+ *+ * Public + IP rate-limited — pipeline health carries no secrets and the point+ * of a status surface is that anyone can see whether the platform is alive.+ */++import { cors, json, method, wrap, rateLimited } from './_lib/http.js';+import { limits, clientIp } from './_lib/rate-limit.js';+import { sql } from './_lib/db.js';++const WORKER = 'agent-sniper';+// 2× the 30s heartbeat cadence + slack: one skipped beat under load must not+// flap the recorder between "live" and "down".+const HEARTBEAT_FRESH_MS = 90_000;+// Public spend categories whose 24h counts the loop produces (mirror pulse.js).+const SNIPE = 'snipe';+const TRADE = 'trade';++/** Derive the recorder's operational truth from its heartbeat row. */+function recorderState(beat) {+ if (!beat) return { state: 'offline', reason: 'never started' };+ const lastBeatMs = beat.last_beat_at ? new Date(beat.last_beat_at).getTime() : 0;+ const ageMs = lastBeatMs ? Date.now() - lastBeatMs : null;+ const alive = ageMs != null && ageMs < HEARTBEAT_FRESH_MS;+ const meta = beat.meta && typeof beat.meta === 'object' ? beat.meta : {};+ const feedLive = alive && meta.feedConnected === true;+ const watchdogMs = Number(meta.feedWatchdogMs) || 180_000;+ const feedSilent = alive && Number(meta.lastEventAgeMs) > watchdogMs;+ const state = !alive ? 'down' : feedSilent || !feedLive ? 'degraded' : 'live';+ return {+ state,+ mode: beat.mode || meta.mode || 'unknown',+ network: meta.network || null,+ feedLive,+ feedSilent: !!feedSilent,+ heartbeatAgeMs: ageMs,+ lastEventAgeMs: meta.lastEventAgeMs ?? null,+ reconnects: meta.reconnects ?? null,+ errors: meta.errors ?? null,+ lastError: meta.lastError ?? null,+ intel: meta.intel ?? null,+ bootAt: meta.bootAt ?? null,+ };+}++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.mcpIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const url = new URL(req.url, 'http://x');+ const network = url.searchParams.get('network') === 'devnet' ? 'devnet' : 'mainnet';++ // Each stage resolves independently: a missing table or a cold worker is a+ // zero/offline state for that stage, never a 500 for the whole loop.+ const safe = async (fn, fallback) => {+ try {+ return await fn();+ } catch {+ return fallback;+ }+ };++ const [recorder, intel, outcomes, oracle, reputation, learning, trading] = await Promise.all([+ // 1 — Recorder: is the always-on worker alive and its feed live?+ safe(async () => {+ const [beat] = await sql`+ SELECT mode, last_beat_at, meta FROM bot_heartbeat WHERE worker = ${WORKER} LIMIT 1`;+ return recorderState(beat);+ }, { state: 'unknown', reason: 'status store unreachable' }),++ // 2 — Intel: launches observed + signal-quality distribution.+ safe(async () => {+ const [r] = await sql`+ SELECT+ count(*)::int AS total,+ count(*) filter (where first_seen_at > now() - interval '24 hours')::int AS observed_24h,+ count(*) filter (where first_seen_at > now() - interval '1 hour')::int AS observed_1h,+ round(avg(quality_score) filter (where quality_score is not null+ and first_seen_at > now() - interval '24 hours'))::int AS avg_quality,+ count(*) filter (where quality_score >= 70+ and first_seen_at > now() - interval '24 hours')::int AS healthy,+ count(*) filter (where quality_score >= 40 and quality_score < 70+ and first_seen_at > now() - interval '24 hours')::int AS mixed,+ count(*) filter (where quality_score < 40+ and first_seen_at > now() - interval '24 hours')::int AS risky,+ count(*) filter (where smart_money_count > 0+ and first_seen_at > now() - interval '24 hours')::int AS smart_money_touched+ FROM pump_coin_intel WHERE network = ${network}`;+ return {+ total: r?.total ?? 0,+ observed_24h: r?.observed_24h ?? 0,+ observed_1h: r?.observed_1h ?? 0,+ avg_quality: r?.avg_quality ?? null,+ healthy: r?.healthy ?? 0,+ mixed: r?.mixed ?? 0,+ risky: r?.risky ?? 0,+ smart_money_touched: r?.smart_money_touched ?? 0,+ };+ }, { total: 0, observed_24h: 0, observed_1h: 0, avg_quality: null, healthy: 0, mixed: 0, risky: 0, smart_money_touched: 0 }),++ // 3 — Outcomes: ground-truth labels folded back in (the learning fuel).+ safe(async () => {+ const [r] = await sql`+ SELECT+ count(*)::int AS labeled,+ count(*) filter (where graduated)::int AS graduated,+ count(*) filter (where rugged)::int AS rugged,+ count(*) filter (where outcome = 'pumped')::int AS pumped,+ count(*) filter (where labeled_at > now() - interval '24 hours')::int AS labeled_24h+ FROM pump_coin_outcomes o+ JOIN pump_coin_intel i ON i.mint = o.mint AND i.network = ${network}`;+ return {+ labeled: r?.labeled ?? 0,+ graduated: r?.graduated ?? 0,+ rugged: r?.rugged ?? 0,+ pumped: r?.pumped ?? 0,+ labeled_24h: r?.labeled_24h ?? 0,+ };+ }, { labeled: 0, graduated: 0, rugged: 0, pumped: 0, labeled_24h: 0 }),++ // 4 — Oracle: conviction scoring throughput + tier distribution.+ safe(async () => {+ const [c] = await sql`+ SELECT+ count(*)::int AS scored_total,+ count(*) filter (where scored_at >= now() - interval '24 hours')::int AS scored_24h,+ count(*) filter (where tier = 'prime')::int AS prime,+ count(*) filter (where tier = 'strong')::int AS strong+ FROM oracle_conviction WHERE network = ${network}`;+ const [a] = await sql`+ SELECT count(*)::int AS open_actions FROM oracle_watch_actions+ WHERE network = ${network} AND outcome = 'open'`;+ return {+ scored_total: c?.scored_total ?? 0,+ scored_24h: c?.scored_24h ?? 0,+ prime: c?.prime ?? 0,+ strong: c?.strong ?? 0,+ open_actions: a?.open_actions ?? 0,+ };+ }, { scored_total: 0, scored_24h: 0, prime: 0, strong: 0, open_actions: 0 }),++ // 5 — Reputation graph: wallets with a folded track record.+ safe(async () => {+ const [r] = await sql`+ SELECT+ count(*)::int AS wallets,+ count(*) filter (where label = 'smart_money')::int AS smart_money+ FROM wallet_reputation WHERE network = ${network}`;+ return { wallets: r?.wallets ?? 0, smart_money: r?.smart_money ?? 0 };+ }, { wallets: 0, smart_money: 0 }),++ // 6 — Learning: latest trained per-signal weights (top by |correlation|).+ safe(async () => {+ const [w] = await sql`+ SELECT weights, sample_size, trained_at FROM pump_intel_weights+ WHERE network = ${network} ORDER BY trained_at DESC LIMIT 1`;+ let top = [];+ if (w?.weights && typeof w.weights === 'object') {+ top = Object.entries(w.weights)+ .filter(([, v]) => Number.isFinite(Number(v)))+ .map(([signal, v]) => ({ signal, weight: Number(v) }))+ .sort((a, b) => Math.abs(b.weight) - Math.abs(a.weight))+ .slice(0, 8);+ }+ return { sample_size: w?.sample_size ?? 0, trained_at: w?.trained_at ?? null, weights: top };+ }, { sample_size: 0, trained_at: null, weights: [] }),++ // 7 — Trading: armed strategies, open positions, and 24h confirmed spend.+ safe(async () => {+ const [s] = await sql`+ SELECT count(*)::int AS armed FROM agent_sniper_strategies+ WHERE enabled AND NOT kill_switch AND network = ${network}`;+ const [p] = await sql`+ SELECT count(*)::int AS open FROM agent_sniper_positions+ WHERE status IN ('opening','open','closing') AND network = ${network}`;+ const [e] = await sql`+ SELECT+ count(*) filter (where category = ${SNIPE})::int AS snipes_24h,+ count(*) filter (where category = ${TRADE})::int AS trades_24h+ FROM agent_custody_events+ WHERE network = ${network} AND event_type = 'spend'+ AND status IN ('ok','confirmed')+ AND created_at > now() - interval '24 hours'`;+ return {+ strategies_armed: s?.armed ?? 0,+ open_positions: p?.open ?? 0,+ snipes_24h: e?.snipes_24h ?? 0,+ trades_24h: e?.trades_24h ?? 0,+ };+ }, { 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';++ return json(+ res,+ 200,+ {+ ok: true,+ network,+ health,+ stages: { recorder, intel, outcomes, oracle, reputation, learning, trading },+ t: Date.now(),+ },+ // Heartbeat + crons refresh on the order of seconds-to-minutes; a short+ // shared cache absorbs page-poll bursts without staling the answer.+ { 'cache-control': 'public, max-age=8' },+ );+});diff --git a/api/pulse.js b/api/pulse.jsindex 8ac2e5464..c141a577c 100644--- a/api/pulse.js+++ b/api/pulse.js@@ -563,7 +563,8 @@ async function handleMarketplace(network) {COALESCE(SUM(sp.amount) FILTER (WHERE sp.status = 'confirmed'), 0)::text AS gmv_atomic,COUNT(DISTINCT sp.user_id) FILTER (WHERE sp.status = 'confirmed')::int AS buyers,COUNT(DISTINCT sp.agent_id) FILTER (WHERE sp.status = 'confirmed')::int AS sellers,- COUNT(DISTINCT (sp.user_id, sp.agent_id)) FILTER (WHERE sp.status = 'confirmed')::int AS pairs+ COUNT(DISTINCT (sp.user_id, sp.agent_id)) FILTER (WHERE sp.status = 'confirmed')::int AS pairs,+ COALESCE(SUM(sp.platform_fee_amount) FILTER (WHERE sp.status = 'confirmed'), 0)::text AS fee_atomicFROM skill_purchases spJOIN agent_identities ai ON ai.id = sp.agent_id AND ${pubAgent}WHERE sp.currency_mint = ${THREE_MINT} AND sp.chain = 'solana'@@ -571,6 +572,9 @@ async function handleMarketplace(network) {`;const purchases = Number(r?.purchases || 0);const gmv = threeFromAtomic(r?.gmv_atomic);+ // Take-rate is the fee ACTUALLY charged on-chain (persisted per row by the+ // purchase splitter), never a GMV × rate estimate — so the number is real+ // even when some purchases predate the fee or skipped it.return {purchases,trials: Number(r?.trials || 0),@@ -579,7 +583,7 @@ async function handleMarketplace(network) {sellers: Number(r?.sellers || 0),pairs: Number(r?.pairs || 0),avg_ticket_three: purchases > 0 ? gmv / purchases : 0,- take_rate_three: feeBps > 0 ? (gmv * feeBps) / 10_000 : 0,+ take_rate_three: threeFromAtomic(r?.fee_atomic),};};@@ -701,6 +705,162 @@ async function handleMarketplace(network) {};}+// ── trading viability dashboard ────────────────────────────────────────────────+// The numbers that answer "is funded agent trading actually happening, what does it+// cost, and is it making money?" Activity + cost come from agent_custody_events+// (category='trade' — the exact source the headline Trades counter reconciles with,+// so the panel can never drift from it). Realized P&L comes from CLOSED positions in+// the strategy + sniper position tables, where exit-minus-entry is computed against+// real fills. Heartbeat buys that never close show up as cost with no P&L — which is+// the honest story: profitability lives in positions that round-trip, not in volume.+async function handleTrading(network) {+ const pubAgent = sql`ai.deleted_at IS NULL AND ai.is_public = true+ AND COALESCE((ai.meta->>'pulse_opt_out')::boolean, false) = false`;++ // One windowed aggregate over the custody ledger, reused for 24h + 7d. Buys carry+ // SOL out in amount_lamports (asset='SOL'); sells carry only token base units, so+ // "SOL deployed" = SUM(amount_lamports) is exactly the SOL spent acquiring coins.+ const windowAgg = async (interval) => {+ const [r] = await sql`+ SELECT+ COUNT(*)::int AS trades,+ COUNT(*) FILTER (WHERE ce.amount_lamports IS NOT NULL)::int AS buys,+ COUNT(*) FILTER (WHERE ce.amount_lamports IS NULL)::int AS sells,+ COALESCE(SUM(ce.amount_lamports), 0)::text AS deployed_lamports,+ COALESCE(SUM(ce.usd), 0)::float8 AS deployed_usd,+ COUNT(DISTINCT ce.agent_id)::int AS traders+ FROM agent_custody_events ce+ JOIN agent_identities ai ON ai.id = ce.agent_id AND ${pubAgent}+ WHERE ce.network = ${network}+ AND ce.event_type = 'spend' AND ce.category = 'trade'+ AND ce.status IN ('ok', 'confirmed')+ AND ce.created_at > now() - ${interval}::interval+ `;+ const trades = Number(r?.trades || 0);+ const buys = Number(r?.buys || 0);+ const deployedSol = Number(r?.deployed_lamports || 0) / 1e9;+ return {+ trades,+ buys,+ sells: Number(r?.sells || 0),+ deployed_sol: deployedSol,+ deployed_usd: Number(r?.deployed_usd || 0),+ traders: Number(r?.traders || 0),+ avg_trade_sol: buys > 0 ? deployedSol / buys : 0,+ };+ };++ // Realized P&L over 7d from CLOSED positions across both real position tables.+ // `realized_pnl_lamports` is signed (exit − entry); a win is strictly positive.+ const pnlPromise = sql`+ WITH closed AS (+ SELECT sp.realized_pnl_lamports AS pnl+ FROM agent_strategy_positions sp+ JOIN agent_identities ai ON ai.id = sp.agent_id AND ${pubAgent}+ WHERE sp.network = ${network} AND sp.status = 'closed'+ AND sp.realized_pnl_lamports IS NOT NULL+ AND sp.closed_at > now() - interval '7 days'+ UNION ALL+ SELECT snp.realized_pnl_lamports AS pnl+ FROM agent_sniper_positions snp+ JOIN agent_identities ai ON ai.id = snp.agent_id AND ${pubAgent}+ WHERE snp.network = ${network} AND snp.status = 'closed'+ AND snp.realized_pnl_lamports IS NOT NULL+ AND snp.closed_at > now() - interval '7 days'+ )+ SELECT COUNT(*)::int AS closed_count,+ COUNT(*) FILTER (WHERE pnl > 0)::int AS wins,+ COALESCE(SUM(pnl), 0)::text AS net_lamports+ FROM closed+ `;++ // Top trading agents (7d) by trade count, then SOL deployed — the wallets actually+ // putting capital to work. Same public-agent gate as every other rail.+ const topTradersPromise = sql`+ SELECT ai.id AS agent_id, ai.name AS agent_name,+ av.thumbnail_key AS thumb_key, av.visibility AS avatar_vis,+ ai.meta->>'solana_address' AS agent_addr,+ COUNT(*)::int AS trades,+ COALESCE(SUM(ce.amount_lamports), 0)::text AS deployed_lamports+ FROM agent_custody_events ce+ JOIN agent_identities ai ON ai.id = ce.agent_id AND ${pubAgent}+ LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL+ WHERE ce.network = ${network}+ AND ce.event_type = 'spend' AND ce.category = 'trade'+ AND ce.status IN ('ok', 'confirmed')+ AND ce.created_at > now() - interval '7 days'+ GROUP BY ai.id, ai.name, av.thumbnail_key, av.visibility, ai.meta->>'solana_address'+ ORDER BY COUNT(*) DESC, SUM(ce.amount_lamports) DESC NULLS LAST+ LIMIT 6+ `;++ // 7-day trade-count + SOL-deployed sparkline, zero-filled per UTC day.+ const seriesPromise = sql`+ WITH days AS (+ SELECT generate_series(+ date_trunc('day', now()) - interval '6 days',+ date_trunc('day', now()),+ interval '1 day'+ ) AS day+ ),+ ev AS (+ SELECT date_trunc('day', ce.created_at) AS day,+ COUNT(*)::int AS trades,+ COALESCE(SUM(ce.amount_lamports), 0)::text AS deployed_lamports+ FROM agent_custody_events ce+ JOIN agent_identities ai ON ai.id = ce.agent_id AND ${pubAgent}+ WHERE ce.network = ${network}+ AND ce.event_type = 'spend' AND ce.category = 'trade'+ AND ce.status IN ('ok', 'confirmed')+ AND ce.created_at > date_trunc('day', now()) - interval '6 days'+ GROUP BY 1+ )+ SELECT to_char(days.day, 'Dy') AS label, to_char(days.day, 'YYYY-MM-DD') AS day,+ COALESCE(ev.trades, 0) AS trades, COALESCE(ev.deployed_lamports, '0') AS deployed_lamports+ FROM days LEFT JOIN ev ON ev.day = days.day+ ORDER BY days.day+ `;++ const [d24, d7, [pnl], topTraders, series] = await Promise.all([+ windowAgg('24 hours'),+ windowAgg('7 days'),+ pnlPromise,+ topTradersPromise,+ seriesPromise,+ ]);++ const closedCount = Number(pnl?.closed_count || 0);+ const wins = Number(pnl?.wins || 0);+ const netPnlSol = Number(pnl?.net_lamports || 0) / 1e9;++ return {+ network,+ window_24h: d24,+ window_7d: d7,+ realized_pnl_7d: {+ net_sol: netPnlSol,+ closed_positions: closedCount,+ wins,+ win_rate: closedCount > 0 ? wins / closedCount : null,+ },+ series_7d: series.map((r) => ({+ label: r.label,+ day: r.day,+ trades: Number(r.trades || 0),+ deployed_sol: Number(r.deployed_lamports || 0) / 1e9,+ })),+ top_traders: topTraders.map((r) => ({+ id: r.agent_id,+ name: r.agent_name || 'Agent',+ url: `/agent/${r.agent_id}`,+ avatar_thumbnail_url: r2Url(r.thumb_key, r.avatar_vis === 'public' || r.avatar_vis === 'unlisted'),+ solana_address: r.agent_addr || null,+ trades: Number(r.trades || 0),+ deployed_sol: Number(r.deployed_lamports || 0) / 1e9,+ })),+ };+}+export default async function handler(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;if (!method(req, res, ['GET'])) return;@@ -741,6 +901,17 @@ export default async function handler(req, res) {return json(res, 200, { data: body });}+ if (view === 'trading') {+ const cacheKey = `pulse:trading:${network}`;+ let body = await cacheGet(cacheKey);+ if (body === null) {+ body = await handleTrading(network);+ await cacheSet(cacheKey, body, STATS_TTL_S);+ }+ res.setHeader('cache-control', 'public, max-age=20');+ return json(res, 200, { data: body });+ }+if (view === 'agent-summary') {if (!agentId) return error(res, 400, 'validation_error', 'agent_id is required for agent-summary');const body = await handleAgentSummary(network, agentId);diff --git a/api/scene-capture.js b/api/scene-capture.jsnew file mode 100644index 000000000..3d9e77966--- /dev/null+++ b/api/scene-capture.js@@ -0,0 +1,144 @@+/**+ * /api/scene-capture — streaming video → 3D point-cloud reconstruction.+ *+ * POST /api/scene-capture+ * { video_url: string, // public https URL to an mp4/mov/webm+ * mode?: "streaming"|"windowed",+ * fps?: int, keyframe_interval?: int, num_scale_frames?: int,+ * mask_sky?: bool, conf_percentile?: 0..95, max_points?: int }+ * → 202 { job_id, status, eta_seconds }+ *+ * GET /api/scene-capture?job=<id>+ * → { job_id, status, result_url?, num_points?, frames?, error? }+ *+ * Routes to workers/model-video2scene (LingBot-Map on Cloud Run GPU) via the+ * shared gcp regen provider when GCP_VIDEO2SCENE_URL + GCP_RECONSTRUCTION_KEY are+ * set; otherwise returns a clean 503 so the page degrades to its sample renderer.+ *+ * The result is a binary .ply point cloud the /capture page renders client-side+ * with a WebGL point-cloud viewer. No auth — rate-limited by client IP on the+ * same mcp3d buckets the rest of the forge surface uses.+ */++import { cors, json, method, readJson, wrap, rateLimited } from './_lib/http.js';+import { limits, clientIp } from './_lib/rate-limit.js';+import { assertPublicHttpsUrl, SsrfError } from './_lib/ssrf.js';+import { createRegenProvider } from './_providers/gcp.js';++const JOB_ID_RE = /^[A-Za-z0-9_-]{20,512}$/;++// Reconstruction quality / sampling knobs, clamped to the worker's accepted ranges.+function clampInt(v, lo, hi, dflt) {+ const n = Math.round(Number(v));+ return Number.isFinite(n) ? Math.min(hi, Math.max(lo, n)) : dflt;+}++function unconfigured(res) {+ return json(res, 503, {+ error: 'unconfigured',+ message:+ 'Scene capture is not configured on this deployment. Set GCP_VIDEO2SCENE_URL ' ++ 'and GCP_RECONSTRUCTION_KEY to the URL and bearer secret of your deployed ' ++ 'workers/model-video2scene Cloud Run service.',+ });+}++async function startJob(req, res) {+ const ip = clientIp(req);+ const rl = await limits.mcp3dGenerate(ip);+ if (!rl.success) return rateLimited(res, rl, 'Reconstruction limit reached. Try again shortly.');++ const body = await readJson(req, 8_000).catch(() => null);++ const rawVideoUrl = typeof body?.video_url === 'string' ? body.video_url.trim() : '';+ if (!rawVideoUrl) {+ return json(res, 400, {+ error: 'missing_video_url',+ message: 'Pass a public https URL to a video (mp4, mov, or webm) as video_url.',+ });+ }++ // Resolve + validate the host ourselves (rejects private/loopback/metadata IPs)+ // before handing the URL to the worker — defense in depth against SSRF.+ let videoUrl;+ try {+ videoUrl = await assertPublicHttpsUrl(rawVideoUrl);+ } catch (err) {+ return json(res, 400, {+ error: 'invalid_video_url',+ message: err instanceof SsrfError ? `video_url rejected: ${err.message}` : 'video_url must be a public https URL.',+ });+ }++ const params = {+ mode: body?.mode === 'windowed' ? 'windowed' : 'streaming',+ fps: clampInt(body?.fps, 1, 30, 8),+ keyframe_interval: clampInt(body?.keyframe_interval, 1, 64, 4),+ num_scale_frames: clampInt(body?.num_scale_frames, 2, 16, 8),+ 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),+ mask_sky: body?.mask_sky !== false,+ };++ let provider;+ try {+ provider = createRegenProvider();+ if (!provider.supportsMode('video2scene')) return unconfigured(res);+ } catch {+ return unconfigured(res);+ }++ try {+ const job = await provider.submit({ mode: 'video2scene', sourceUrl: videoUrl, params });+ return json(res, 202, {+ job_id: job.extJobId,+ status: 'queued',+ eta_seconds: job.eta,+ });+ } catch (err) {+ const status = err?.status === 501 ? 503 : 502;+ return json(res, status, {+ error: status === 503 ? 'unconfigured' : 'capture_failed',+ message: err?.message || 'Reconstruction could not start.',+ });+ }+}++async function pollJob(req, res, jobId) {+ if (!JOB_ID_RE.test(jobId)) {+ return json(res, 400, { error: 'invalid_job', message: 'Malformed job id.' });+ }++ const rl = await limits.mcp3dStatus(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ let provider;+ try {+ provider = createRegenProvider();+ } catch {+ return unconfigured(res);+ }++ const result = await provider.status(jobId);+ return json(res, 200, {+ job_id: jobId,+ status: result.status,+ result_url: result.resultPointCloudUrl || null,+ num_points: result.numPoints ?? null,+ frames: result.frames ?? null,+ error: result.error || null,+ });+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;+ if (!method(req, res, ['GET', 'POST'])) return;++ if (req.method === 'POST') return startJob(req, res);++ const url = new URL(req.url, 'http://localhost');+ const jobId = (url.searchParams.get('job') || '').trim();+ if (!jobId) return json(res, 400, { error: 'missing_job', message: 'Pass ?job=<id> to poll.' });+ return pollJob(req, res, jobId);+});diff --git a/data/pages.json b/data/pages.jsonindex a17254167..0862f194c 100644--- a/data/pages.json+++ b/data/pages.json@@ -313,6 +313,14 @@"changefreq": "monthly","added": "2026-06-26"},+ {+ "path": "/capture",+ "title": "Scene Capture — Video to 3D Point Cloud",+ "description": "Turn a phone video of any space into an explorable 3D point cloud. Streaming feed-forward reconstruction (LingBot-Map Geometric Context Transformer) fuses the frames into a coloured .ply, rendered live in the browser with WebGL. Or load a point cloud you already have.",+ "priority": 0.7,+ "changefreq": "monthly",+ "added": "2026-06-27"+ },{"path": "/forge-nim","title": "Forge · NIM — Self-Hosted Image to 3D",@@ -675,6 +683,14 @@"changefreq": "realtime","added": "2026-06-16"},+ {+ "path": "/pipeline",+ "title": "Recording Pipeline — the data loop, live",+ "description": "One-glance health of the closed loop that turns every pump.fun launch into a trade signal: the launch recorder, signal intel, ground-truth outcomes, Oracle conviction, the wallet reputation graph, trained weights, and the agents trading on the result — every stage, in real time.",+ "priority": 0.7,+ "changefreq": "realtime",+ "added": "2026-06-27"+ },{"path": "/guardian","title": "Guardian console — recover & inherit agent wallets",diff --git a/pages/admin/launcher.html b/pages/admin/launcher.htmlindex 79c700f58..5c6157528 100644--- a/pages/admin/launcher.html+++ b/pages/admin/launcher.html@@ -149,17 +149,33 @@</section></form>- <!-- Live console -->- <section class="ml-console" aria-label="Live launch console">- <div class="ml-console-h">- <h2 class="ml-card-h">Live console</h2>- <span class="ml-console-meta" id="ml-console-meta">—</span>- </div>- <ol class="ml-runs" id="ml-runs"></ol>- <div class="ml-runs-empty" id="ml-runs-empty" hidden>- <p>No launches yet. Arm the launcher to see live activity here.</p>- </div>- </section>+ <!-- Right column: live intelligence + console -->+ <div class="ml-rail">+ <!-- Live narratives the launcher would ride right now -->+ <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="ml-narr-meta">—</span>+ </div>+ <p class="ml-narr-lead" id="ml-narr-lead" hidden></p>+ <ol class="ml-narr-list" id="ml-narr-list"></ol>+ <div class="ml-narr-empty" id="ml-narr-empty" hidden>+ <p>No live narrative yet. Enable trend sources (Know Your Meme, Coin intel…) to surface the currents the launcher would ride.</p>+ </div>+ </section>++ <!-- Live console -->+ <section class="ml-console" aria-label="Live launch console">+ <div class="ml-console-h">+ <h2 class="ml-card-h">Live console</h2>+ <span class="ml-console-meta" id="ml-console-meta">—</span>+ </div>+ <ol class="ml-runs" id="ml-runs"></ol>+ <div class="ml-runs-empty" id="ml-runs-empty" hidden>+ <p>No launches yet. Arm the launcher to see live activity here.</p>+ </div>+ </section>+ </div></div></div></main>diff --git a/pages/agent-screen.html b/pages/agent-screen.htmlindex 8b71c1ccb..02419320d 100644--- a/pages/agent-screen.html+++ b/pages/agent-screen.html@@ -25,9 +25,12 @@<style>:root {- --screen-accent: #5b8fff;- --screen-live: #3ddc84;+ /* Monochrome viewer: the accent and the "live" signal are both pure+ white against the near-black panels; depth comes from tone, not hue. */+ --screen-accent: #f4f4f5;+ --screen-live: #ffffff;--screen-dark: rgba(255,255,255,0.3);+ --screen-on-accent: #0a0a0b;}body {@@ -74,7 +77,7 @@display: inline-flex;align-items: center;gap: 0.35rem;- background: rgba(61,220,132,0.12);+ background: rgba(255,255,255,0.12);color: var(--screen-live);font-size: 0.72rem;font-weight: 700;@@ -82,7 +85,7 @@text-transform: uppercase;padding: 0.25rem 0.6rem;border-radius: 999px;- border: 1px solid rgba(61,220,132,0.25);+ border: 1px solid rgba(255,255,255,0.25);}.asc-live-badge .dot {width: 6px;@@ -179,7 +182,7 @@.asc-screen-overlay .pulse-ring {width: 56px;height: 56px;- border: 2px solid rgba(91,143,255,0.35);+ border: 2px solid rgba(255,255,255,0.35);border-radius: 50%;animation: asc-ring 2s ease-out infinite;position: relative;@@ -189,7 +192,7 @@position: absolute;inset: 8px;border-radius: 50%;- background: rgba(91,143,255,0.12);+ background: rgba(255,255,255,0.12);animation: asc-inner 2s ease-out infinite;}.asc-screen-overlay p { margin: 0; text-align: center; }@@ -314,9 +317,9 @@padding: 1px 6px;border-radius: 4px;}- .asc-log-type.screenshot { background: rgba(91,143,255,0.15); color: #7aaeff; }- .asc-log-type.trade { background: rgba(61,220,132,0.15); color: #4ddd96; }- .asc-log-type.analysis { background: rgba(255,192,80,0.15); color: #ffc85a; }+ .asc-log-type.screenshot { background: rgba(255,255,255,0.15); color: #d4d4d8; }+ .asc-log-type.trade { background: rgba(255,255,255,0.15); color: #ffffff; }+ .asc-log-type.analysis { background: rgba(255,255,255,0.15); color: #d4d4d8; }.asc-log-type.activity { background: rgba(255,255,255,0.07); color: rgba(255,255,255,0.5); }.asc-log-text { color: rgba(255,255,255,0.78); }.asc-log-empty {@@ -363,8 +366,8 @@display: inline-flex;align-items: center;gap: 0.4rem;- background: linear-gradient(135deg, #4a7fff, #8260ff);- color: #fff;+ background: var(--screen-accent);+ color: var(--screen-on-accent);border-radius: 9px;padding: 0.55rem 1.1rem;font-weight: 650;@@ -399,12 +402,8 @@margin: 0 0 0.5rem;font-size: 1.6rem;font-weight: 760;- color: #eef2fa;+ color: #f4f4f5;letter-spacing: -0.03em;- background: linear-gradient(135deg, #fff 30%, #8a9fff);- -webkit-background-clip: text;- -webkit-text-fill-color: transparent;- background-clip: text;}.ws-setup-hero p {margin: 0;@@ -429,9 +428,9 @@width: 26px;height: 26px;border-radius: 50%;- background: rgba(91,143,255,0.18);- border: 1.5px solid rgba(91,143,255,0.4);- color: #7aabff;+ background: rgba(255,255,255,0.18);+ border: 1.5px solid rgba(255,255,255,0.4);+ color: #d4d4d8;font-size: 0.78rem;font-weight: 760;display: flex;@@ -440,9 +439,9 @@flex: none;}.ws-step-num.done {- background: rgba(61,220,132,0.15);- border-color: rgba(61,220,132,0.4);- color: #3ddc84;+ background: rgba(255,255,255,0.15);+ border-color: rgba(255,255,255,0.4);+ color: #ffffff;}.ws-setup-step-head h3 {margin: 0;@@ -476,24 +475,24 @@transition: border-color 0.15s, background 0.15s;text-align: left;}- .ws-agent-card:hover { border-color: rgba(91,143,255,0.35); background: rgba(91,143,255,0.07); }- .ws-agent-card.selected { border-color: #5b8fff; background: rgba(91,143,255,0.12); }+ .ws-agent-card:hover { border-color: rgba(255,255,255,0.35); background: rgba(255,255,255,0.07); }+ .ws-agent-card.selected { border-color: #f4f4f5; background: rgba(255,255,255,0.12); }.ws-agent-avatar {width: 36px;height: 36px;border-radius: 8px;object-fit: cover;flex: none;- background: rgba(91,143,255,0.15);- border: 1px solid rgba(91,143,255,0.2);+ background: rgba(255,255,255,0.15);+ border: 1px solid rgba(255,255,255,0.2);}.ws-agent-avatar-placeholder {width: 36px;height: 36px;border-radius: 8px;flex: none;- background: linear-gradient(135deg, rgba(91,143,255,0.2), rgba(130,96,255,0.2));- border: 1px solid rgba(91,143,255,0.2);+ background: linear-gradient(135deg, rgba(255,255,255,0.2), rgba(255,255,255,0.2));+ border: 1px solid rgba(255,255,255,0.2);display: flex;align-items: center;justify-content: center;@@ -522,7 +521,7 @@padding: 1rem 0;text-align: center;}- .ws-agent-empty a { color: #7aabff; }+ .ws-agent-empty a { color: #d4d4d8; }/* API key area */.ws-key-row {@@ -538,7 +537,7 @@padding: 0.6rem 0.85rem;font-family: 'Courier New', monospace;font-size: 0.8rem;- color: #a8c2ff;+ color: #c8c8cc;overflow: hidden;text-overflow: ellipsis;white-space: nowrap;@@ -560,8 +559,8 @@}.ws-btn:active { transform: scale(0.97); }.ws-btn-primary {- background: linear-gradient(135deg, #4a7fff, #8260ff);- color: #fff;+ background: var(--screen-accent);+ color: var(--screen-on-accent);}.ws-btn-primary:hover { opacity: 0.88; }.ws-btn-primary:disabled { opacity: 0.45; cursor: not-allowed; }@@ -579,14 +578,14 @@border-radius: 8px;font-size: 0.8rem;}- .ws-btn-copy.copied { background: rgba(61,220,132,0.12); border-color: rgba(61,220,132,0.3); color: #3ddc84; }+ .ws-btn-copy.copied { background: rgba(255,255,255,0.12); border-color: rgba(255,255,255,0.3); color: #ffffff; }.ws-key-note {font-size: 0.78rem;color: rgba(255,255,255,0.35);margin-top: 0.6rem;line-height: 1.5;}- .ws-key-note strong { color: rgba(255,200,80,0.8); }+ .ws-key-note strong { color: rgba(255,255,255,0.8); }/* Command block */.ws-cmd-tabs {@@ -608,9 +607,9 @@transition: all 0.15s;}.ws-cmd-tab.active {- background: rgba(91,143,255,0.15);- border-color: rgba(91,143,255,0.4);- color: #8aabff;+ background: rgba(255,255,255,0.15);+ border-color: rgba(255,255,255,0.4);+ color: #d4d4d8;}.ws-cmd-block {position: relative;@@ -629,15 +628,15 @@font-family: 'Courier New', monospace;font-size: 0.78rem;line-height: 1.65;- color: #c5d5ff;+ color: #c8c8cc;overflow-x: auto;white-space: pre;padding-right: 3rem;}.ws-cmd-block pre .cmd-comment { color: rgba(255,255,255,0.3); }- .ws-cmd-block pre .cmd-key { color: #7aabff; }- .ws-cmd-block pre .cmd-val { color: #a8e6cf; }- .ws-cmd-block pre .cmd-run { color: #ffcc66; }+ .ws-cmd-block pre .cmd-key { color: #d4d4d8; }+ .ws-cmd-block pre .cmd-val { color: #c8c8cc; }+ .ws-cmd-block pre .cmd-run { color: #d4d4d8; }.ws-cmd-block pre .cmd-dim { color: rgba(255,255,255,0.25); }.ws-status-ok {@@ -645,11 +644,11 @@align-items: center;gap: 0.5rem;font-size: 0.82rem;- color: #3ddc84;+ color: #ffffff;margin-top: 0.9rem;padding: 0.55rem 0.85rem;- background: rgba(61,220,132,0.08);- border: 1px solid rgba(61,220,132,0.2);+ background: rgba(255,255,255,0.08);+ border: 1px solid rgba(255,255,255,0.2);border-radius: 8px;}.ws-watch-link {@@ -657,8 +656,8 @@align-items: center;gap: 0.45rem;margin-top: 0.75rem;- background: linear-gradient(135deg, #4a7fff, #8260ff);- color: #fff;+ background: var(--screen-accent);+ color: var(--screen-on-accent);border-radius: 9px;padding: 0.6rem 1.2rem;font-size: 0.88rem;@@ -675,17 +674,17 @@font-size: 0.85rem;color: rgba(255,255,255,0.5);padding: 0.8rem 1rem;- background: rgba(255,200,80,0.06);- border: 1px solid rgba(255,200,80,0.15);+ background: rgba(255,255,255,0.06);+ border: 1px solid rgba(255,255,255,0.15);border-radius: 8px;}- .ws-not-signed-in a { color: #ffcc66; }+ .ws-not-signed-in a { color: #d4d4d8; }.ws-spinner {display: inline-block;width: 14px;height: 14px;- border: 2px solid rgba(91,143,255,0.3);- border-top-color: #5b8fff;+ border: 2px solid rgba(255,255,255,0.3);+ border-top-color: #f4f4f5;border-radius: 50%;animation: ws-spin 0.7s linear infinite;flex: none;@@ -720,11 +719,11 @@transition: border-color 0.15s, box-shadow 0.15s;}.asc-task-form:focus-within {- border-color: rgba(91,143,255,0.55);- box-shadow: 0 0 0 3px rgba(91,143,255,0.12);+ border-color: rgba(255,255,255,0.55);+ box-shadow: 0 0 0 3px rgba(255,255,255,0.12);}.asc-task-icon {- color: rgba(91,143,255,0.6);+ color: rgba(255,255,255,0.6);font-size: 0.72rem;flex: none;user-select: none;@@ -738,7 +737,7 @@color: rgba(255,255,255,0.9);font: inherit;font-size: 0.85rem;- caret-color: #5b8fff;+ caret-color: #f4f4f5;}.asc-task-input::placeholder { color: rgba(255,255,255,0.28); }.asc-task-input:disabled { opacity: 0.5; }@@ -746,8 +745,8 @@flex: none;appearance: none;border: none;- background: linear-gradient(135deg, #4a7fff, #8260ff);- color: #fff;+ background: var(--screen-accent);+ color: var(--screen-on-accent);border-radius: 7px;width: 30px;height: 30px;@@ -769,7 +768,7 @@transition: opacity 0.2s;}.asc-task-status.ok { color: var(--screen-live); }- .asc-task-status.err { color: #ff6b6b; }+ .asc-task-status.err { color: #f4f4f5; }/* ── fullscreen mode ── */.asc-screen-panel:fullscreen { background: #000; }diff --git a/pages/agents-live.html b/pages/agents-live.htmlindex 178fab7ad..bf74fabea 100644--- a/pages/agents-live.html+++ b/pages/agents-live.html@@ -24,14 +24,30 @@<link rel="stylesheet" href="/fonts/fonts.css" /><style>:root {- --al-bg: #060608;- --al-surface: #0d0f18;- --al-border: rgba(255,255,255,0.07);- --al-text: #e8eaf4;- --al-muted: rgba(255,255,255,0.35);- --al-green: #5fd08a;- --al-accent: #5b8fff;- --al-font: 'Inter', system-ui, -apple-system, sans-serif;+ --al-bg: #0a0a0b;+ --al-surface: #141416;+ --al-surface-2: #1b1b1e;+ --al-border: rgba(255,255,255,0.08);+ --al-border-hi: rgba(255,255,255,0.18);+ --al-text: #f4f4f5;+ --al-muted: rgba(255,255,255,0.44);+ --al-faint: rgba(255,255,255,0.22);+ /* Monochrome: "live" reads as pure white against the near-black field. */+ --al-green: #ffffff;+ --al-accent: #f4f4f5;+ --al-font: 'Inter', system-ui, -apple-system, sans-serif;+ }+ [data-theme='light'] {+ --al-bg: #f6f6f7;+ --al-surface: #ffffff;+ --al-surface-2: #f0f0f1;+ --al-border: rgba(0,0,0,0.1);+ --al-border-hi: rgba(0,0,0,0.2);+ --al-text: #18181b;+ --al-muted: rgba(0,0,0,0.5);+ --al-faint: rgba(0,0,0,0.3);+ --al-green: #18181b;+ --al-accent: #18181b;}*, *::before, *::after { box-sizing: border-box; margin: 0; padding: 0; }@@ -85,13 +101,13 @@display: flex;align-items: center;gap: 5px;- background: rgba(95,208,138,0.1);- border: 1px solid rgba(95,208,138,0.22);+ background: rgba(255,255,255,0.06);+ border: 1px solid var(--al-border-hi);border-radius: 20px;padding: 3px 10px 3px 7px;font-size: 11px;font-weight: 700;- color: var(--al-green);+ color: var(--al-text);letter-spacing: 0.03em;}.al-live-pill-dot {@@ -121,15 +137,15 @@.al-nav-cta {padding: 6px 14px;border-radius: 6px;- background: rgba(91,143,255,0.12);- border: 1px solid rgba(91,143,255,0.28);- color: var(--al-accent);+ background: rgba(255,255,255,0.06);+ border: 1px solid var(--al-border-hi);+ color: var(--al-text);font-size: 13px;font-weight: 700;text-decoration: none;- transition: background 0.12s;+ transition: background 0.12s, border-color 0.12s;}- .al-nav-cta:hover { background: rgba(91,143,255,0.22); }+ .al-nav-cta:hover { background: rgba(255,255,255,0.12); border-color: var(--al-text); }/* ── main content ─────────────────────────────────────────────── */.al-main {@@ -383,15 +399,15 @@margin-top: 4px;padding: 9px 20px;border-radius: 7px;- background: rgba(95,208,138,0.1);- border: 1px solid rgba(95,208,138,0.25);- color: var(--al-green);+ background: var(--al-text);+ border: 1px solid var(--al-text);+ color: var(--al-bg);font-size: 13px;font-weight: 700;text-decoration: none;- transition: background 0.12s;+ transition: opacity 0.12s;}- .al-empty-cta:hover { background: rgba(95,208,138,0.2); }+ .al-empty-cta:hover { opacity: 0.85; }/* ── skeleton loader ──────────────────────────────────────────── */.al-skeleton {@@ -492,8 +508,8 @@</div><div class="al-grid" id="al-grid">- <!-- Skeleton loaders while fetching -->- ${[0,1,2].map(() => `+ <!-- Static skeleton loaders shown until the roster resolves; src/agents-live.js+ removes these once real cards (or the empty state) render. --><div class="al-skeleton"><div class="al-skeleton-screen"></div><div class="al-skeleton-info">@@ -503,7 +519,27 @@<div class="al-skeleton-line"></div></div></div>- </div>`).join('')}+ </div>+ <div class="al-skeleton">+ <div class="al-skeleton-screen"></div>+ <div class="al-skeleton-info">+ <div class="al-skeleton-avatar"></div>+ <div class="al-skeleton-lines">+ <div class="al-skeleton-line"></div>+ <div class="al-skeleton-line"></div>+ </div>+ </div>+ </div>+ <div class="al-skeleton">+ <div class="al-skeleton-screen"></div>+ <div class="al-skeleton-info">+ <div class="al-skeleton-avatar"></div>+ <div class="al-skeleton-lines">+ <div class="al-skeleton-line"></div>+ <div class="al-skeleton-line"></div>+ </div>+ </div>+ </div></div></main>diff --git a/pages/capture.html b/pages/capture.htmlnew file mode 100644index 000000000..494d3389f--- /dev/null+++ b/pages/capture.html@@ -0,0 +1,335 @@+<!doctype html>+<html lang="en">+ <head>+ <script>/* three.ws theme boot — no-flash */(function(){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 http-equiv="X-UA-Compatible" content="IE=edge" />+ <title>Scene Capture — Video to 3D Point Cloud · three.ws</title>+ <meta name="viewport" content="width=device-width, initial-scale=1.0" />+ <meta name="description" content="Turn a phone video of any space into an explorable 3D point cloud in the browser. Streaming feed-forward reconstruction (LingBot-Map) → coloured .ply, rendered live with WebGL." />+ <meta name="theme-color" content="#000000" />+ <link rel="canonical" href="https://three.ws/capture" />++ <meta property="og:type" content="website" />+ <meta property="og:site_name" content="three.ws" />+ <meta property="og:title" content="Scene Capture — Video to 3D Point Cloud · three.ws" />+ <meta property="og:description" content="Film a space, get an explorable 3D point cloud. Streaming feed-forward reconstruction → coloured .ply, rendered live in the browser." />+ <meta property="og:url" content="https://three.ws/capture" />+ <meta property="og:image" content="https://three.ws/api/page-og?s=build&t=Scene+Capture&d=Turn+a+video+of+any+space+into+an+explorable+3D+point+cloud.&p=%2Fcapture" />+ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:site" content="@trythreews" />+ <meta name="twitter:title" content="Scene Capture — Video to 3D Point Cloud · three.ws" />+ <meta name="twitter:description" content="Film a space, get an explorable 3D point cloud — rendered live in the browser." />+ <meta name="twitter:image" content="https://three.ws/api/page-og?s=build&t=Scene+Capture&d=Turn+a+video+of+any+space+into+an+explorable+3D+point+cloud.&p=%2Fcapture" />++ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/footer.css" />+ <link rel="stylesheet" href="/fonts/fonts.css" />++ <style>+ /* Monochrome by design — greyscale tokens only, white as the single accent. */+ .pc-page {+ min-height: 100vh;+ background: var(--bg, #060606);+ color: var(--text, #f6f6f6);+ font-family: var(--font-body, 'Inter', system-ui, sans-serif);+ -webkit-font-smoothing: antialiased;+ }+ .pc-wrap { max-width: 1180px; margin: 0 auto; padding: 40px 24px 72px; }++ .pc-chip {+ display: inline-flex; align-items: center; gap: 7px;+ padding: 4px 11px; background: var(--surface-1, #141414);+ border: 1px solid var(--hairline, #1f1f1f); border-radius: 20px;+ font-size: 11px; color: var(--text-2, #b4b4b4); letter-spacing: 0.06em;+ text-transform: uppercase; margin-bottom: 16px;+ }+ .pc-chip-dot { width: 6px; height: 6px; border-radius: 50%; background: var(--text, #f6f6f6); }+ .pc-head h1 {+ font-family: var(--font-display, 'Space Grotesk', sans-serif);+ font-size: clamp(26px, 4.4vw, 42px); font-weight: 700;+ letter-spacing: -0.025em; margin: 0 0 12px; line-height: 1.06;+ }+ .pc-head p { color: var(--text-2, #a8a8a8); font-size: 15px; line-height: 1.6; margin: 0; max-width: 660px; }+ .pc-head a { color: var(--text, #f6f6f6); }++ .pc-layout { display: grid; grid-template-columns: 1fr 320px; gap: 18px; margin-top: 28px; align-items: start; }++ /* Stage */+ .pc-stage {+ position: relative; aspect-ratio: 16 / 11;+ background:+ radial-gradient(circle at 50% 30%, #141414 0%, #070707 72%);+ border: 1px solid var(--hairline, #1f1f1f);+ border-radius: 16px; overflow: hidden; min-height: 380px;+ }+ .pc-host { position: absolute; inset: 0; }+ .pc-host canvas { display: block; width: 100% !important; height: 100% !important; }+ .pc-stage.is-dragover { border-color: var(--text, #f6f6f6); }++ /* Overlays */+ .pc-overlay {+ position: absolute; inset: 0; display: flex; flex-direction: column;+ align-items: center; justify-content: center; gap: 14px;+ text-align: center; padding: 24px; pointer-events: none;+ }+ .pc-overlay[hidden] { display: none; }+ .pc-spinner {+ width: 34px; height: 34px; border-radius: 50%;+ border: 2px solid rgba(255,255,255,0.14); border-top-color: var(--text, #f6f6f6);+ animation: pc-spin 0.8s linear infinite;+ }+ @keyframes pc-spin { to { transform: rotate(360deg); } }+ .pc-overlay h3 { font-family: var(--font-display, 'Space Grotesk', sans-serif); font-size: 17px; margin: 0; color: var(--text, #f6f6f6); }+ .pc-overlay p { font-size: 13px; color: var(--text-3, #8a8a8a); margin: 0; max-width: 380px; line-height: 1.5; }+ .pc-overlay--drop { pointer-events: auto; cursor: pointer; transition: background 0.15s; }+ .pc-overlay--drop:hover, .pc-stage.is-dragover .pc-overlay--drop { background: rgba(255,255,255,0.03); }+ .pc-glyph {+ width: 56px; height: 56px; border-radius: 14px; display: grid; place-items: center;+ color: var(--text, #f6f6f6); background: var(--surface-1, #141414); border: 1px solid var(--hairline-strong, #2a2a2a);+ }+ .pc-err-actions { display: flex; gap: 8px; pointer-events: auto; }++ /* HUD */+ .pc-hud {+ position: absolute; left: 12px; right: 12px; bottom: 12px;+ display: flex; align-items: center; justify-content: space-between; gap: 10px; pointer-events: none;+ }+ .pc-hud-label {+ font-size: 11.5px; color: var(--text-2, #cfcfcf);+ background: rgba(0,0,0,0.6); border: 1px solid var(--hairline, #1f1f1f);+ padding: 6px 11px; border-radius: 8px; backdrop-filter: blur(6px);+ max-width: 52%; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;+ }+ .pc-hud-right { display: flex; align-items: center; gap: 8px; pointer-events: auto; }+ .pc-size-wrap {+ display: flex; align-items: center; gap: 7px; background: rgba(0,0,0,0.6);+ border: 1px solid var(--hairline, #1f1f1f); border-radius: 8px; padding: 5px 9px; backdrop-filter: blur(6px);+ }+ .pc-size-wrap svg { color: var(--text-3, #8a8a8a); }+ .pc-size { width: 84px; accent-color: var(--text, #f6f6f6); cursor: pointer; }+ .pc-size:disabled { opacity: 0.4; cursor: default; }+ .pc-icon-btn {+ width: 32px; height: 32px; display: grid; place-items: center;+ background: rgba(0,0,0,0.6); border: 1px solid var(--hairline, #1f1f1f);+ border-radius: 8px; color: var(--text-2, #cfcfcf); cursor: pointer;+ backdrop-filter: blur(6px); transition: color 0.15s, border-color 0.15s;+ }+ .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[hidden] { display: none; }++ /* Side panel */+ .pc-panel { display: flex; flex-direction: column; gap: 14px; }+ .pc-card {+ background: var(--surface-1, #111); border: 1px solid var(--hairline, #1f1f1f);+ border-radius: 13px; padding: 16px;+ }+ .pc-card h2 { font-family: var(--font-display, 'Space Grotesk', sans-serif); font-size: 13px; font-weight: 700; margin: 0 0 12px; letter-spacing: 0.01em; display: flex; align-items: center; gap: 7px; }+ .pc-field { display: flex; flex-direction: column; gap: 8px; }+ .pc-label { font-size: 11px; color: var(--text-3, #8a8a8a); letter-spacing: 0.03em; text-transform: uppercase; }+ .pc-input, .pc-select {+ width: 100%; background: var(--surface-0, #0b0b0b);+ border: 1px solid var(--hairline, #1f1f1f); border-radius: 9px;+ color: var(--text, #f6f6f6); font-size: 13px; font-family: inherit;+ padding: 9px 11px; outline: none; transition: border-color 0.15s; box-sizing: border-box;+ }+ .pc-input:focus, .pc-select:focus { border-color: var(--text, #f6f6f6); }+ .pc-input::placeholder { color: var(--text-4, #6e6e6e); }+ .pc-btn {+ display: inline-flex; align-items: center; justify-content: center; gap: 7px;+ width: 100%; padding: 10px 14px; border-radius: 9px; font-size: 13px; font-weight: 600;+ border: 1px solid var(--hairline-strong, #2a2a2a); background: transparent;+ color: var(--text, #f6f6f6); cursor: pointer; font-family: inherit;+ transition: background 0.15s, border-color 0.15s, opacity 0.15s;+ }+ .pc-btn:hover { background: var(--surface-2, #1a1a1a); }+ .pc-btn:focus-visible { outline: 2px solid var(--text, #fff); outline-offset: 2px; }+ .pc-btn:disabled { opacity: 0.5; cursor: default; }+ .pc-btn--primary { background: var(--text, #f6f6f6); color: #000; border-color: var(--text, #f6f6f6); }+ .pc-btn--primary:hover { background: #fff; }+ .pc-row { display: grid; grid-template-columns: 1fr 1fr; gap: 8px; }+ .pc-adv { margin-top: 10px; }+ .pc-adv summary { font-size: 11.5px; color: var(--text-3, #8a8a8a); cursor: pointer; list-style: none; user-select: none; padding: 4px 0; }+ .pc-adv summary::-webkit-details-marker { display: none; }+ .pc-adv summary::before { content: '▸ '; color: var(--text-4, #6e6e6e); }+ .pc-adv[open] summary::before { content: '▾ '; }+ .pc-adv-body { display: flex; flex-direction: column; gap: 10px; padding-top: 10px; }+ .pc-check { display: flex; align-items: center; gap: 8px; font-size: 12.5px; color: var(--text-2, #b4b4b4); cursor: pointer; }+ .pc-check input { accent-color: var(--text, #f6f6f6); width: 15px; height: 15px; }+ .pc-or { display: flex; align-items: center; gap: 10px; color: var(--text-4, #6e6e6e); font-size: 11px; margin: 12px 0; }+ .pc-or::before, .pc-or::after { content: ''; flex: 1; height: 1px; background: var(--hairline, #1f1f1f); }+ .pc-hint { font-size: 11.5px; color: var(--text-4, #6e6e6e); line-height: 1.5; margin: 10px 0 0; }+ .pc-sample-btn {+ display: flex; align-items: center; gap: 9px; text-align: left; width: 100%;+ padding: 9px 11px; border-radius: 9px; cursor: pointer; font-family: inherit;+ background: var(--surface-0, #0b0b0b); border: 1px solid var(--hairline, #1f1f1f);+ color: var(--text-2, #a8a8a8); font-size: 12.5px; transition: border-color 0.15s, color 0.15s;+ }+ .pc-sample-btn:hover { border-color: var(--hairline-strong, #2a2a2a); color: var(--text, #f6f6f6); }+ .pc-sample-dot { width: 8px; height: 8px; border-radius: 50%; background: var(--text, #f6f6f6); flex: 0 0 auto; }+ .pc-note { font-size: 11.5px; color: var(--text-3, #8a8a8a); line-height: 1.55; }+ .pc-note a { color: var(--text-2, #cfcfcf); }++ @media (max-width: 880px) { .pc-layout { grid-template-columns: 1fr; } }+ </style>+ </head>+ <body>+ <div class="pc-page">+ <div id="nav-container"></div>+ <script type="module" src="/nav.js"></script>++ <div class="pc-wrap">+ <header class="pc-head">+ <span class="pc-chip"><span class="pc-chip-dot"></span> Streaming reconstruction · LingBot-Map</span>+ <h1>Video → 3D scene.</h1>+ <p>+ Film a room, a street, an object — and get back an explorable 3D point cloud.+ A feed-forward <a href="/avatar-engines">Geometric Context Transformer</a> reconstructs+ dense world-space geometry from the frames, then streams a coloured <code>.ply</code> you+ can orbit right here. Already have a point cloud? Drop it in or paste a URL.+ </p>+ </header>++ <div class="pc-layout">+ <div class="pc-stage" id="pc-stage">+ <div class="pc-host" id="pc-host"></div>++ <!-- Idle / drop -->+ <div class="pc-overlay pc-overlay--drop" id="pc-idle">+ <div class="pc-glyph">+ <svg width="26" height="26" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.6"><path d="M12 2 2 7l10 5 10-5-10-5Z"/><path d="M2 17l10 5 10-5"/><path d="M2 12l10 5 10-5"/></svg>+ </div>+ <h3>Capture a scene to begin</h3>+ <p>Paste a video URL on the right to reconstruct, drop a <code>.ply</code> here, or try the sample cloud.</p>+ </div>++ <!-- Loading -->+ <div class="pc-overlay" id="pc-loading" hidden>+ <div class="pc-spinner"></div>+ <h3 id="pc-loading-title">Working…</h3>+ <p id="pc-loading-sub"></p>+ </div>++ <!-- Error -->+ <div class="pc-overlay" id="pc-error" hidden>+ <div class="pc-glyph" style="color:#f0f0f0">+ <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.8"><path d="M12 9v4 M12 17h.01"/><circle cx="12" cy="12" r="9"/></svg>+ </div>+ <h3 id="pc-error-title">Something went wrong</h3>+ <p id="pc-error-sub"></p>+ <div class="pc-err-actions">+ <button class="pc-btn" id="pc-error-retry" type="button" style="width:auto">Try the sample</button>+ </div>+ </div>++ <!-- HUD -->+ <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">+ <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">+ <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>+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 3v12 M7 11l5 4 5-4 M5 21h14"/></svg>+ </a>+ </div>+ </div>+ </div>++ <aside class="pc-panel">+ <div class="pc-card">+ <h2>+ <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>+ Capture from video+ </h2>+ <div class="pc-field">+ <input class="pc-input" id="pc-url" type="url" placeholder="https://…/walkthrough.mp4" autocomplete="off" />+ <button class="pc-btn pc-btn--primary" id="pc-run" type="button">+ <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>+ </div>+ <details class="pc-adv">+ <summary>Reconstruction settings</summary>+ <div class="pc-adv-body">+ <div class="pc-row">+ <div class="pc-field">+ <span class="pc-label">Mode</span>+ <select class="pc-select" id="pc-mode">+ <option value="streaming" selected>Streaming</option>+ <option value="windowed">Windowed (>3k frames)</option>+ </select>+ </div>+ <div class="pc-field">+ <span class="pc-label">Sample FPS</span>+ <select class="pc-select" id="pc-fps">+ <option value="4">4</option>+ <option value="8" selected>8</option>+ <option value="12">12</option>+ </select>+ </div>+ </div>+ <div class="pc-field">+ <span class="pc-label">Keyframe interval</span>+ <select class="pc-select" id="pc-kf">+ <option value="2">2 · denser, slower</option>+ <option value="4" selected>4 · balanced</option>+ <option value="8">8 · faster, lighter</option>+ </select>+ </div>+ <label class="pc-check"><input type="checkbox" id="pc-sky" checked /> Mask out sky</label>+ </div>+ </details>+ <p class="pc-hint">Steady, well-lit footage that orbits or walks through a space works best. Long clips run in minutes — the view updates the moment it's ready.</p>+ </div>++ <div class="pc-card">+ <h2>+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><path d="M7 10l5 5 5-5"/><path d="M12 15V3"/></svg>+ Load a point cloud+ </h2>+ <div class="pc-field">+ <input class="pc-input" id="pc-ply-url" type="url" placeholder="https://…/scene.ply" autocomplete="off" />+ <button class="pc-btn" id="pc-load-url" type="button">Render URL</button>+ </div>+ <div class="pc-or">or</div>+ <button class="pc-btn" id="pc-pick" type="button">+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M12 3v12 M7 11l5 4 5-4 M5 21h14"/></svg>+ Upload a .ply+ </button>+ <input id="pc-file" type="file" accept=".ply" hidden />+ <div class="pc-or">or</div>+ <button class="pc-sample-btn" id="pc-sample" type="button"><span class="pc-sample-dot"></span> Sample interior · 90k points</button>+ <p class="pc-hint">Files stay on your device — decoding and rendering run entirely in your browser.</p>+ </div>++ <div class="pc-card">+ <h2>How it works</h2>+ <p class="pc-note">+ Frames stream through a feed-forward transformer that grounds coordinates, reads dense+ geometry, and corrects drift across the whole clip — no per-scene optimisation. The result+ is a world-space coloured point cloud. Output renders with WebGL <code>THREE.Points</code>;+ this is a point cloud, not a <a href="/splat">Gaussian splat</a>.+ </p>+ </div>+ </aside>+ </div>+ </div>++ <div id="footer-container"></div>+ <script src="/footer.js" defer></script>+ </div>++ <script type="module" src="/src/scene-capture.js"></script>+ </body>+</html>diff --git a/pages/pipeline.html b/pages/pipeline.htmlnew file mode 100644index 000000000..f7fd07c07--- /dev/null+++ b/pages/pipeline.html@@ -0,0 +1,318 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <script>/* three.ws theme boot — no-flash */(function(){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, viewport-fit=cover" />+ <title>Recording Pipeline · three.ws</title>+ <meta name="description" content="Live health of the three.ws data loop: the pump.fun launch recorder, signal intel, ground-truth outcomes, Oracle conviction, the wallet reputation graph, trained weights, and the agents trading on the result — every stage, in real time." />+ <link rel="canonical" href="https://three.ws/pipeline" />+ <link rel="icon" href="/favicon.ico" sizes="any" />+ <link rel="icon" type="image/svg+xml" href="/favicon.svg" />+ <link rel="apple-touch-icon" href="/apple-touch-icon.png" />+ <link rel="manifest" href="/site.webmanifest" />+ <link rel="stylesheet" href="/style.css" />+ <link rel="stylesheet" href="/nav.css" />+ <link rel="stylesheet" href="/mobile.css" />+ <meta property="og:type" content="website" />+ <meta property="og:title" content="Recording Pipeline · three.ws" />+ <meta property="og:description" content="The data loop, live: launch recorder → signal intel → ground-truth outcomes → Oracle conviction → reputation graph → trained weights → trading agents." />+ <meta property="og:url" content="https://three.ws/pipeline" />+ <meta name="twitter:card" content="summary_large_image" />+ <style>+ /* ── Strict monochrome. State is encoded by lightness + opacity, never hue.+ All values inherit the canonical ramp from /tokens.css (loaded via+ style.css): --bg-*, --ink*, --surface-*, --stroke*, --radius-*. ── */+ :root {+ --pl-gap: 14px;+ --pl-card-min: 168px;+ /* one neutral ramp for stage "liveness" — bright = flowing, faint = idle */+ --pl-live: var(--ink-bright, #fff);+ --pl-active: var(--ink, #e8e8e8);+ --pl-idle: var(--ink-faint, rgba(255,255,255,0.45));+ --pl-down: var(--ink-dim, #888);+ }+ * { box-sizing: border-box; }+ body {+ margin: 0;+ background: var(--bg-0, #0a0a0a);+ color: var(--ink, #e8e8e8);+ font-family: var(--font-body, 'Inter', system-ui, sans-serif);+ -webkit-font-smoothing: antialiased;+ }+ .pl-main { max-width: 1180px; margin: 0 auto; padding: clamp(18px, 4vw, 40px) clamp(14px, 4vw, 28px) 80px; }++ /* ── Header ───────────────────────────────────────────────────── */+ .pl-head { display: flex; flex-wrap: wrap; align-items: flex-end; gap: 16px 24px; margin-bottom: 8px; }+ .pl-title { font-family: var(--font-display, 'Space Grotesk', sans-serif); font-size: clamp(1.6rem, 4vw, 2.3rem); font-weight: 600; letter-spacing: -0.02em; margin: 0; color: var(--ink-bright, #fff); }+ .pl-sub { color: var(--ink-dim, #888); font-size: 0.9rem; max-width: 56ch; margin: 6px 0 0; line-height: 1.5; }+ .pl-controls { display: flex; align-items: center; gap: 10px; margin-left: auto; }+ .pl-net { display: inline-flex; border: 1px solid var(--stroke, rgba(255,255,255,0.08)); border-radius: var(--radius-pill, 999px); overflow: hidden; }+ .pl-net button { appearance: none; background: transparent; border: 0; color: var(--ink-dim, #888); font: inherit; font-size: 0.78rem; padding: 6px 13px; cursor: pointer; transition: color .14s, background .14s; }+ .pl-net button[aria-pressed="true"] { background: var(--surface-3, rgba(255,255,255,0.08)); color: var(--ink-bright, #fff); }+ .pl-net button:hover { color: var(--ink, #e8e8e8); }+ .pl-net button:focus-visible { outline: 2px solid var(--stroke-strong, rgba(255,255,255,0.14)); outline-offset: -2px; }+ .pl-refresh { appearance: none; 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, 10px); color: var(--ink-dim, #888); width: 34px; height: 34px; display: grid; place-items: center; cursor: pointer; transition: color .14s, border-color .14s, transform .3s; }+ .pl-refresh:hover { color: var(--ink-bright, #fff); border-color: var(--stroke-strong, rgba(255,255,255,0.14)); }+ .pl-refresh.spin svg { animation: pl-spin .6s var(--ease-standard, cubic-bezier(.2,.8,.2,1)); }+ @keyframes pl-spin { to { transform: rotate(360deg); } }++ /* ── Overall health banner ───────────────────────────────────── */+ .pl-health { display: flex; flex-wrap: wrap; align-items: center; gap: 12px 18px; margin: 22px 0 26px; padding: 16px 18px; border: 1px solid var(--stroke, rgba(255,255,255,0.08)); border-radius: var(--radius-lg, 14px); background: var(--surface-1, rgba(255,255,255,0.03)); }+ .pl-dot { width: 9px; height: 9px; border-radius: 50%; flex: none; background: var(--pl-down); position: relative; }+ .pl-dot.is-live { background: var(--pl-live); box-shadow: 0 0 0 0 rgba(255,255,255,0.5); animation: pl-pulse 2s infinite; }+ .pl-dot.is-active { background: var(--pl-active); }+ .pl-dot.is-degraded { background: var(--pl-down); animation: pl-blink 1.1s steps(2) infinite; }+ .pl-dot.is-idle, .pl-dot.is-offline, .pl-dot.is-down, .pl-dot.is-unknown { background: transparent; border: 1.5px solid var(--pl-idle); }+ @keyframes pl-pulse { 0% { box-shadow: 0 0 0 0 rgba(255,255,255,0.45); } 70% { box-shadow: 0 0 0 7px rgba(255,255,255,0); } 100% { box-shadow: 0 0 0 0 rgba(255,255,255,0); } }+ @keyframes pl-blink { 50% { opacity: 0.3; } }+ .pl-health-label { font-family: var(--font-display, sans-serif); font-weight: 600; font-size: 1.05rem; color: var(--ink-bright, #fff); text-transform: capitalize; }+ .pl-health-note { color: var(--ink-dim, #888); font-size: 0.85rem; flex: 1 1 280px; line-height: 1.45; }+ .pl-meta { color: var(--ink-faint, rgba(255,255,255,0.45)); font-size: 0.72rem; font-family: var(--font-mono, monospace); letter-spacing: 0.02em; white-space: nowrap; }++ /* ── Offline call-to-action ──────────────────────────────────── */+ .pl-cta { margin: -8px 0 26px; padding: 16px 18px; border: 1px dashed var(--stroke-strong, rgba(255,255,255,0.14)); border-radius: var(--radius-lg, 14px); background: var(--surface-1, rgba(255,255,255,0.03)); }+ .pl-cta h3 { margin: 0 0 6px; font-size: 0.95rem; color: var(--ink-bright, #fff); font-weight: 600; }+ .pl-cta p { margin: 0; color: var(--ink-dim, #888); font-size: 0.85rem; line-height: 1.5; }+ .pl-cta code { font-family: var(--font-mono, monospace); font-size: 0.8rem; background: var(--surface-3, rgba(255,255,255,0.08)); padding: 1px 6px; border-radius: 5px; color: var(--ink, #e8e8e8); }++ /* ── The flow rail ───────────────────────────────────────────── */+ .pl-flow { display: grid; grid-template-columns: repeat(7, 1fr); gap: var(--pl-gap); align-items: stretch; }+ @media (max-width: 1080px) { .pl-flow { grid-template-columns: repeat(3, 1fr); } }+ @media (max-width: 620px) { .pl-flow { grid-template-columns: repeat(2, 1fr); } }+ @media (max-width: 400px) { .pl-flow { grid-template-columns: 1fr; } }++ .pl-stage { position: relative; display: flex; flex-direction: column; min-height: 158px; padding: 14px; border: 1px solid var(--stroke, rgba(255,255,255,0.08)); border-radius: var(--radius-lg, 14px); background: var(--surface-1, rgba(255,255,255,0.03)); transition: border-color .2s var(--ease-standard, ease), background .2s, transform .2s; opacity: 0; transform: translateY(8px); animation: pl-in .42s var(--ease-standard, cubic-bezier(.2,.8,.2,1)) forwards; }+ .pl-stage:hover { border-color: var(--stroke-strong, rgba(255,255,255,0.14)); background: var(--surface-2, rgba(255,255,255,0.05)); }+ .pl-stage.s-live, .pl-stage.s-active { border-color: var(--stroke-strong, rgba(255,255,255,0.18)); }+ .pl-stage.s-live::before { content: ""; position: absolute; inset: 0; border-radius: inherit; box-shadow: inset 0 0 0 1px rgba(255,255,255,0.10); pointer-events: none; }+ .pl-stage.s-idle, .pl-stage.s-offline, .pl-stage.s-down { opacity: 0; }+ .pl-stage.s-idle { animation-name: pl-in-dim; }+ @keyframes pl-in { to { opacity: 1; transform: none; } }+ @keyframes pl-in-dim { to { opacity: 0.62; transform: none; } }++ /* flow arrows between stages (desktop only) */+ .pl-stage:not(:last-child)::after { content: ""; position: absolute; top: 50%; right: calc(var(--pl-gap) * -1 - 1px); width: var(--pl-gap); height: 1px; background: linear-gradient(90deg, var(--stroke-strong, rgba(255,255,255,0.14)), transparent); transform: translateY(-50%); z-index: 1; }+ @media (max-width: 1080px) { .pl-stage::after { display: none; } }++ .pl-stage-top { display: flex; align-items: center; gap: 7px; margin-bottom: 2px; }+ .pl-stage-n { font-family: var(--font-mono, monospace); font-size: 0.62rem; color: var(--ink-faint, rgba(255,255,255,0.45)); }+ .pl-stage-label { font-family: var(--font-display, sans-serif); font-size: 0.82rem; font-weight: 600; color: var(--ink-bright, #fff); margin: 0; }+ .pl-stage-tag { font-size: 0.66rem; color: var(--ink-dim, #888); margin: 0 0 12px; text-transform: uppercase; letter-spacing: 0.06em; }+ .pl-stat { margin-top: auto; }+ .pl-stat-v { font-family: var(--font-mono, monospace); font-size: 1.55rem; font-weight: 600; color: var(--ink-bright, #fff); line-height: 1; letter-spacing: -0.02em; }+ .pl-stat-v.dim { color: var(--ink-faint, rgba(255,255,255,0.45)); }+ .pl-stat-l { font-size: 0.68rem; color: var(--ink-dim, #888); margin-top: 4px; }+ .pl-subs { list-style: none; margin: 11px 0 0; padding: 11px 0 0; border-top: 1px solid var(--stroke, rgba(255,255,255,0.06)); display: grid; gap: 4px; }+ .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; }++ /* ── 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; }+ @keyframes pl-shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }+ .pl-error { grid-column: 1 / -1; text-align: center; padding: 48px 22px; border: 1px solid var(--stroke, rgba(255,255,255,0.08)); border-radius: var(--radius-lg, 14px); background: var(--surface-1, rgba(255,255,255,0.03)); }+ .pl-error h3 { margin: 0 0 6px; color: var(--ink-bright, #fff); font-size: 1rem; }+ .pl-error p { margin: 0 0 16px; color: var(--ink-dim, #888); font-size: 0.85rem; }+ .pl-btn { appearance: none; background: var(--ink-bright, #fff); color: var(--bg-0, #0a0a0a); border: 0; border-radius: var(--radius-md, 10px); font: inherit; font-weight: 600; font-size: 0.82rem; padding: 9px 18px; cursor: pointer; transition: opacity .14s, transform .14s; }+ .pl-btn:hover { opacity: 0.9; }+ .pl-btn:active { transform: translateY(1px); }++ /* ── Legend ──────────────────────────────────────────────────── */+ .pl-legend { display: flex; flex-wrap: wrap; gap: 16px; margin-top: 26px; color: var(--ink-dim, #888); font-size: 0.72rem; }+ .pl-legend span { display: inline-flex; align-items: center; gap: 7px; }+ @media (prefers-reduced-motion: reduce) { * { animation-duration: .001ms !important; } .pl-stage { opacity: 1 !important; transform: none !important; } }+ </style>+</head>+<body>+ <header class="site-header"><div id="nav-container"></div></header>++ <main class="pl-main">+ <div class="pl-head">+ <div>+ <h1 class="pl-title">Recording Pipeline</h1>+ <p class="pl-sub">The closed loop that turns every pump.fun launch into a trade signal — recorded, scored, labeled, and learned from. Each stage feeds the next.</p>+ </div>+ <div class="pl-controls">+ <div class="pl-net" role="group" aria-label="Network">+ <button data-net="mainnet" aria-pressed="true">mainnet</button>+ <button data-net="devnet" aria-pressed="false">devnet</button>+ </div>+ <button class="pl-refresh" id="pl-refresh" aria-label="Refresh now" title="Refresh">+ <svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.2" stroke-linecap="round" stroke-linejoin="round"><path d="M21 12a9 9 0 1 1-2.64-6.36"/><path d="M21 3v6h-6"/></svg>+ </button>+ </div>+ </div>++ <div class="pl-health" id="pl-health" hidden>+ <span class="pl-dot" id="pl-health-dot"></span>+ <span class="pl-health-label" id="pl-health-label">—</span>+ <span class="pl-health-note" id="pl-health-note"></span>+ <span class="pl-meta" id="pl-meta"></span>+ </div>++ <div class="pl-cta" id="pl-cta" hidden>+ <h3>The recorder hasn't started yet</h3>+ <p>The always-on worker that watches the live pump.fun feed isn't reporting a heartbeat. Deploy it in simulate mode — <code>npm run deploy:sniper</code> — and this pipeline lights up stage by stage as data flows. Simulate spends zero SOL; it only records.</p>+ </div>++ <div class="pl-flow" id="pl-flow" aria-live="polite">+ <div class="pl-skel"></div><div class="pl-skel"></div><div class="pl-skel"></div>+ <div class="pl-skel"></div><div class="pl-skel"></div><div class="pl-skel"></div><div class="pl-skel"></div>+ </div>++ <div class="pl-legend">+ <span><i class="pl-dot is-live" style="position:static"></i> Live — flowing now</span>+ <span><i class="pl-dot is-active" style="position:static"></i> Active — has data</span>+ <span><i class="pl-dot is-idle" style="position:static"></i> Idle — awaiting upstream</span>+ <span><i class="pl-dot is-degraded" style="position:static"></i> Degraded — up but stalled</span>+ </div>+ </main>++ <script src="/nav.js"></script>+ <script type="module">+ const flow = document.getElementById('pl-flow');+ const healthEl = document.getElementById('pl-health');+ const dotEl = document.getElementById('pl-health-dot');+ const labelEl = document.getElementById('pl-health-label');+ const noteEl = document.getElementById('pl-health-note');+ const metaEl = document.getElementById('pl-meta');+ const ctaEl = document.getElementById('pl-cta');+ const refreshBtn = document.getElementById('pl-refresh');+ const netBtns = [...document.querySelectorAll('.pl-net button')];++ let network = 'mainnet';+ let timer = null;+ let inFlight = false;++ const esc = (s) => String(s ?? '').replace(/[&<>"]/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"' }[c]));+ const fmt = (n) => { n = Number(n) || 0; return n >= 1e6 ? (n / 1e6).toFixed(1) + 'M' : n >= 1e3 ? (n / 1e3).toFixed(1) + 'k' : String(n); };+ const ago = (ms) => { if (ms == null) return '—'; const s = Math.round(ms / 1000); if (s < 60) return s + 's ago'; const m = Math.round(s / 60); if (m < 60) return m + 'm ago'; return Math.round(m / 60) + 'h ago'; };+ const since = (iso) => { if (!iso) return '—'; return ago(Date.now() - new Date(iso).getTime()); };++ // Each stage derives its visual state + headline + sub-rows from the raw payload.+ // State is purely about data flow — encoded by lightness in the monochrome theme.+ function stageModels(s) {+ const rec = s.recorder || {};+ const recState = rec.state === 'live' ? 'live' : rec.state === 'degraded' ? 'degraded'+ : (rec.state === 'down' || rec.state === 'offline' || rec.state === 'unknown') ? rec.state : 'idle';+ const on = (v) => (v > 0 ? 'active' : 'idle');+ return [+ {+ n: '01', label: 'Recorder', tag: 'pump.fun feed', state: recState,+ value: rec.state === 'live' ? 'LIVE' : rec.state === 'degraded' ? 'STALL' : rec.state === 'down' ? 'DOWN' : 'OFF',+ vdim: rec.state !== 'live', vlabel: rec.mode ? rec.mode + ' · ' + (rec.feedLive ? 'feed up' : 'feed down') : 'not reporting',+ subs: [['Heartbeat', ago(rec.heartbeatAgeMs)], ['Last event', ago(rec.lastEventAgeMs)], ['Reconnects', rec.reconnects ?? '—']],+ },+ {+ n: '02', label: 'Intel', tag: 'launch signals', state: on(s.intel.observed_24h),+ value: fmt(s.intel.observed_24h), vdim: !s.intel.observed_24h, vlabel: 'launches recorded · 24h',+ subs: [['Last hour', fmt(s.intel.observed_1h)], ['Avg quality', s.intel.avg_quality ?? '—'], ['Smart-money seen', fmt(s.intel.smart_money_touched)]],+ },+ {+ n: '03', label: 'Outcomes', tag: 'ground truth', state: on(s.outcomes.labeled),+ value: fmt(s.outcomes.labeled), vdim: !s.outcomes.labeled, vlabel: 'coins labeled',+ subs: [['Graduated', fmt(s.outcomes.graduated)], ['Pumped ≥3×', fmt(s.outcomes.pumped)], ['Rugged', fmt(s.outcomes.rugged)]],+ },+ {+ n: '04', label: 'Oracle', tag: 'conviction', state: on(s.oracle.scored_total),+ value: fmt(s.oracle.scored_total), vdim: !s.oracle.scored_total, vlabel: 'coins scored',+ subs: [['Scored · 24h', fmt(s.oracle.scored_24h)], ['Prime tier', fmt(s.oracle.prime)], ['Strong tier', fmt(s.oracle.strong)]],+ },+ {+ n: '05', label: 'Reputation', tag: 'wallet graph', state: on(s.reputation.wallets),+ value: fmt(s.reputation.wallets), vdim: !s.reputation.wallets, vlabel: 'wallets profiled',+ subs: [['Smart money', fmt(s.reputation.smart_money)]],+ },+ {+ n: '06', label: 'Learning', tag: 'trained weights', state: on(s.learning.sample_size),+ value: fmt(s.learning.sample_size), vdim: !s.learning.sample_size, vlabel: s.learning.sample_size >= 50 ? 'samples trained' : 'samples · needs ≥50',+ subs: s.learning.weights.length+ ? s.learning.weights.slice(0, 3).map((w) => [w.signal.replace(/_/g, ' '), (w.weight >= 0 ? '+' : '') + w.weight.toFixed(2)])+ : [['Trained', since(s.learning.trained_at)]],+ },+ {+ n: '07', label: 'Trading', tag: 'armed agents', state: (s.trading.snipes_24h + s.trading.trades_24h) > 0 ? 'active' : on(s.trading.strategies_armed),+ value: fmt(s.trading.snipes_24h + s.trading.trades_24h), vdim: !(s.trading.snipes_24h + s.trading.trades_24h), vlabel: 'snipes + trades · 24h',+ subs: [['Armed', fmt(s.trading.strategies_armed)], ['Open positions', fmt(s.trading.open_positions)], ['Snipes · 24h', fmt(s.trading.snipes_24h)]],+ },+ ];+ }++ 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">+ <div class="pl-stage-top">+ <span class="pl-stage-n">${m.n}</span>+ <h2 class="pl-stage-label">${esc(m.label)}</h2>+ <span class="pl-dot pl-stage-dot is-${m.state}"></span>+ </div>+ <p class="pl-stage-tag">${esc(m.tag)}</p>+ <div class="pl-stat">+ <div class="pl-stat-v${m.vdim ? ' dim' : ''}">${esc(m.value)}</div>+ <div class="pl-stat-l">${esc(m.vlabel)}</div>+ </div>+ <ul class="pl-subs">${subs}</ul>+ </article>`;+ }++ function renderHealth(data) {+ healthEl.hidden = false;+ const rec = data.stages.recorder || {};+ const cls = data.health === 'flowing' ? 'is-live' : data.health === 'recording' ? 'is-active'+ : rec.state === 'degraded' ? 'is-degraded' : 'is-idle';+ dotEl.className = 'pl-dot ' + cls;+ labelEl.textContent = data.health;+ noteEl.textContent = data.health === 'flowing'+ ? 'The recorder is live and launches are streaming in — the full loop is running.'+ : data.health === 'recording'+ ? 'The recorder is live; waiting on the next launch to flow downstream.'+ : rec.state === 'degraded'+ ? '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');+ }++ async function load() {+ if (inFlight) return;+ inFlight = true;+ refreshBtn.classList.add('spin');+ try {+ const r = await fetch(`/api/pipeline?network=${network}`, { headers: { accept: 'application/json' } });+ if (!r.ok) throw new Error('HTTP ' + r.status);+ const data = await r.json();+ renderHealth(data);+ flow.innerHTML = stageModels(data.stages).map(stageCard).join('');+ } catch (e) {+ healthEl.hidden = true;+ ctaEl.hidden = true;+ flow.innerHTML = `<div class="pl-error">+ <h3>Couldn't reach the pipeline</h3>+ <p>${esc(e.message)} — the status service may be briefly unavailable.</p>+ <button class="pl-btn" id="pl-retry">Try again</button></div>`;+ document.getElementById('pl-retry')?.addEventListener('click', load);+ } finally {+ inFlight = false;+ setTimeout(() => refreshBtn.classList.remove('spin'), 600);+ }+ }++ function schedule() { clearInterval(timer); timer = setInterval(load, 8000); }++ netBtns.forEach((b) => b.addEventListener('click', () => {+ if (b.dataset.net === network) return;+ network = b.dataset.net;+ netBtns.forEach((x) => x.setAttribute('aria-pressed', String(x.dataset.net === network)));+ flow.innerHTML = '<div class="pl-skel"></div>'.repeat(7);+ load();+ }));+ refreshBtn.addEventListener('click', load);+ // Pause polling when the tab is hidden — no point burning requests in the background.+ document.addEventListener('visibilitychange', () => { if (document.hidden) clearInterval(timer); else { load(); schedule(); } });++ load();+ schedule();+ </script>+</body>+</html>diff --git a/pages/pulse.html b/pages/pulse.htmlindex 7366f0c0e..7db7858a4 100644--- a/pages/pulse.html+++ b/pages/pulse.html@@ -139,6 +139,37 @@</div></section>+ <section class="px-market px-trading" id="px-trading" aria-label="Trading viability" hidden>+ <div class="px-market-h">+ <div class="px-market-htxt">+ <span class="px-market-title">Trading viability</span>+ <span class="px-market-tag" id="px-trade-pnl-tag">—</span>+ </div>+ <span class="px-market-sub">Real, fully-guarded coin trades through agent wallets — what's flowing, what it costs, and the realized P&L on positions that have closed. The honest signal behind the Trades counter.</span>+ </div>+ <div class="px-market-kpis">+ <div class="px-kpi"><dt>Trades · 24h</dt><dd id="px-trade-c24">—</dd><span class="px-kpi-sub" id="px-trade-c24-sub">swaps</span></div>+ <div class="px-kpi"><dt>Trades · 7d</dt><dd id="px-trade-c7">—</dd><span class="px-kpi-sub" id="px-trade-c7-sub">swaps</span></div>+ <div class="px-kpi"><dt>SOL deployed · 7d</dt><dd id="px-trade-dep7">—</dd><span class="px-kpi-sub" id="px-trade-dep7-sub">into buys</span></div>+ <div class="px-kpi"><dt>Avg trade · 7d</dt><dd id="px-trade-avg">—</dd><span class="px-kpi-sub">SOL per buy</span></div>+ <div class="px-kpi"><dt>Active traders · 24h</dt><dd id="px-trade-act">—</dd><span class="px-kpi-sub">wallets trading</span></div>+ <div class="px-kpi"><dt>Realized P&L · 7d</dt><dd id="px-trade-pnl">—</dd><span class="px-kpi-sub" id="px-trade-pnl-sub">closed positions</span></div>+ </div>+ <div class="px-market-body">+ <div class="px-market-spark">+ <div class="px-spark-h">+ <span class="px-spark-title">Trades · last 7 days</span>+ <span class="px-spark-total" id="px-trade-spark-total">—</span>+ </div>+ <div class="px-spark-bars" id="px-trade-spark" role="img" aria-label="Daily trade count, last 7 days"></div>+ </div>+ <div class="px-market-skills">+ <div class="px-card-h">Top traders <small>trades · 7d</small></div>+ <div id="px-trade-traders"><p class="px-lb-empty">Loading…</p></div>+ </div>+ </div>+ </section>+<div class="px-grid"><div class="px-main"><h2 class="px-section-h">Live feed</h2>diff --git a/public/changelog.json b/public/changelog.jsonindex 67fe43515..235f6a876 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-27T20:20:01.960Z",+ "generated_at": "2026-06-27T20:21:36.214Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -46,6 +46,16 @@"launch"]},+ {+ "date": "2026-06-27",+ "type": "launch",+ "title": "Recording Pipeline — the data loop, live",+ "summary": "One-glance health of the closed loop that turns every pump.fun launch into a trade signal: the launch recorder, signal intel, ground-truth outcomes, Oracle conviction, the wallet reputation graph, trained weights, and the agents trading on the result — every stage, in real time.",+ "link": "/pipeline",+ "tags": [+ "launch"+ ]+ },{"date": "2026-06-27","type": "launch",diff --git a/public/changelog.xml b/public/changelog.xmlindex 738048e83..7ba701b6c 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -38,6 +38,14 @@<category>launch</category><description>three.ws partner ecosystem — AWS, IBM, Google Cloud, Alibaba Cloud, Intel, NVIDIA, Microsoft, Oracle. The cloud and AI platforms powering 3D AI agents at enterprise scale.</description></item>+ <item>+ <title>Recording Pipeline — the data loop, live</title>+ <link>https://three.ws/pipeline</link>+ <guid isPermaLink="false">2026-06-27:Recording Pipeline — the data loop, live</guid>+ <pubDate>Sat, 27 Jun 2026 12:00:00 GMT</pubDate>+ <category>launch</category>+ <description>One-glance health of the closed loop that turns every pump.fun launch into a trade signal: the launch recorder, signal intel, ground-truth outcomes, Oracle conviction, the wallet reputation graph, trained weights, and the agents trading on the result — every stage, in real time.</description>+ </item><item><title>three.ws Joins the Alibaba Cloud Partner Network</title><link>https://three.ws/blog/three-ws-alibaba-cloud-partnership</link>diff --git a/public/dashboard/x402-admin.html b/public/dashboard/x402-admin.htmlindex ffa385392..4713a6561 100644--- a/public/dashboard/x402-admin.html+++ b/public/dashboard/x402-admin.html@@ -19,8 +19,13 @@--text: #f0f2f8;--muted: #8a90a8;--muted-2: #6b7088;- --accent: #0a84ff;- --accent-2: #60a5fa;+ /* Monochrome accent — matches the platform design system (public/tokens.css).+ Emphasis is pure white/ink; the only chromatic tokens are the functional+ green/amber/red below, mirroring --success/--warn/--danger. */+ --accent: #ffffff;+ --accent-2: #e8e8e8;+ --accent-tint: rgba(255,255,255,0.10);+ --accent-tint-strong: rgba(255,255,255,0.18);--green: #4ade80;--amber: #fbbf24;--red: #ef4444;@@ -33,7 +38,7 @@-webkit-font-smoothing: antialiased; line-height: 1.5; min-height: 100dvh;}a { color: var(--accent-2); text-decoration: none; }- a:hover { color: #93c5fd; }+ a:hover { color: #ffffff; text-decoration: underline; }/* ── Header ── */header {@@ -43,7 +48,7 @@position: sticky; top: 0; z-index: 30;}header .brand { display: flex; align-items: center; gap: 10px; font-weight: 700; font-size: 15px; letter-spacing: -0.01em; }- header .brand .dot { width: 22px; height: 22px; background: conic-gradient(from 200deg, #ffffff, #60a5fa); border-radius: 6px; }+ header .brand .dot { width: 22px; height: 22px; background: conic-gradient(from 200deg, #ffffff, #4a4a4a); border-radius: 6px; }header .crumb { color: var(--muted); }header .right { margin-left: auto; display: flex; gap: 10px; align-items: center; }header .save-state { font-size: 12px; color: var(--muted); font-family: var(--mono); min-width: 90px; text-align: right; }@@ -110,7 +115,7 @@padding: 11px 13px; border-radius: 9px; font-size: 14px; font-family: inherit;text-transform: none; letter-spacing: 0; font-weight: 400; outline: none; transition: border-color 0.12s, box-shadow 0.12s;}- label.field input:focus, label.field select:focus, label.field textarea:focus { border-color: var(--accent); box-shadow: 0 0 0 3px rgba(10,132,255,0.15); }+ label.field input:focus, label.field select:focus, label.field textarea:focus { border-color: var(--accent); box-shadow: 0 0 0 3px var(--accent-tint); }label.field input.mono { font-family: var(--mono); font-size: 12.5px; }label.field input.invalid { border-color: #7f1d1d; box-shadow: 0 0 0 3px rgba(239,68,68,0.12); }label.field input.valid { border-color: #1c5f3a; }@@ -130,8 +135,8 @@.switch input { opacity: 0; width: 0; height: 0; }.switch .slider { position: absolute; inset: 0; background: var(--panel-2); border: 1px solid var(--border-strong); border-radius: 99px; cursor: pointer; transition: background 0.15s; }.switch .slider::before { content: ""; position: absolute; width: 18px; height: 18px; left: 2px; top: 2px; background: var(--muted); border-radius: 50%; transition: transform 0.15s, background 0.15s; }- .switch input:checked + .slider { background: rgba(10,132,255,0.25); border-color: var(--accent); }- .switch input:checked + .slider::before { transform: translateX(18px); background: var(--accent-2); }+ .switch input:checked + .slider { background: var(--accent-tint-strong); border-color: var(--accent); }+ .switch input:checked + .slider::before { transform: translateX(18px); background: var(--accent); }/* network segmented */.seg { display: inline-flex; background: var(--bg-2); border: 1px solid var(--border); border-radius: 10px; padding: 3px; gap: 3px; }@@ -202,7 +207,7 @@.palette .pal-block .pico { width: 16px; height: 16px; opacity: 0.8; }.canvas { background: var(--bg-2); border: 1px solid var(--border); border-radius: 14px; padding: 14px; min-height: 280px; }- .canvas.drag-over { border-color: var(--accent); box-shadow: inset 0 0 0 2px rgba(10,132,255,0.2); }+ .canvas.drag-over { border-color: var(--accent); box-shadow: inset 0 0 0 2px var(--accent-tint-strong); }.canvas-empty { text-align: center; color: var(--muted); padding: 60px 20px; font-size: 13.5px; }.cblock {@@ -357,7 +362,7 @@</div><div class="row-2"><label class="field">Logo URL<input id="logo_url" class="mono" placeholder="https://acme.com/logo.png" spellcheck="false" /></label>- <label class="field">Accent color<input id="accent_color" type="color" value="#0a84ff" style="height:44px;padding:5px" /></label>+ <label class="field">Accent color<input id="accent_color" type="color" value="#111111" style="height:44px;padding:5px" /></label></div></div></section>@@ -624,7 +629,7 @@ function hydrate(){$('business_name').value = s.business_name || '';$('support_email').value = s.support_email || '';$('logo_url').value = s.logo_url || '';- $('accent_color').value = s.accent_color || '#0a84ff';+ $('accent_color').value = s.accent_color || '#111111';setNetSeg(s.default_network || 'solana');$('webhook_url').value = s.webhook_url || '';$('facilitator').value = s.facilitator || '';@@ -664,7 +669,7 @@ function collect(){business_name: $('business_name').value.trim() || null,support_email: $('support_email').value.trim() || null,logo_url: $('logo_url').value.trim() || null,- accent_color: $('accent_color').value || '#0a84ff',+ accent_color: $('accent_color').value || '#111111',default_network: currentNet,agent_wallets: agentWallets,facilitator: $('facilitator').value.trim() || null,@@ -804,7 +809,7 @@ function renderWallets(){const ok = ADDR_RE[w.chain]?.test(w.address);const caps = [w.per_call_cap_atomics?`≤ ${fmtUsdc(w.per_call_cap_atomics)}/call`:null, w.daily_cap_atomics?`≤ ${fmtUsdc(w.daily_cap_atomics)}/day`:null].filter(Boolean).join(' · ') || 'no caps';return `<div class="prod-card ${w.enabled===false?'inactive':''}" data-i="${i}">- <div class="pc-img" style="background:${w.role==='payer'?'linear-gradient(135deg,#fbbf24,#f59e0b)':'linear-gradient(135deg,#0a84ff,#60a5fa)'};font-size:12px">${w.role==='payer'?'PAY':'IN'}</div>+ <div class="pc-img" style="background:${w.role==='payer'?'linear-gradient(135deg,#fbbf24,#f59e0b)':'linear-gradient(135deg,#5a5a5a,#2e2e2e)'};font-size:12px">${w.role==='payer'?'PAY':'IN'}</div><div><div class="pc-name">${esc(w.label)} ${ok?'':'<span style="color:var(--red);font-size:11px">⚠ invalid</span>'}</div><div class="pc-meta">${esc(w.chain)} · ${esc(shortAddr(w.address))} · ${esc(caps)}</div></div><div class="pc-price" style="color:var(--muted);font-size:11px;text-transform:uppercase">${w.enabled===false?'off':w.role}</div><div class="pc-actions"><button class="btn ghost sm" data-act="edit">Edit</button><button class="btn ghost sm" data-act="del">Remove</button></div>@@ -1130,7 +1135,7 @@ $('store_published').addEventListener('change', updateHandlePreview);// the preview and the live page render identically.function renderStoreHtml(data, isPreview){const s = data.store, prods = data.products || [];- const accent = (s.store_theme && s.store_theme.accent) || s.accent_color || '#0a84ff';+ const accent = (s.store_theme && s.store_theme.accent) || s.accent_color || '#111111';const byId = (id)=> prods.find((p)=> p.id===id);const priceLabel = (p)=> p.price_atomics ? `${(Number(p.price_atomics)/1e6).toString()} USDC` : 'Pay-per-call';const card = (p)=> p ? `<div class="p-card">@@ -1166,7 +1171,7 @@ function renderStoreHtml(data, isPreview){.p-grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(250px,1fr));gap:16px}.p-card{border:1px solid #e6e8ee;border-radius:16px;padding:20px;display:flex;flex-direction:column;gap:10px;background:#fff;transition:box-shadow .15s,transform .08s}.p-card:hover{box-shadow:0 12px 32px rgba(0,0,0,.07);transform:translateY(-2px)}-.p-img{width:52px;height:52px;border-radius:13px;background:linear-gradient(135deg,var(--accent),#60a5fa);color:#fff;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:22px;overflow:hidden}.p-img img{width:100%;height:100%;object-fit:cover}+.p-img{width:52px;height:52px;border-radius:13px;background:var(--accent);color:#fff;display:flex;align-items:center;justify-content:center;font-weight:700;font-size:22px;overflow:hidden}.p-img img{width:100%;height:100%;object-fit:cover}.p-name{font-weight:700;font-size:17px;letter-spacing:-.01em}.p-desc{color:#667;font-size:13.5px;flex:1;min-height:36px}.p-foot{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-top:4px}.p-price{font-weight:700;color:#0a7d3a;font-size:14px}.p-buy{background:#111;color:#fff;border:none;border-radius:10px;padding:10px 20px;font-weight:600;font-size:14px;cursor:pointer;font-family:inherit}.p-buy:hover:not(:disabled){background:#000}.p-buy:disabled{opacity:.5;cursor:default}diff --git a/public/dashboard/x402.html b/public/dashboard/x402.htmlindex e69066f3b..1f9648873 100644--- a/public/dashboard/x402.html+++ b/public/dashboard/x402.html@@ -17,8 +17,11 @@--text: #f0f2f8;--muted: #8a90a8;--muted-2: #6b7088;- --accent: #0a84ff;- --accent-2: #60a5fa;+ /* Monochrome accent — matches the platform design system (public/tokens.css).+ Emphasis is carried by pure white/ink, never a brand hue. Functional+ green/red below are the only chromatic tokens, mirroring --success/--danger. */+ --accent: #ffffff;+ --accent-2: #e8e8e8;--green: #4ade80;--red: #ef4444;--mono: ui-monospace, "JetBrains Mono", "Fira Code", Menlo, monospace;@@ -32,7 +35,7 @@min-height: 100dvh;}a { color: var(--accent-2); text-decoration: none; }- a:hover { color: #93c5fd; }+ a:hover { color: #ffffff; text-decoration: underline; }header {display: flex; align-items: center; gap: 16px;@@ -48,7 +51,7 @@}header .brand .dot {width: 22px; height: 22px;- background: conic-gradient(from 200deg, #ffffff, #60a5fa);+ background: conic-gradient(from 200deg, #ffffff, #4a4a4a);border-radius: 6px;}header .crumb { color: var(--muted); margin-left: 4px; }diff --git a/public/features.json b/public/features.jsonindex 3277eaa72..8b0f9fc98 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-27T10:26:19.957Z",+ "generated_at": "2026-06-27T20:21:36.176Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",@@ -826,6 +826,16 @@"tags": [],"showcase": false},+ {+ "path": "/pipeline",+ "title": "Recording Pipeline — the data loop, live",+ "description": "One-glance health of the closed loop that turns every pump.fun launch into a trade signal: the launch recorder, signal intel, ground-truth outcomes, Oracle conviction, the wallet reputation graph, trained weights, and the agents trading on the result — every stage, in real time.",+ "added": "2026-06-27",+ "auth": null,+ "indexable": true,+ "tags": [],+ "showcase": false+ },{"path": "/guardian","title": "Guardian console — recover & inherit agent wallets",diff --git a/public/llms-full.txt b/public/llms-full.txtindex 765d8636a..f95eab6e4 100644--- a/public/llms-full.txt+++ b/public/llms-full.txt@@ -504,6 +504,12 @@ URL: https://three.ws/activityThe trading floor: every Oracle conviction action from every autonomous 3D agent on pump.fun, live. Filter by tier and mode, track outcomes, and copy the winners.+### Recording Pipeline — the data loop, live++URL: https://three.ws/pipeline++One-glance health of the closed loop that turns every pump.fun launch into a trade signal: the launch recorder, signal intel, ground-truth outcomes, Oracle conviction, the wallet reputation graph, trained weights, and the agents trading on the result — every stage, in real time.+### Guardian console — recover & inherit agent walletsURL: https://three.ws/guardiandiff --git a/public/llms.txt b/public/llms.txtindex 11747b2ab..5a68aaf39 100644--- a/public/llms.txt+++ b/public/llms.txt@@ -102,6 +102,7 @@ On-chain features: pay-per-call, token launches, vanity wallets.- [Oracle — AI Conviction Engine](https://three.ws/oracle): A fused AI conviction engine for every pump.fun launch: pedigree (who's buying), structure (bundle vs organic), narrative (what story is it riding), and momentum — fused into a single 0–100 conviction score with transparent pillar reasoning.- [Arm your agent — automate Oracle conviction](https://three.ws/oracle/arm): Configure your 3D agent to trade Oracle conviction automatically: set the minimum score, position size, daily and open-position caps, narrative filters and Telegram alerts, then arm it in simulate or live mode. Every action is graded against the outcome.- [Agent Activity — Oracle conviction in real time](https://three.ws/activity): The trading floor: every Oracle conviction action from every autonomous 3D agent on pump.fun, live. Filter by tier and mode, track outcomes, and copy the winners.+- [Recording Pipeline — the data loop, live](https://three.ws/pipeline): One-glance health of the closed loop that turns every pump.fun launch into a trade signal: the launch recorder, signal intel, ground-truth outcomes, Oracle conviction, the wallet reputation graph, trained weights, and the agents trading on the result — every stage, in real time.- [Guardian console — recover & inherit agent wallets](https://three.ws/guardian): The agents you’re trusted to protect. Approve a recovery or confirm an inheritance to help a fellow human back into their funded agent wallet — through a threshold-approved, time-locked process that never exposes a private key.- [Launch a Coin](https://three.ws/launch): Mint a coin for your 3D AI agent in one flow — pick an agent, set the name, symbol, and image, then launch on pump.fun straight from your wallet with an optional three.ws-branded vanity mint.- [Agent Launches](https://three.ws/launches): Live public feed of every coin launched by a three.ws agent — market caps, graduation status, and the agent behind each launch.diff --git a/public/nav-data.js b/public/nav-data.jsindex 1c2dc41be..bbd8bb339 100644--- a/public/nav-data.js+++ b/public/nav-data.js@@ -297,6 +297,11 @@ export const NAV_GROUPS = [href: '/activity',desc: 'Every agent trade in real time — entries, outcomes, and who to copy',},+ {+ title: 'Recording Pipeline',+ href: '/pipeline',+ desc: 'Live health of the data loop: recorder, intel, outcomes, Oracle, learning, trading',+ },{title: '3D Visualizer',href: '/pump-visualizer',diff --git a/public/sitemap/index.html b/public/sitemap/index.htmlindex 94dbef019..f59c5cbdc 100644--- a/public/sitemap/index.html+++ b/public/sitemap/index.html@@ -65,7 +65,7 @@<main class="sm-wrap"><div class="sm-hero"><h1>Sitemap</h1>- <p>All 348 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>+ <p>All 349 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p><div class="sm-formats"><a href="/sitemap.xml"><code>sitemap.xml</code> · for search engines</a><a href="/llms.txt"><code>llms.txt</code> · for AI agents</a>@@ -77,7 +77,7 @@</div><div class="sm-filter"><svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" aria-hidden="true"><circle cx="11" cy="11" r="7"/><path d="m21 21-4.3-4.3"/></svg>- <input id="sm-filter-input" type="search" placeholder="Filter 348 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />+ <input id="sm-filter-input" type="search" placeholder="Filter 349 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" /><kbd aria-hidden="true">/</kbd></div><p class="sm-filter-count" id="sm-filter-count" role="status" aria-live="polite"></p>@@ -648,7 +648,7 @@<section class="sm-section" id="crypto"><header>- <h2>Crypto<span class="sm-count" data-count>71</span></h2>+ <h2>Crypto<span class="sm-count" data-count>72</span></h2><p class="sm-section-desc">On-chain features: pay-per-call, token launches, vanity wallets.</p></header><ul class="sm-list">@@ -680,6 +680,13 @@<span class="sm-desc">The trading floor: every Oracle conviction action from every autonomous 3D agent on pump.fun, live. Filter by tier and mode, track outcomes, and copy the winners.</span></a></li>+ <li>+ <a href="/pipeline">+ <span class="sm-title">Recording Pipeline — the data loop, live</span>+ <span class="sm-path">/pipeline</span>+ <span class="sm-desc">One-glance health of the closed loop that turns every pump.fun launch into a trade signal: the launch recorder, signal intel, ground-truth outcomes, Oracle conviction, the wallet reputation graph, trained weights, and the agents trading on the result — every stage, in real time.</span>+ </a>+ </li><li><a href="/guardian"><span class="sm-title">Guardian console — recover & inherit agent wallets</span>diff --git a/scripts/verify-trading-pulse.mjs b/scripts/verify-trading-pulse.mjsnew file mode 100644index 000000000..85a455267--- /dev/null+++ b/scripts/verify-trading-pulse.mjs@@ -0,0 +1,110 @@+#!/usr/bin/env node+// Verify the Trading-viability surface end-to-end against a running deployment.+//+// Proves three things the /pulse "Trading viability" panel depends on:+// 1. GET /api/pulse?view=trading returns the full shape the panel renders.+// 2. Its 24h trade count RECONCILES with the headline stats counter+// (trades_only_24h) — the panel can never silently drift from the number+// $THREE holders see at the top of the page.+// 3. (optional) Firing one circulation tick actually produces trade events —+// the real "is the trade-generation loop wired?" check.+//+// Usage:+// node scripts/verify-trading-pulse.mjs # prod, mainnet+// BASE=https://<preview>.vercel.app NET=devnet node scripts/verify-trading-pulse.mjs+// CRON_SECRET=… TICK=1 NET=devnet node scripts/verify-trading-pulse.mjs # also fire a tick+//+// Exit code 0 = all assertions passed; 1 = a check failed.++const BASE = (process.env.BASE || 'https://three.ws').replace(/\/$/, '');+const NET = process.env.NET === 'devnet' ? 'devnet' : 'mainnet';+const DO_TICK = process.env.TICK === '1' || process.env.TICK === 'true';+const CRON_SECRET = process.env.CRON_SECRET || '';++let failures = 0;+const pass = (m) => console.log(` \x1b[32m✓\x1b[0m ${m}`);+const fail = (m) => { console.log(` \x1b[31m✗ ${m}\x1b[0m`); failures++; };+const fmt = (n) => (Number(n) || 0).toLocaleString('en-US', { maximumFractionDigits: 4 });++async function getJson(path) {+ const res = await fetch(`${BASE}${path}`, { headers: { accept: 'application/json' } });+ const body = await res.json().catch(() => null);+ if (!res.ok) throw new Error(`${path} → ${res.status} ${JSON.stringify(body)?.slice(0, 160)}`);+ return body?.data;+}++async function main() {+ console.log(`\nTrading-viability verify · ${BASE} · ${NET}\n`);++ // 1. Shape.+ console.log('1) GET /api/pulse?view=trading');+ const t = await getJson(`/api/pulse?view=trading&network=${NET}`);+ for (const key of ['window_24h', 'window_7d', 'realized_pnl_7d', 'series_7d', 'top_traders']) {+ if (t && key in t) pass(`has ${key}`);+ else fail(`missing ${key} (got: ${t ? Object.keys(t).join(', ') : 'null'})`);+ }+ if (Array.isArray(t?.series_7d) && t.series_7d.length === 7) pass('series_7d is zero-filled to 7 days');+ else fail(`series_7d should have 7 days, got ${t?.series_7d?.length}`);++ const w24 = t?.window_24h || {};+ const w7 = t?.window_7d || {};+ const pnl = t?.realized_pnl_7d || {};+ console.log(+ ` trades 24h=${fmt(w24.trades)} · 7d=${fmt(w7.trades)} · ` ++ `SOL deployed 7d=◎${fmt(w7.deployed_sol)} · traders 24h=${fmt(w24.traders)} · ` ++ `realized P&L 7d=◎${fmt(pnl.net_sol)} over ${fmt(pnl.closed_positions)} closes`,+ );++ // 2. Reconciliation with the headline counter.+ console.log('\n2) Reconcile with headline stats (trades_only_24h)');+ const stats = await getJson(`/api/pulse?view=stats&network=${NET}`);+ const headline = Number(stats?.trades_only_24h);+ if (!Number.isFinite(headline)) {+ fail('stats.trades_only_24h missing — deploy is behind (split counters not live yet)');+ } else if (headline === Number(w24.trades || 0)) {+ pass(`trading.window_24h.trades (${headline}) === stats.trades_only_24h (${headline})`);+ } else {+ // A small drift is possible if the two cached views expired across a new trade.+ // Flag it but don't hard-fail on a 1-event cache skew.+ const drift = Math.abs(headline - Number(w24.trades || 0));+ (drift <= 1 ? pass : fail)(`headline=${headline} vs panel=${w24.trades} (drift ${drift}${drift <= 1 ? ', within cache skew' : ''})`);+ }++ // 3. Optional: fire one circulation tick and confirm it can produce trades.+ if (DO_TICK) {+ console.log('\n3) Fire one circulation tick (pulse-tick cron)');+ if (!CRON_SECRET) {+ fail('TICK=1 set but CRON_SECRET is empty — cannot authenticate the cron');+ } else {+ const res = await fetch(`${BASE}/api/cron/pulse-tick`, {+ method: 'POST',+ headers: { authorization: `Bearer ${CRON_SECRET}`, 'content-type': 'application/json' },+ });+ const body = await res.json().catch(() => null);+ if (!res.ok) {+ fail(`tick → ${res.status} ${JSON.stringify(body)?.slice(0, 200)}`);+ } else if (body?.skipped === 'disabled') {+ pass('tick inert (CIRCULATION_ENABLED unset) — expected until env + treasury are configured');+ } else if (body?.note === 'pool warming up' || (body?.pool ?? 0) < 2) {+ pass(`tick ran, pool warming up (pool=${body?.pool ?? 0}) — agents being provisioned`);+ } else {+ const acts = Array.isArray(body?.results) ? body.results : [];+ const trades = acts.filter((a) => a?.kind === 'trade' && a?.ok).length;+ const skips = acts.filter((a) => a?.skipped).map((a) => `${a.kind}:${a.skipped}`);+ pass(`tick ran: pool=${body?.pool ?? '?'} · ${acts.length} action(s) · ${trades} trade(s)`);+ if (trades > 0) pass('circulation produced a real trade event — loop is live');+ if (skips.length) console.log(` skips: ${skips.slice(0, 4).join(', ')}`);+ }+ }+ } else {+ console.log('\n3) Skipped circulation tick (set TICK=1 + CRON_SECRET to exercise it)');+ }++ console.log(`\n${failures ? `\x1b[31m${failures} check(s) failed\x1b[0m` : '\x1b[32mAll checks passed\x1b[0m'}\n`);+ process.exit(failures ? 1 : 0);+}++main().catch((e) => {+ console.error(`\n\x1b[31mverify failed:\x1b[0m ${e?.message || e}\n`);+ process.exit(1);+});diff --git a/src/admin-launcher.css b/src/admin-launcher.cssindex 6f68de42e..b6a79d515 100644--- a/src/admin-launcher.css+++ b/src/admin-launcher.css@@ -155,13 +155,34 @@.ml-seg-btn.active { color: var(--ink-bright, #fff); background: var(--surface-3, rgba(255, 255, 255, 0.08)); }.ml-seg-btn:focus-visible { outline: 2px solid var(--accent, #fff); outline-offset: 2px; }+/* ── right rail (narratives + console) ──────────────────────────────────────── */+.ml-rail { position: sticky; top: var(--space-md, 16px); display: flex; flex-direction: column; gap: var(--space-md, 18px); }++/* ── live narratives ────────────────────────────────────────────────────────── */+.ml-narr { background: var(--surface-1, rgba(255, 255, 255, 0.025)); border: 1px solid var(--stroke, rgba(255, 255, 255, 0.07)); border-radius: var(--radius-lg, 16px); padding: var(--space-lg, 22px); }+.ml-narr-lead { margin: 0 0 var(--space-md, 14px); font-size: var(--text-sm, 0.82rem); color: var(--ink-dim, #999); }+.ml-narr-lead strong { color: var(--ink-bright, #fff); font-weight: 700; }+.ml-narr-list { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 6px; max-height: 360px; overflow-y: auto; }+.ml-narr-row { position: relative; display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 8px 11px; border: 1px solid var(--stroke, rgba(255, 255, 255, 0.06)); border-radius: var(--radius-md, 9px); background: var(--surface-1, rgba(255, 255, 255, 0.02)); overflow: hidden; }+.ml-narr-bar { position: absolute; left: 0; top: 0; bottom: 0; background: var(--surface-3, rgba(255, 255, 255, 0.08)); z-index: 0; transition: width 0.35s ease; }+.ml-narr-term { position: relative; z-index: 1; font-size: var(--text-sm, 0.82rem); font-weight: 600; color: var(--ink-bright, #fff); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }+.ml-narr-tags { position: relative; z-index: 1; display: inline-flex; align-items: center; gap: 7px; flex: none; }+.ml-narr-kind { font-size: 0.6rem; text-transform: uppercase; letter-spacing: 0.05em; color: var(--ink-dim, #999); border: 1px solid var(--stroke-strong, rgba(255, 255, 255, 0.16)); border-radius: 999px; padding: 2px 7px; }+.ml-narr-conf { font-family: var(--font-mono, monospace); font-size: var(--text-2xs, 0.66rem); color: var(--ink, #ccc); }+.ml-narr-empty { color: var(--ink-dim, #888); font-size: var(--text-xs, 0.78rem); line-height: 1.5; padding: var(--space-sm, 10px) 0; }+.ml-narr-empty p { margin: 0; }+/* ── console ──────────────────────────────────────────────────────────────── */-.ml-console { position: sticky; top: var(--space-md, 16px); background: var(--surface-1, rgba(255, 255, 255, 0.025)); border: 1px solid var(--stroke, rgba(255, 255, 255, 0.07)); border-radius: var(--radius-lg, 16px); padding: var(--space-lg, 22px); }+.ml-console { background: var(--surface-1, rgba(255, 255, 255, 0.025)); border: 1px solid var(--stroke, rgba(255, 255, 255, 0.07)); border-radius: var(--radius-lg, 16px); padding: var(--space-lg, 22px); }.ml-console-h { display: flex; align-items: baseline; justify-content: space-between; gap: 12px; margin-bottom: var(--space-md, 16px); }.ml-console-meta { font-family: var(--font-mono, monospace); font-size: var(--text-2xs, 0.68rem); color: var(--ink-faint, #666); }.ml-runs { list-style: none; margin: 0; padding: 0; display: flex; flex-direction: column; gap: 8px; max-height: 620px; overflow-y: auto; }.ml-run { display: grid; grid-template-columns: auto 1fr auto; align-items: center; gap: 10px; padding: 10px 12px; background: var(--surface-1, rgba(255, 255, 255, 0.03)); border: 1px solid var(--stroke, rgba(255, 255, 255, 0.06)); border-radius: var(--radius-md, 10px); animation: ml-in 0.24s ease; }@keyframes ml-in { from { opacity: 0; transform: translateY(-4px); } to { opacity: 1; transform: none; } }+/* A freshly-arrived run briefly flashes, then settles — draws the eye without colour. */+.ml-run--new { animation: ml-in 0.24s ease, ml-flash 1.1s ease; }+@keyframes ml-flash { 0% { background: var(--surface-3, rgba(255, 255, 255, 0.1)); border-color: var(--stroke-strong, rgba(255, 255, 255, 0.22)); } 100% { background: var(--surface-1, rgba(255, 255, 255, 0.03)); border-color: var(--stroke, rgba(255, 255, 255, 0.06)); } }+@media (prefers-reduced-motion: reduce) { .ml-run--new { animation: none; } }.ml-run-main { min-width: 0; }.ml-run-name { font-size: var(--text-sm, 0.82rem); font-weight: 600; color: var(--ink-bright, #fff); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }.ml-run-name a { color: inherit; text-decoration: none; border-bottom: 1px solid transparent; }@@ -206,7 +227,7 @@/* ── responsive ───────────────────────────────────────────────────────────── */@media (max-width: 940px) {.ml-grid { grid-template-columns: 1fr; }- .ml-console { position: static; }+ .ml-rail { position: static; }.ml-stats { grid-template-columns: repeat(3, 1fr); }}@media (max-width: 560px) {@@ -218,4 +239,5 @@@media (prefers-reduced-motion: reduce) {.ml-dot.is-armed, .ml-run, .ml-savebar, .ml-toast, .ml-modal, .ml-skel { animation: none; }+ .ml-narr-bar { transition: none; }}diff --git a/src/admin-launcher.js b/src/admin-launcher.jsindex 085f5d162..7124ae22e 100644--- a/src/admin-launcher.js+++ b/src/admin-launcher.js@@ -149,6 +149,13 @@ function startRefresh() { stopRefresh(); refreshTimer = setInterval(refresh, REFfunction stopRefresh() { if (refreshTimer) clearInterval(refreshTimer); refreshTimer = null; }document.addEventListener('visibilitychange', () => { if (!document.hidden) refresh(); });+// Power-user: ⌘/Ctrl+S saves when there are pending edits (and a panel is up).+document.addEventListener('keydown', (e) => {+ if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === 's') {+ if (loaded && !$('ml-panel').hidden && isDirty()) { e.preventDefault(); save(); }+ }+});+// ── static controls (modes, chips, network) built once ────────────────────────let built = false;function buildStaticControls() {@@ -302,39 +309,117 @@ function renderState(state) {renderConsole(state.console || [], state.config?.network || draft.network);$('ml-console-meta').textContent = `updated ${new Date().toLocaleTimeString()}`;++ renderNarratives(state.narratives);}-function renderConsole(runs, network) {- const list = $('ml-runs');- const empty = $('ml-runs-empty');- if (!runs.length) { list.innerHTML = ''; empty.hidden = false; return; }+// ── live narratives (what the launcher would ride right now) ─────────────────────+function renderNarratives(narr) {+ const list = $('ml-narr-list');+ const empty = $('ml-narr-empty');+ const lead = $('ml-narr-lead');+ const meta = $('ml-narr-meta');+ const terms = (narr && Array.isArray(narr.terms)) ? narr.terms : [];++ 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;- list.innerHTML = runs- .map((r) => {- const status = String(r.status || 'pending');- const mint = 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 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>${r.trigger_source ? ' · ' + esc(r.trigger_source) : ''}`;- const sol = Number(r.sol_spent) > 0 ? `${fmtSol(r.sol_spent)} ◎` : (r.dry_run ? 'dry' : '—');+ 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-run">- <span class="ml-pill s-${esc(status)}">${esc(statusLabel(status))}</span>- <span class="ml-run-main">- <span class="ml-run-name">${mint} <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-sol">${esc(sol)}</span>- <span class="ml-run-time">${esc(reltime(r.created_at))}</span>- </span>+ <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('');}+// Inner markup for one run row (without the <li> wrapper) — shared by the keyed+// renderer so a row can be created once and patched in place.+function runRowHtml(r, network) {+ const status = String(r.status || 'pending');+ const mint = 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 = 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) : '')}`;+ 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>` ++ `<span class="ml-run-main">` ++ `<span class="ml-run-name">${mint} <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-sol">${esc(sol)}</span>` ++ `<span class="ml-run-time">${esc(reltime(r.created_at))}</span>` ++ `</span>`+ );+}++// A run is "the same" until its status/cost/mint/error changes — only then do we+// touch the DOM for it. Keeps the 5s refresh cheap and flicker-free.+function runSig(r) { return `${r.status}|${r.sol_spent}|${r.mint || ''}|${r.error || ''}|${reltime(r.created_at)}`; }++const _rows = new Map(); // run id → { el, sig }++// Keyed/incremental render: create new rows (animated in), patch changed rows in+// place, reorder to match newest-first, and drop rows that fell off the window.+function renderConsole(runs, network) {+ const list = $('ml-runs');+ const empty = $('ml-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); }+ }+}+// ── 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)); }@@ -421,6 +506,12 @@ function round(n, d) { const p = 10 ** d; return Math.round(Number(n) * p) / p;function fmtSol(n) { const v = Number(n || 0); return v === 0 ? '0' : v < 0.001 ? v.toExponential(1) : round(v, 4).toString(); }function trunc(s, n) { s = String(s || ''); return s.length > n ? s.slice(0, n - 1) + '…' : s; }function statusLabel(s) { return { dry_run: 'dry', 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 '';diff --git a/src/agents-live.js b/src/agents-live.jsindex defde6471..69e8ef409 100644--- a/src/agents-live.js+++ b/src/agents-live.js@@ -197,16 +197,20 @@ async function refresh() {return;}- // Add new cards.+ // Add new cards — and re-attach streams to existing cards whose stream was+ // torn down (e.g. after the tab was backgrounded via suspendStreams()).for (const agent of agents) {const id = agent.agentId || agent.id;- if (!grid.querySelector(`[data-agent-id="${CSS.escape(id)}"]`)) {- const card = buildCard(agent);+ let card = grid.querySelector(`[data-agent-id="${CSS.escape(id)}"]`);+ if (!card) {+ card = buildCard(agent);// Remove skeleton loaders once we have real cards.grid.querySelectorAll('.al-skeleton').forEach((s) => s.remove());grid.querySelector('.al-empty')?.remove();grid.appendChild(card);attachStream(card, id);+ } else if (!_streams.has(id)) {+ attachStream(card, id);}}}@@ -221,8 +225,36 @@ function startFpsTicker() {}, 1000);}+// Tear down every live stream (used when the tab goes to the background — no+// point decoding frames nobody is watching). Cards stay in the DOM showing+// their last frame; refresh() re-attaches streams when the tab returns.+function suspendStreams() {+ for (const [id, es] of _streams) {+ try { es.close(); } catch { /* */ }+ _streams.delete(id);+ const card = grid.querySelector(`[data-agent-id="${CSS.escape(id)}"]`);+ card?.querySelector('[data-status]')?.replaceChildren(document.createTextNode('Paused'));+ card?.querySelector('[data-dot]')?.classList.add('idle');+ }+}+// ── boot ──────────────────────────────────────────────────────────────────────+let _refreshTimer = null;+function startRefreshLoop() {+ clearInterval(_refreshTimer);+ _refreshTimer = setInterval(() => { if (!document.hidden) refresh(); }, 30_000);+}+await refresh();startFpsTicker();-setInterval(refresh, 30_000);+startRefreshLoop();++// Pause all decoding while the tab is hidden; reconnect the moment it's visible.+document.addEventListener('visibilitychange', () => {+ if (document.hidden) {+ suspendStreams();+ } else {+ refresh(); // re-discovers the roster and re-attaches streams to existing cards+ }+});diff --git a/src/game/coincommunities.css b/src/game/coincommunities.cssindex 4ca233c91..285deab5a 100644--- a/src/game/coincommunities.css+++ b/src/game/coincommunities.css@@ -1744,119 +1744,155 @@ html[data-bg="transparent"] #cc-lobby {.pg-root {position: fixed; inset: 0; z-index: 200;display: grid; place-items: center; padding: 24px;- animation: pg-fade 0.28s ease both;+ animation: pg-fade 0.22s ease both;}-.pg-root.pg-leaving { animation: pg-fade 0.3s ease reverse forwards; pointer-events: none; }+.pg-root.pg-leaving { animation: pg-fade 0.25s ease reverse forwards; pointer-events: none; }.pg-backdrop {position: absolute; inset: 0;- background: radial-gradient(circle at 50% 36%, #161616, #050505 74%);- backdrop-filter: saturate(130%) blur(6px);+ background: radial-gradient(circle at 50% 36%, #141414, #040404 72%);+ backdrop-filter: saturate(140%) blur(8px);}.pg-card {position: relative; z-index: 1;- width: min(420px, 100%); padding: 34px 30px 28px;+ width: min(400px, 100%); padding: 32px 28px 26px;display: flex; flex-direction: column; align-items: center; text-align: center;- background: var(--cc-panel-solid);+ background: #0a0a0a;border: 1px solid var(--cc-edge);+ border-top-color: rgba(255, 255, 255, 0.26);border-radius: var(--cc-radius);- box-shadow: var(--cc-shadow);- animation: pg-rise 0.42s cubic-bezier(0.16, 0.84, 0.34, 1) both;+ box-shadow: 0 20px 60px rgba(0, 0, 0, 0.8), 0 0 0 1px rgba(0, 0, 0, 0.5) inset;+ animation: pg-rise 0.36s cubic-bezier(0.16, 0.84, 0.34, 1) both;}.pg-brand {- display: flex; align-items: center; gap: 9px; margin-bottom: 22px;+ display: flex; align-items: center; gap: 9px; margin-bottom: 20px;color: var(--cc-dim);}-.pg-brand img { filter: drop-shadow(0 0 12px rgba(255, 255, 255, 0.25)); }-.pg-brand span { font-weight: 800; font-size: 11px; letter-spacing: 0.26em; }+.pg-brand img { filter: drop-shadow(0 0 10px rgba(255, 255, 255, 0.2)); }+.pg-brand span { font-weight: 800; font-size: 10.5px; letter-spacing: 0.28em; }.pg-icon {- width: 56px; height: 56px; margin-bottom: 16px;+ width: 52px; height: 52px; margin-bottom: 14px;display: grid; place-items: center;border: 1px solid var(--cc-edge); border-radius: 50%;color: var(--cc-text);+ transition: border-color 0.3s ease, box-shadow 0.3s ease;+}+.pg-icon svg { width: 22px; height: 22px; }+/* Breathing pulse on connect state to draw eye to the CTA */+.pg-card[data-state="connect"] .pg-icon {+ animation: pg-icon-breathe 2.6s ease-in-out infinite;}-.pg-icon svg { width: 26px; height: 26px; }-.pg-title { margin: 0 0 8px; font-size: 21px; font-weight: 700; letter-spacing: -0.01em; color: var(--cc-text); }-.pg-sub { margin: 0 0 22px; font-size: 13.5px; line-height: 1.55; color: var(--cc-dim); max-width: 34ch; }+.pg-title { margin: 0 0 7px; font-size: 20px; font-weight: 700; letter-spacing: -0.015em; color: var(--cc-text); }+.pg-sub { margin: 0 0 20px; font-size: 13px; line-height: 1.58; color: var(--cc-dim); max-width: 32ch; }.pg-sub strong { color: var(--cc-text); font-weight: 600; }.pg-error {- margin: -8px 0 18px; padding: 9px 12px; width: 100%;- font-size: 12.5px; line-height: 1.45; color: var(--cc-text);- background: rgba(255, 255, 255, 0.05);- border: 1px solid var(--cc-edge); border-radius: var(--cc-radius-sm);+ margin: -6px 0 16px; padding: 8px 12px; width: 100%;+ font-size: 12px; line-height: 1.45; color: var(--cc-text);+ background: rgba(255, 255, 255, 0.04);+ border: 1px solid rgba(255, 255, 255, 0.14); border-radius: var(--cc-radius-sm);}-.pg-fine { margin: 12px 0 0; font-size: 11px; letter-spacing: 0.04em; color: var(--cc-faint); }+.pg-fine { margin: 10px 0 0; font-size: 10.5px; letter-spacing: 0.04em; color: var(--cc-faint); }/* buttons */.pg-btn {-webkit-appearance: none; appearance: none; cursor: pointer;- width: 100%; margin-top: 10px; padding: 13px 18px;- font-family: inherit; font-size: 13px; font-weight: 600; letter-spacing: 0.03em;+ width: 100%; margin-top: 9px; padding: 12px 18px;+ font-family: inherit; font-size: 12.5px; font-weight: 600; letter-spacing: 0.04em;border-radius: var(--cc-radius-sm); border: 1px solid var(--cc-edge);background: transparent; color: var(--cc-text);text-decoration: none; display: inline-flex; align-items: center; justify-content: center;- transition: transform 0.12s ease, background 0.18s ease, border-color 0.18s ease, box-shadow 0.18s ease;+ transition: transform 0.1s ease, background 0.16s ease, border-color 0.16s ease, box-shadow 0.16s ease;}.pg-btn:hover { border-color: var(--cc-edge-hi); background: rgba(255, 255, 255, 0.04); }.pg-btn:active { transform: translateY(1px); }.pg-btn:focus-visible { outline: none; box-shadow: 0 0 0 2px var(--cc-bg), 0 0 0 4px var(--cc-edge-hi); }.pg-btn-primary {+ position: relative; overflow: hidden;background: var(--cc-accent); color: var(--cc-ink); border-color: var(--cc-accent);}+.pg-btn-primary::after {+ content: ''; position: absolute; inset: 0; border-radius: inherit;+ background: linear-gradient(105deg, transparent 30%, rgba(0,0,0,0.07) 50%, transparent 70%);+ background-size: 250% 100%; background-position: 200% 0;+ animation: pg-shimmer 2.8s ease-in-out infinite;+}.pg-btn-primary:hover { background: #fff; box-shadow: var(--cc-glow); }+.pg-btn-primary:hover::after { animation: none; }.pg-btn-ghost { color: var(--cc-dim); }.pg-btn-ghost:hover { color: var(--cc-text); }-/* quiet text action — "use a different wallet" */+/* quiet text action — "try a different wallet" */.pg-link {-webkit-appearance: none; appearance: none; cursor: pointer;- margin: 12px 0 0; padding: 4px 6px;- font-family: inherit; font-size: 12px; font-weight: 500; letter-spacing: 0.02em;+ margin: 10px 0 0; padding: 4px 6px;+ font-family: inherit; font-size: 11.5px; font-weight: 500; letter-spacing: 0.02em;background: none; border: none; border-radius: var(--cc-radius-sm);- color: var(--cc-dim); text-decoration: underline; text-underline-offset: 3px;- transition: color 0.18s ease;+ color: var(--cc-faint); text-decoration: underline; text-underline-offset: 3px;+ transition: color 0.16s ease;}-.pg-link:hover { color: var(--cc-text); }+.pg-link:hover { color: var(--cc-dim); }.pg-link:focus-visible { outline: none; box-shadow: 0 0 0 2px var(--cc-bg), 0 0 0 4px var(--cc-edge-hi); }+/* step dots — 3-step progress indicator in working state */+.pg-steps {+ display: flex; gap: 7px; margin-bottom: 18px;+}+.pg-dot {+ width: 5px; height: 5px; border-radius: 50%;+ background: var(--cc-edge);+ transition: background 0.25s ease, transform 0.25s ease;+}+.pg-dot-done { background: rgba(255, 255, 255, 0.4); }+.pg-dot-active {+ background: var(--cc-accent);+ animation: pg-dot-pulse 1.1s ease-in-out infinite;+}+/* balance comparison (too-low state) */.pg-balance {- display: flex; align-items: center; justify-content: center; gap: 14px;- width: 100%; margin: 2px 0 18px; padding: 14px;+ display: flex; align-items: center; justify-content: center; gap: 12px;+ width: 100%; margin: 0 0 16px; padding: 13px;border: 1px solid var(--cc-edge-soft); border-radius: var(--cc-radius-sm);- background: rgba(255, 255, 255, 0.02);+ background: rgba(255, 255, 255, 0.015);}.pg-balance > div { display: flex; flex-direction: column; gap: 3px; }-.pg-balance-k { font-size: 10px; letter-spacing: 0.16em; text-transform: uppercase; color: var(--cc-faint); }-.pg-balance-v { font-size: 18px; font-weight: 700; color: var(--cc-text); font-variant-numeric: tabular-nums; }+.pg-balance-k { font-size: 9.5px; letter-spacing: 0.18em; text-transform: uppercase; color: var(--cc-faint); }+.pg-balance-v { font-size: 17px; font-weight: 700; color: var(--cc-dim); font-variant-numeric: tabular-nums; }+.pg-balance-low { color: var(--cc-faint); }.pg-balance-need { color: var(--cc-text); }-.pg-balance-sep { color: var(--cc-faint); font-size: 16px; }+.pg-balance-sep { color: var(--cc-edge); font-size: 14px; }/* spinner + success check */.pg-spinner {- width: 38px; height: 38px; margin-bottom: 18px; border-radius: 50%;- border: 2px solid var(--cc-edge); border-top-color: var(--cc-accent);- animation: pg-spin 0.8s linear infinite;+ width: 34px; height: 34px; margin-bottom: 16px; border-radius: 50%;+ border: 1.5px solid rgba(255, 255, 255, 0.1); border-top-color: var(--cc-text);+ animation: pg-spin 0.65s linear infinite;}.pg-check {- width: 56px; height: 56px; margin-bottom: 16px; border-radius: 50%;- display: grid; place-items: center; font-size: 26px; font-weight: 700;- color: var(--cc-ink); background: var(--cc-accent); box-shadow: var(--cc-glow);- animation: pg-pop 0.4s cubic-bezier(0.16, 0.84, 0.34, 1) both;+ width: 56px; height: 56px; margin-bottom: 14px; border-radius: 50%;+ display: grid; place-items: center; font-size: 24px; font-weight: 700;+ color: var(--cc-ink); background: var(--cc-accent);+ box-shadow: var(--cc-glow), 0 0 0 8px rgba(255, 255, 255, 0.06);+ animation: pg-pop 0.38s cubic-bezier(0.16, 0.84, 0.34, 1) both;}@keyframes pg-fade { from { opacity: 0; } to { opacity: 1; } }-@keyframes pg-rise { from { opacity: 0; transform: translateY(12px) scale(0.985); } to { opacity: 1; transform: none; } }+@keyframes pg-rise { from { opacity: 0; transform: translateY(8px) scale(0.992); } to { opacity: 1; transform: none; } }@keyframes pg-spin { to { transform: rotate(360deg); } }-@keyframes pg-pop { 0% { transform: scale(0.4); opacity: 0; } 100% { transform: scale(1); opacity: 1; } }+@keyframes pg-pop { 0% { transform: scale(0.5); opacity: 0; } 70% { transform: scale(1.06); } 100% { transform: scale(1); opacity: 1; } }+@keyframes pg-shimmer { 0% { background-position: 200% 0; } 100% { background-position: -200% 0; } }+@keyframes pg-icon-breathe { 0%, 100% { box-shadow: 0 0 0 0 rgba(255,255,255,0); } 50% { box-shadow: 0 0 0 7px rgba(255,255,255,0.05); } }+@keyframes pg-dot-pulse { 0%, 100% { transform: scale(1); opacity: 1; } 50% { transform: scale(1.5); opacity: 0.7; } }@media (prefers-reduced-motion: reduce) {.pg-root, .pg-card, .pg-check { animation: none; }- .pg-spinner { animation-duration: 1.4s; }+ .pg-spinner { animation-duration: 1.2s; }+ .pg-btn-primary::after, .pg-card[data-state="connect"] .pg-icon, .pg-dot-active { animation: none; }}@media (max-width: 480px) {- .pg-card { padding: 28px 20px 24px; }- .pg-title { font-size: 19px; }+ .pg-card { padding: 26px 18px 22px; }+ .pg-title { font-size: 18px; }+ .pg-sub { font-size: 12.5px; }}/* ───────────────────────── Cosmetics shop (R21) ─────────────────────────diff --git a/src/game/play-auth.js b/src/game/play-auth.jsindex 1852e6355..1066d4746 100644--- a/src/game/play-auth.js+++ b/src/game/play-auth.js@@ -60,8 +60,16 @@ export function hasWallet() {* @returns {Promise<{ nonce: string, expiresAt: string, required: boolean, mint: string, minBalance: number }>}*/export async function fetchPlayConfig() {- const res = await fetch(NONCE_URL, { credentials: 'include', headers: { accept: 'application/json' } });- const body = await res.json().catch(() => null);+ let res, body;+ try {+ res = await fetch(NONCE_URL, { credentials: 'include', headers: { accept: 'application/json' } });+ body = await res.json().catch(() => null);+ } catch {+ throw new PlayAuthError('nonce_unavailable', 'Cannot reach the server. Check your connection and try again.');+ }+ if (res.status === 429) {+ throw new PlayAuthError('nonce_unavailable', 'Server is busy — try again in a moment.');+ }if (!res.ok || !body?.data?.nonce) {throw new PlayAuthError('nonce_unavailable', body?.error_description || 'Could not start sign-in. Try again.');}diff --git a/src/game/play-gate.js b/src/game/play-gate.jsindex 1c6cea1e4..60e6c4115 100644--- a/src/game/play-gate.js+++ b/src/game/play-gate.js@@ -214,8 +214,8 @@ class Gate {_html(view) {const card = (inner) => `<div class="pg-backdrop"></div>- <div class="pg-card">- <div class="pg-brand"><img loading="lazy" decoding="async" src="/three.svg" alt="" width="30" height="30"><span>COIN COMMUNITIES</span></div>+ <div class="pg-card" data-state="${esc(view.state)}">+ <div class="pg-brand"><img loading="eager" decoding="async" src="/three.svg" alt="" width="30" height="30"><span>COIN COMMUNITIES</span></div>${inner}</div>`;@@ -228,7 +228,7 @@ class Gate {return card(`<div class="pg-icon">${SVG.wallet}</div><h1 class="pg-title">Install a Solana wallet</h1>- <p class="pg-sub">Your wallet is your account — no email, no password. Install Phantom, then come back and retry.</p>+ <p class="pg-sub">Your wallet is your account — no email, no password. Install <strong>Phantom</strong>, then come back and retry.</p><a class="pg-btn pg-btn-primary" href="${PHANTOM_INSTALL}" target="_blank" rel="noopener noreferrer">Get Phantom</a><button class="pg-btn pg-btn-ghost" data-act="retry">I've installed it — retry</button>`);@@ -236,19 +236,34 @@ class Gate {return card(`<div class="pg-icon">${SVG.key}</div><h1 class="pg-title">Sign in to play</h1>- <p class="pg-sub">Connect your Solana wallet and approve a signature to prove it's yours. You'll need at least <strong>${esc(String(min))} ${tokenLabel}</strong> to enter. This never moves any funds.</p>+ <p class="pg-sub">Connect your wallet and sign a message to prove ownership. You'll need at least <strong>${esc(String(min))} ${tokenLabel}</strong>. Nothing moves on-chain.</p>${view.error ? `<p class="pg-error" role="alert">${esc(view.error)}</p>` : ''}<button class="pg-btn pg-btn-primary" data-act="connect">Connect wallet</button>${view.onSwitch ? `<button class="pg-link" data-act="switch">Use a different wallet</button>` : ''}<p class="pg-fine">We will never ask for your seed phrase.</p>`);case 'working': {- const labels = { connecting: 'Connecting your wallet…', signing: 'Approve the signature in your wallet…', verifying: 'Checking your token balance on-chain…' };+ const stageIndex = { connecting: 0, signing: 1, verifying: 2 }[view.stage] ?? 0;+ const dots = [0, 1, 2].map((i) => {+ const cls = i < stageIndex ? 'pg-dot pg-dot-done' : i === stageIndex ? 'pg-dot pg-dot-active' : 'pg-dot';+ return `<span class="${cls}" aria-hidden="true"></span>`;+ }).join('');+ const labels = {+ connecting: 'Connecting your wallet…',+ signing: 'Approve the signature…',+ verifying: 'Checking your balance…',+ };+ const subs = {+ connecting: 'Opening your wallet — this only takes a moment.',+ signing: 'Your wallet is waiting for your approval.',+ verifying: 'Reading on-chain balance — almost there.',+ };const label = labels[view.stage] || 'Working…';return card(`+ <div class="pg-steps" aria-label="Step ${stageIndex + 1} of 3">${dots}</div><div class="pg-spinner" aria-live="polite" aria-label="${esc(label)}"></div><h1 class="pg-title">${esc(label)}</h1>- <p class="pg-sub">${view.stage === 'signing' ? 'Check your wallet — it is waiting for your approval.' : 'This only takes a moment.'}</p>`);+ <p class="pg-sub">${esc(subs[view.stage] || 'This only takes a moment.')}</p>`);}case 'low': {@@ -259,31 +274,31 @@ class Gate {return card(`<div class="pg-icon">${SVG.ticket}</div><h1 class="pg-title">Not enough ${displaySym}</h1>- <p class="pg-sub">Entry requires <strong>${need} ${displaySym}</strong>. Your wallet has <strong>${bal} ${displaySym}</strong>. Top up then recheck — no need to sign again.</p>+ <p class="pg-sub">You need <strong>${need} ${displaySym}</strong> to enter. Top up, then recheck — no need to sign again.</p><div class="pg-balance" aria-label="Balance comparison">- <div><span class="pg-balance-k">You have</span><span class="pg-balance-v">${bal}</span></div>+ <div><span class="pg-balance-k">You have</span><span class="pg-balance-v pg-balance-low">${bal}</span></div><div class="pg-balance-sep" aria-hidden="true">→</div><div><span class="pg-balance-k">Required</span><span class="pg-balance-v pg-balance-need">${need}</span></div></div>${view.onAcquire ? `<button class="pg-btn pg-btn-primary" data-act="acquire">Get ${displaySym}</button>` : ''}<button class="pg-btn ${view.onAcquire ? 'pg-btn-ghost' : 'pg-btn-primary'}" data-act="recheck">Recheck balance</button>- ${view.onSwitch ? `<button class="pg-link" data-act="switch">Use a different wallet</button>` : ''}`);+ ${view.onSwitch ? `<button class="pg-link" data-act="switch">Try a different wallet</button>` : ''}`);}case 'granted':return card(`<div class="pg-check" aria-label="Access granted">✓</div><h1 class="pg-title">You're in</h1>- <p class="pg-sub">Wallet verified${view.balance != null ? ` — ${fmt(view.balance)} ${view.symbol ? '$' + esc(view.symbol) : tokenLabel}` : ''}. Entering the world…</p>`);+ <p class="pg-sub">Verified${view.balance != null ? ` · ${fmt(view.balance)} ${view.symbol ? '$' + esc(view.symbol) : tokenLabel}` : ''}. Entering the world…</p>`);case 'error':default:return card(`<div class="pg-icon">${SVG.warn}</div>- <h1 class="pg-title">Something went wrong</h1>+ <h1 class="pg-title">Sign-in failed</h1><p class="pg-sub" role="alert">${esc(view.error || 'Please try again.')}</p><button class="pg-btn pg-btn-primary" data-act="retry">Try again</button>- ${view.onSwitch ? `<button class="pg-link" data-act="switch">Use a different wallet</button>` : ''}`);+ ${view.onSwitch ? `<button class="pg-link" data-act="switch">Try a different wallet</button>` : ''}`);}}}diff --git a/src/pointcloud-viewer.js b/src/pointcloud-viewer.jsnew file mode 100644index 000000000..a9145eb31--- /dev/null+++ b/src/pointcloud-viewer.js@@ -0,0 +1,213 @@+// PointCloudViewer — render a coloured 3D point cloud (.ply) in the browser.+//+// The output format of the Scene Capture pipeline (workers/model-video2scene,+// 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.++import {+ Scene,+ PerspectiveCamera,+ WebGLRenderer,+ Points,+ BufferGeometry,+ BufferAttribute,+ PointsMaterial,+ Color,+ Box3,+ Sphere,+ Vector3,+} from 'three';+import { OrbitControls } from 'three/examples/jsm/controls/OrbitControls.js';+import { PLYLoader } from 'three/examples/jsm/loaders/PLYLoader.js';++export class PointCloudViewer {+ constructor(host, { background = '#0a0a0a' } = {}) {+ this.host = host;+ this._disposed = false;+ this._needsRender = true;+ this._settleUntil = 0;++ this.scene = new Scene();+ this.scene.background = new Color(background);++ 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' });+ this.renderer.setPixelRatio(Math.min(window.devicePixelRatio || 1, 2));+ host.appendChild(this.renderer.domElement);++ this.controls = new OrbitControls(this.camera, this.renderer.domElement);+ this.controls.enableDamping = true;+ this.controls.dampingFactor = 0.08;+ this.controls.rotateSpeed = 0.7;+ this.controls.addEventListener('change', () => { this._needsRender = true; });++ this.points = null;+ this.material = new PointsMaterial({ size: 0.012, sizeAttenuation: true, vertexColors: true });+ this._home = { position: new Vector3(0, 0, 4), target: new Vector3(0, 0, 0) };+ this._radius = 1;++ this._onResize = this._resize.bind(this);+ window.addEventListener('resize', this._onResize);+ this._resize();+ this._loop = this._tick.bind(this);+ requestAnimationFrame(this._loop);+ }++ _resize() {+ const w = this.host.clientWidth || 1;+ const h = this.host.clientHeight || 1;+ this.renderer.setSize(w, h, false);+ this.camera.aspect = w / h;+ this.camera.updateProjectionMatrix();+ this._needsRender = true;+ }++ _tick() {+ if (this._disposed) return;+ requestAnimationFrame(this._loop);+ const damping = this.controls.enableDamping && performance.now() < this._settleUntil;+ if (this._needsRender || damping) {+ this.controls.update();+ this.renderer.render(this.scene, this.camera);+ this._needsRender = false;+ }+ }++ // Parse a PLY ArrayBuffer into a Points cloud and frame it. Returns { count }.+ loadBuffer(buffer) {+ const geom = new PLYLoader().parse(buffer);+ return this._setGeometry(geom);+ }++ setGeometryFromArrays(positions, colors) {+ const geom = new BufferGeometry();+ geom.setAttribute('position', new BufferAttribute(positions, 3));+ if (colors) geom.setAttribute('color', new BufferAttribute(colors, 3, true));+ return this._setGeometry(geom);+ }++ _setGeometry(geom) {+ if (this.points) {+ this.scene.remove(this.points);+ 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));+ }+ geom.computeBoundingBox();+ 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;++ this.points = new Points(geom, this.material);+ this.scene.add(this.points);++ this._frame();+ return { count: geom.getAttribute('position').count };+ }++ _frame() {+ const r = this._radius;+ const dist = r * 2.6;+ this._home.position.set(dist * 0.5, dist * 0.35, dist);+ this._home.target.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);+ this.camera.far = r * 100;+ this.camera.updateProjectionMatrix();+ this.controls.update();+ this._settle();+ }++ recenter() {+ if (!this.points) return;+ 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;+ }++ _settle() {+ this._settleUntil = performance.now() + 600;+ this._needsRender = true;+ }++ dispose() {+ this._disposed = true;+ window.removeEventListener('resize', this._onResize);+ this.controls.dispose();+ if (this.points) this.points.geometry.dispose();+ this.material.dispose();+ this.renderer.dispose();+ if (this.renderer.domElement?.parentNode) {+ this.renderer.domElement.parentNode.removeChild(this.renderer.domElement);+ }+ }+}++// ── Synthetic sample cloud ────────────────────────────────────────────────────+// Procedurally exercises the renderer with a recognisable interior — a floor,+// two walls, and a centre object — in monochrome greys. Clearly synthetic, not a+// real capture; mirrors the labelled-sample convention used by the splat viewer.+export function sampleRoomCloud(count = 90_000) {+ const positions = new Float32Array(count * 3);+ const colors = new Float32Array(count * 3);+ const c = new Color();+ let i = 0;+ const put = (x, y, z, shade) => {+ positions[i * 3] = x; positions[i * 3 + 1] = y; positions[i * 3 + 2] = z;+ c.setHSL(0, 0, shade);+ colors[i * 3] = c.r; colors[i * 3 + 1] = c.g; colors[i * 3 + 2] = c.b;+ 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);+ };+ for (let k = 0; k < count; k++) {+ const r = rnd(k + 1);+ const region = rnd(k * 1.7 + 3);+ const jitter = (rnd(k * 2.3 + 7) - 0.5) * 0.04;+ if (region < 0.34) {+ // floor+ put((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 wall+ put((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 wall+ put(-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 column+ const 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);+ put(Math.cos(theta) * rad, t * 1.8 - 1, Math.sin(theta) * rad - 0.2, 0.55 + r * 0.2);+ }+ }+ return { positions, colors, count: i };+}diff --git a/src/pulse.css b/src/pulse.cssindex f00b02487..344f0d872 100644--- a/src/pulse.css+++ b/src/pulse.css@@ -104,6 +104,15 @@.px-market-body { display: grid; grid-template-columns: 1.4fr 1fr; gap: var(--space-md, 16px); align-items: start; }.px-market-spark .px-spark-bar--mkt { background: rgba(255,255,255,.28); }.px-market-spark .px-spark-col:hover .px-spark-bar--mkt { background: var(--ink, #e8e8e8); }+/* Trading panel: a touch dimmer than the marketplace bars so the two read distinct+ in the same monochrome ramp; today's bar still resolves to full ink. */+.px-trading .px-spark-bar--trade { background: rgba(255,255,255,.22); }+.px-trading .px-spark-col:hover .px-spark-bar--trade { background: var(--ink, #e8e8e8); }+.px-trading .px-spark-col--now .px-spark-bar--trade { background: var(--ink-bright, #fff); }+/* Realized P&L sign — monochrome: the glyph and weight carry direction, never colour.+ A gain reads bright + tight; a loss reads dim. No green/red anywhere. */+.px-pnl--up { color: var(--ink-bright, #fff); letter-spacing: -.01em; }+.px-pnl--down { color: var(--ink-dim, #9a9a9a); }.px-skill-row { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 7px 8px; border-radius: var(--radius-md, 9px); }.px-skill-row:hover { background: var(--surface-2, rgba(255,255,255,.05)); }.px-skill-name { font-size: var(--text-sm, .8rem); font-weight: 600; color: var(--ink, #e8e8e8); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }diff --git a/src/pulse.js b/src/pulse.jsindex 50e2df791..0c2745bdc 100644--- a/src/pulse.js+++ b/src/pulse.js@@ -236,8 +236,12 @@ function renderMarketplace(d) {$('px-mkt-repeat').textContent = fmtPct(d.repeat_buyer_rate_7d);$('px-mkt-repeat-sub').textContent = `${d.repeat_buyers_7d || 0}/${d.buyers_7d || 0} buyers · 7d`;$('px-mkt-pairs').textContent = String(w7.pairs || 0);- $('px-mkt-take').textContent = d.fee_bps > 0 ? fmtThree(w7.take_rate_three) : '—';- $('px-mkt-take-sub').textContent = d.fee_bps > 0 ? `$THREE earned · 7d` : 'fee disabled';+ // Take-rate = fees ACTUALLY charged on-chain (real, persisted per purchase).+ const take7 = w7.take_rate_three || 0;+ $('px-mkt-take').textContent = take7 > 0 ? fmtThree(take7) : '—';+ $('px-mkt-take-sub').textContent = take7 > 0+ ? '$THREE earned · 7d'+ : (d.fee_bps > 0 ? 'no fees yet · 7d' : 'fee off');renderMarketSpark(d.series_7d);@@ -297,6 +301,109 @@ function renderMarketSpark(series) {.join('');}+async function loadTrading() {+ try {+ const res = await fetch(`/api/pulse?view=trading&network=${state.network}`, { headers: { accept: 'application/json' } });+ if (!res.ok) throw new Error(`trading ${res.status}`);+ const { data } = await res.json();+ renderTrading(data);+ } catch (e) {+ log.warn('trading failed', e?.message);+ // Supplementary panel — never block the page; just hide it on failure.+ $('px-trading')?.setAttribute('hidden', '');+ }+}++// Signed SOL → compact ledger label with an explicit sign and direction glyph.+// Monochrome by design: the arrow carries the sign, never colour.+function fmtSignedSol(n) {+ const v = Number(n) || 0;+ if (v === 0) return '◎0';+ const mag = Math.abs(v);+ const body = mag >= 1 ? mag.toFixed(2) : mag.toFixed(3).replace(/0+$/, '').replace(/\.$/, '');+ return `${v > 0 ? '▲ +' : '▼ −'}◎${body}`;+}++function renderTrading(d) {+ const panel = $('px-trading');+ if (!panel) return;+ // Guard against a deploy-skew response (e.g. an older backend answering this view+ // with the feed shape): without the windowed aggregates there's nothing honest to+ // show, so hide rather than render a panel full of em-dashes.+ if (!d || (!d.window_24h && !d.window_7d)) { panel.hidden = true; return; }+ const w24 = d.window_24h || {};+ const w7 = d.window_7d || {};+ const pnl = d.realized_pnl_7d || {};+ panel.hidden = false;++ $('px-trade-c24').textContent = fmtNum(w24.trades);+ $('px-trade-c24-sub').textContent = `${w24.traders || 0} wallet${w24.traders === 1 ? '' : 's'}`;+ $('px-trade-c7').textContent = fmtNum(w7.trades);+ $('px-trade-c7-sub').textContent = `${w7.buys || 0} buy · ${w7.sells || 0} sell`;+ $('px-trade-dep7').textContent = fmtSol(w7.deployed_sol);+ $('px-trade-dep7-sub').textContent = w7.deployed_usd > 0 ? `${fmtUsd(w7.deployed_usd)} · into buys` : 'into buys';+ $('px-trade-avg').textContent = fmtSol(w7.avg_trade_sol);+ $('px-trade-act').textContent = fmtNum(w24.traders);++ // Realized P&L — only meaningful once positions have closed. Until then it's an+ // honest "—" rather than a fake zero, so a fresh pilot reads as "no closes yet".+ const pnlEl = $('px-trade-pnl');+ const pnlSub = $('px-trade-pnl-sub');+ const pnlTag = $('px-trade-pnl-tag');+ if (pnl.closed_positions > 0) {+ pnlEl.textContent = fmtSignedSol(pnl.net_sol);+ pnlEl.classList.toggle('px-pnl--up', pnl.net_sol > 0);+ pnlEl.classList.toggle('px-pnl--down', pnl.net_sol < 0);+ pnlSub.textContent = `${pnl.closed_positions} closed · ${fmtPct(pnl.win_rate)} win`;+ pnlTag.textContent = `${pnl.closed_positions} closed · 7d`;+ pnlTag.classList.remove('px-market-tag--off');+ } else {+ pnlEl.textContent = '—';+ pnlEl.classList.remove('px-pnl--up', 'px-pnl--down');+ pnlSub.textContent = 'no closes yet';+ pnlTag.textContent = 'no closes · 7d';+ pnlTag.classList.add('px-market-tag--off');+ }++ renderTradeSpark(d.series_7d);++ // Top traders — the wallets actually putting capital to work.+ const host = $('px-trade-traders');+ if (d.top_traders?.length) {+ host.innerHTML = d.top_traders+ .map((a) => agentCardHTML(a, `${a.trades} <small>trade${a.trades === 1 ? '' : 's'} · ${fmtSol(a.deployed_sol)}</small>`))+ .join('');+ wireWalletChips(host);+ } else {+ host.innerHTML = `<p class="px-lb-empty">No agent trades in the last 7 days. Fund a treasury and enable circulation to start the loop. <a href="/admin/launcher">Open controls.</a></p>`;+ }+}++// 7-day trade-count sparkline; today highlighted, bars scale to the busiest day.+function renderTradeSpark(series) {+ const host = $('px-trade-spark');+ const totalEl = $('px-trade-spark-total');+ if (!host) return;+ 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'}`;+ 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 = days+ .map((d, i) => {+ const n = d.trades || 0;+ const h = n > 0 ? Math.max(6, Math.round((n / peak) * 100)) : 2;+ const today = i === days.length - 1;+ return (+ `<div class="px-spark-col${today ? ' px-spark-col--now' : ''}" title="${esc(d.day)}: ${n} trade${n === 1 ? '' : 's'} · ${fmtSol(d.deployed_sol)}">` ++ `<div class="px-spark-bar px-spark-bar--trade" style="height:${h}%"></div>` ++ `<span class="px-spark-lbl">${esc(d.label)}</span>` ++ `</div>`+ );+ })+ .join('');+}+function mountFeed() {const host = $('px-feed');if (state.pulse) state.pulse.destroy();@@ -323,6 +430,7 @@ function wireNetworkToggle() {$('px-net-label').textContent = net;state.pulse?.setNetwork(net);loadStats();+ loadTrading();loadMarketplace();});}@@ -332,9 +440,10 @@ function init() {wireNetworkToggle();mountFeed();loadStats();+ loadTrading();loadMarketplace();// Refresh stats on a slow cadence; the feed has its own live delta polling.- setInterval(() => { if (!document.hidden) { loadStats(); loadMarketplace(); } }, 60_000);+ setInterval(() => { if (!document.hidden) { loadStats(); loadTrading(); loadMarketplace(); } }, 60_000);}if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);diff --git a/src/scene-capture.js b/src/scene-capture.jsnew file mode 100644index 000000000..600564f58--- /dev/null+++ b/src/scene-capture.js@@ -0,0 +1,250 @@+// Scene Capture — drive the video → 3D point-cloud pipeline and render the result.+//+// Backend: POST /api/scene-capture { video_url, … } → 202 { job_id }, then poll+// GET /api/scene-capture?job=<id> until done. The result is a .ply point cloud we+// render with PointCloudViewer. Every state is designed: idle, submitting,+// processing (with elapsed timer + stage hints), live, and error. When the+// backend isn't configured, the sample cloud still proves the renderer end-to-end.++import { PointCloudViewer, sampleRoomCloud } from './pointcloud-viewer.js';++const $ = (s, r = document) => r.querySelector(s);++let viewer = null;+let pollTimer = null;+let elapsedTimer = null;+let downloadUrl = null;++const STAGE = () => $('#pc-stage');+const HOST = () => $('#pc-host');++// ── viewer lifecycle ──────────────────────────────────────────────────────────+function ensureViewer() {+ if (!viewer) viewer = new PointCloudViewer(HOST(), { background: '#0a0a0a' });+ return viewer;+}++// ── overlay states ────────────────────────────────────────────────────────────+function showOnly(id) {+ for (const k of ['pc-idle', 'pc-loading', 'pc-error']) {+ const node = $(`#${k}`);+ if (node) node.hidden = k !== id;+ }+ if (id !== null) $('#pc-hud').hidden = true;+}+function setLoading(title, sub) {+ $('#pc-loading-title').textContent = title;+ if (sub != null) $('#pc-loading-sub').textContent = sub;+ showOnly('pc-loading');+}+function setError(title, sub) {+ $('#pc-error-title').textContent = title;+ $('#pc-error-sub').textContent = sub || '';+ showOnly('pc-error');+}+function setLive(label) {+ $('#pc-hud-label').textContent = label;+ $('#pc-hud').hidden = false;+ for (const k of ['pc-idle', 'pc-loading', 'pc-error']) $(`#${k}`).hidden = true;+}++function setDownload(url, filename) {+ const btn = $('#pc-download');+ if (downloadUrl && downloadUrl !== url) URL.revokeObjectURL(downloadUrl);+ downloadUrl = url;+ if (!url) { btn.hidden = true; return; }+ btn.href = url;+ btn.download = filename || 'scene.ply';+ btn.hidden = false;+}++function fmt(n) { return n.toLocaleString('en-US'); }++// ── render a point cloud from an ArrayBuffer ──────────────────────────────────+function renderBuffer(buffer, label, downloadName) {+ setLoading('Decoding point cloud…', `${(buffer.byteLength / 1024 / 1024).toFixed(1)} MB`);+ try {+ const v = ensureViewer();+ const { count } = v.loadBuffer(buffer);+ setLive(`${label} · ${fmt(count)} points`);+ setDownload(URL.createObjectURL(new Blob([buffer])), downloadName);+ $('#pc-size').disabled = false;+ } catch (err) {+ console.error('[scene-capture] decode failed', err);+ setError('That isn’t a valid point cloud', 'Expected a binary or ASCII .ply with xyz + rgb vertices.');+ }+}++async function loadFromUrl(url, label) {+ let parsed;+ try { parsed = new URL(url, location.href); } catch { setError('That doesn’t look like a URL', url); return; }+ setLoading('Fetching point cloud…', parsed.hostname);+ try {+ const res = await fetch(parsed.href);+ if (!res.ok) throw new Error(`HTTP ${res.status}`);+ const buffer = await res.arrayBuffer();+ renderBuffer(buffer, label || 'Point cloud', parsed.pathname.split('/').pop() || 'scene.ply');+ } catch (err) {+ console.error('[scene-capture] fetch failed', err);+ setError('Couldn’t fetch that point cloud', `${err.message}. The host may block cross-origin reads (CORS).`);+ }+}++async function loadFromFile(file) {+ setLoading('Reading file…', file.name);+ try {+ const buffer = await file.arrayBuffer();+ renderBuffer(buffer, file.name.replace(/\.ply$/i, ''), file.name);+ } catch (err) {+ setError('Couldn’t read that file', err.message);+ }+}++function loadSample() {+ setLoading('Building sample cloud…', 'Synthetic interior · monochrome');+ const v = ensureViewer();+ const { positions, colors, count } = sampleRoomCloud();+ v.setGeometryFromArrays(positions, colors);+ setLive(`Synthetic interior · ${fmt(count)} points`);+ setDownload(null);+ $('#pc-size').disabled = false;+}++// ── reconstruction job (real backend) ─────────────────────────────────────────+function stopPolling() {+ if (pollTimer) { clearTimeout(pollTimer); pollTimer = null; }+ if (elapsedTimer) { clearInterval(elapsedTimer); elapsedTimer = null; }+}++function processingCopy(seconds, eta) {+ // Honest, changing stage hints keyed to elapsed time — no fake progress bar.+ const stage = seconds < 8 ? 'Sampling frames and warming the model…'+ : seconds < 25 ? 'Streaming geometry — grounding coordinates and correcting drift…'+ : 'Fusing world points into a dense cloud…';+ const etaTxt = eta ? ` · ~${eta}s typical` : '';+ setLoading(`Reconstructing · ${seconds}s`, `${stage}${etaTxt}`);+}++async function startCapture() {+ const url = $('#pc-url').value.trim();+ if (!url) { $('#pc-url').focus(); return; }++ stopPolling();+ $('#pc-run').disabled = true;+ setDownload(null);+ $('#pc-size').disabled = true;+ setLoading('Submitting…', 'Validating the video URL.');++ const params = {+ video_url: url,+ mode: $('#pc-mode').value,+ fps: Number($('#pc-fps').value) || 8,+ keyframe_interval: Number($('#pc-kf').value) || 4,+ mask_sky: $('#pc-sky').checked,+ };++ let started;+ try {+ const res = await fetch('/api/scene-capture', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify(params),+ });+ started = await res.json().catch(() => ({}));+ if (res.status === 503) {+ setError('Scene capture isn’t live here', `${started.message || 'The reconstruction worker is not configured on this deployment.'} You can still load a .ply by URL or upload, or try the sample.`);+ $('#pc-run').disabled = false;+ return;+ }+ if (!res.ok) throw new Error(started.message || `HTTP ${res.status}`);+ } catch (err) {+ setError('Couldn’t start reconstruction', err.message);+ $('#pc-run').disabled = false;+ return;+ }++ const jobId = started.job_id;+ const eta = started.eta_seconds || 0;+ const t0 = Date.now();+ processingCopy(0, eta);+ elapsedTimer = setInterval(() => {+ processingCopy(Math.round((Date.now() - t0) / 1000), eta);+ }, 1000);++ const poll = async () => {+ let data;+ try {+ const res = await fetch(`/api/scene-capture?job=${encodeURIComponent(jobId)}`);+ data = await res.json().catch(() => ({}));+ } catch {+ pollTimer = setTimeout(poll, 3000);+ return;+ }+ if (data.status === 'done' && data.result_url) {+ stopPolling();+ $('#pc-run').disabled = false;+ const label = data.frames ? `Captured · ${fmt(data.frames)} frames` : 'Captured scene';+ await loadFromUrl(data.result_url, label);+ return;+ }+ if (data.status === 'failed') {+ stopPolling();+ $('#pc-run').disabled = false;+ setError('Reconstruction failed', data.error || 'The worker reported a failure. Try a shorter or steadier clip.');+ return;+ }+ pollTimer = setTimeout(poll, 3000);+ };+ pollTimer = setTimeout(poll, 3000);+}++// ── wiring ────────────────────────────────────────────────────────────────────+function init() {+ if (!STAGE()) return;++ $('#pc-run').addEventListener('click', startCapture);+ $('#pc-url').addEventListener('keydown', (e) => { if (e.key === 'Enter') startCapture(); });++ $('#pc-load-url').addEventListener('click', () => {+ const u = $('#pc-ply-url').value.trim();+ if (u) loadFromUrl(u);+ });+ $('#pc-ply-url').addEventListener('keydown', (e) => {+ if (e.key === 'Enter') { const u = e.target.value.trim(); if (u) loadFromUrl(u); }+ });++ $('#pc-pick').addEventListener('click', () => $('#pc-file').click());+ $('#pc-idle').addEventListener('click', () => $('#pc-file').click());+ $('#pc-file').addEventListener('change', (e) => {+ const file = e.target.files?.[0];+ if (file) loadFromFile(file);+ e.target.value = '';+ });++ $('#pc-sample').addEventListener('click', loadSample);+ $('#pc-error-retry').addEventListener('click', loadSample);+ $('#pc-recenter').addEventListener('click', () => viewer?.recenter());+ $('#pc-size').addEventListener('input', (e) => viewer?.setPointScale(Number(e.target.value)));++ // Drag & drop a .ply onto the stage.+ const stage = STAGE();+ ['dragenter', 'dragover'].forEach((ev) => stage.addEventListener(ev, (e) => {+ e.preventDefault(); stage.classList.add('is-dragover');+ }));+ stage.addEventListener('dragleave', (e) => { if (e.target === stage) stage.classList.remove('is-dragover'); });+ stage.addEventListener('drop', (e) => {+ e.preventDefault(); stage.classList.remove('is-dragover');+ const file = e.dataTransfer?.files?.[0];+ if (file) loadFromFile(file);+ });++ // Deep links: ?src=<ply-url> renders directly; ?video=<url> pre-fills capture.+ const p = new URLSearchParams(location.search);+ 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');++ window.addEventListener('beforeunload', () => { stopPolling(); setDownload(null); viewer?.dispose(); });+}++if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', init);+else init();diff --git a/tests/agent-screen-ratelimit.test.js b/tests/agent-screen-ratelimit.test.jsnew file mode 100644index 000000000..62ea76b5e--- /dev/null+++ b/tests/agent-screen-ratelimit.test.js@@ -0,0 +1,42 @@+/**+ * Regression guard for the live-agent screen feature's rate limiters.+ *+ * The screen feed is wired across three endpoints that all gate on the same+ * generic per-IP bucket: api/agent-screen-active.js (roster), agent-screen-push.js+ * (frame ingest), agent-task.js (task queue). A previous revision referenced+ * `limits.apiIp` — a key that did not exist on the limits object — so every one of+ * those endpoints threw `limits.apiIp is not a function` uncaught, producing a hard+ * FUNCTION_INVOCATION_FAILED in production and silently killing the entire feature.+ *+ * These tests pin the limiter contract so that regression can't recur unnoticed.+ */++import { describe, it, expect } from 'vitest';+import { limits } from '../api/_lib/rate-limit.js';++describe('limits.apiIp — generic app endpoint bucket', () => {+ it('exists and is callable', () => {+ expect(typeof limits.apiIp).toBe('function');+ });++ it('resolves a limiter decision for a bare call (roster poll shape)', async () => {+ const res = await limits.apiIp('1.2.3.4');+ expect(res).toBeTruthy();+ expect(typeof res.success).toBe('boolean');+ });++ it('honors a per-caller override (push stream / task queue shapes)', async () => {+ const push = await limits.apiIp('1.2.3.5', { limit: 360, window: '60s' });+ const task = await limits.apiIp('1.2.3.6', { limit: 20, window: '60s' });+ expect(typeof push.success).toBe('boolean');+ expect(typeof task.success).toBe('boolean');+ });++ it('keeps the buckets the screen feature depends on present', () => {+ // Every limiter referenced by the screen/task endpoints must exist, or the+ // endpoint that calls it 500s at the limiter line before any work happens.+ for (const key of ['apiIp', 'mcpIp']) {+ expect(typeof limits[key]).toBe('function');+ }+ });+});diff --git a/tests/launcher-engine.test.js b/tests/launcher-engine.test.jsnew file mode 100644index 000000000..2690b0c09--- /dev/null+++ b/tests/launcher-engine.test.js@@ -0,0 +1,136 @@+import { describe, it, expect, vi, beforeEach } from 'vitest';++// Shared, test-controlled state for the fake DB + mocks. vi.hoisted lets the+// mock factories (hoisted above imports) read/write it.+const H = vi.hoisted(() => ({+ configs: [],+ agent: { id: 'agent-1', user_id: 'user-1', name: 'Nova', avatar_id: 'av-1', solana_address: 'AgentAddr1111' },+ queueCount: 5,+ lastRun: [], // [] ⇒ cadence not gated+ fund: { ok: true, signature: 'fund-sig', lamports: 30_000_000 },+ masterSol: 10,+}));++// Query-aware fake `sql`: routes by the joined template text, ignores values.+vi.mock('../api/_lib/db.js', () => {+ const sql = (strings, ...vals) => {+ if (!Array.isArray(strings)) return { __frag: true }; // sql(identifier) fragment+ const q = strings.join(' ').toLowerCase();+ const rows =+ q.includes('create ') || q.includes('insert into launcher_config') ? []+ : q.includes('from launcher_config where enabled') ? H.configs+ : q.includes('select created_at from launcher_runs') ? H.lastRun+ : q.includes('as c from launcher_runs') ? [{ c: 0 }]+ : q.includes('as c from launcher_queue') ? [{ c: H.queueCount }]+ : q.includes('from launcher_queue q') ? [H.agent]+ : q.includes('insert into launcher_runs') ? [{ id: 'run-1' }]+ : q.includes('select status from launcher_runs') ? []+ : [];+ return Promise.resolve(rows);+ };+ return { sql, isDbUnavailableError: () => false };+});++vi.mock('../api/_lib/launcher-funding.js', () => ({+ masterBalanceSol: vi.fn(async () => H.masterSol),+ dailySpentSol: vi.fn(async () => 0),+ fundAgentForLaunch: vi.fn(async () => H.fund),+}));++vi.mock('../api/_lib/launcher-sources.js', () => ({+ pickSource: vi.fn(async () => ({+ kind: 'random',+ name: 'Turbo Otter',+ symbol: 'TURBOTTR',+ description: 'test coin',+ trigger_source: 'random',+ trigger_detail: { top_narrative: 'otters' },+ })),+}));++vi.mock('../api/_lib/auth.js', () => ({ createSession: vi.fn(async () => 'session-token') }));+vi.mock('../api/_lib/agent-pumpfun.js', () => ({ solanaConnection: vi.fn(() => ({})) }));++import { runLauncherTick } from '../api/_lib/launcher-engine.js';+import { fundAgentForLaunch } from '../api/_lib/launcher-funding.js';++function makeConfig(over = {}) {+ return {+ id: 'cfg-global', scope: 'global', user_id: null,+ enabled: true, dry_run: true, paused: false, pause_reason: null,+ mode: 'random', sources: [], categories: [],+ target_cadence_seconds: 60, max_per_hour: 30,+ per_launch_sol: 0.03, dev_buy_sol: 0, daily_sol_cap: 1,+ buyback_bps: 5000, network: 'devnet', ...over,+ };+}++beforeEach(() => {+ H.configs = [];+ H.lastRun = [];+ H.queueCount = 5;+ H.fund = { ok: true, signature: 'fund-sig', lamports: 30_000_000 };+ H.masterSol = 10;+ vi.clearAllMocks();+});++describe('runLauncherTick — disabled', () => {+ it('is fully inert when no config is enabled (no scopes, no spend)', async () => {+ H.configs = [];+ const out = await runLauncherTick();+ expect(out.ok).toBe(true);+ expect(out.scopes).toBe(0);+ expect(out.results).toEqual([]);+ expect(fundAgentForLaunch).not.toHaveBeenCalled();+ });+});++describe('runLauncherTick — dry run', () => {+ it('selects a coin + agent and records a dry_run without moving SOL', async () => {+ H.configs = [makeConfig({ dry_run: true })];+ const out = await runLauncherTick();+ expect(out.scopes).toBe(1);+ const r = out.results[0];+ expect(r.dry_run).toBe(true);+ expect(r.name).toBe('Turbo Otter');+ expect(r.symbol).toBe('TURBOTTR');+ expect(fundAgentForLaunch).not.toHaveBeenCalled(); // the safety contract+ });+});++describe('runLauncherTick — live', () => {+ it('funds the agent and launches through the real signed path', async () => {+ H.configs = [makeConfig({ dry_run: false })];++ // build-metadata then launch-agent over the internal authenticated fetch.+ const fetchMock = vi.fn(async (url) => {+ const u = String(url);+ if (u.includes('action=build-metadata')) {+ return { status: 200, json: async () => ({ metadata_url: 'ipfs://meta' }) };+ }+ if (u.includes('action=launch-agent')) {+ return { status: 200, json: async () => ({ mint: 'MINTxyz', signature: 'launch-sig' }) };+ }+ return { status: 404, json: async () => ({}) };+ });+ vi.stubGlobal('fetch', fetchMock);++ const out = await runLauncherTick();+ const r = out.results[0];+ expect(fundAgentForLaunch).toHaveBeenCalledTimes(1);+ expect(r.mint).toBe('MINTxyz');+ expect(r.symbol).toBe('TURBOTTR');+ // metadata build + launch = two internal POSTs+ expect(fetchMock).toHaveBeenCalledTimes(2);++ vi.unstubAllGlobals();+ });++ it('records a skip (no launch) when the master balance is too low', async () => {+ H.configs = [makeConfig({ dry_run: false })];+ H.masterSol = 0.001; // below per_launch + buffer+ const out = await runLauncherTick();+ expect(out.results[0].skipped).toMatch(/master low/);+ expect(fundAgentForLaunch).not.toHaveBeenCalled();+ });+});diff --git a/tests/launcher-funding.test.js b/tests/launcher-funding.test.jsnew file mode 100644index 000000000..dd921287a--- /dev/null+++ b/tests/launcher-funding.test.js@@ -0,0 +1,58 @@+import { describe, it, expect } from 'vitest';+import { fundAgentForLaunch, loadMasterSigner } from '../api/_lib/launcher-funding.js';++// These exercise the business-rule guards that fire BEFORE any chain/RPC call, so+// they run without a wallet, RPC, or DB. They prove the caps actually refuse —+// the safety contract the engine relies on to record a clean 'skipped' run.++describe('fundAgentForLaunch — caps refuse before spending', () => {+ const base = { agentAddress: 'AgentSoLAddrXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX', network: 'devnet' };++ it('refuses a non-positive amount', async () => {+ const r = await fundAgentForLaunch({ ...base, sol: 0, perLaunchCapSol: 1, dailyCapSol: 1 });+ expect(r.ok).toBe(false);+ expect(r.reason).toMatch(/positive/);+ });++ it('refuses when the per-launch cap is exceeded', async () => {+ const r = await fundAgentForLaunch({ ...base, sol: 2, perLaunchCapSol: 1, dailyCapSol: 100 });+ expect(r.ok).toBe(false);+ expect(r.reason).toMatch(/per-launch/);+ });++ it('refuses when the daily allowance is exhausted', async () => {+ const r = await fundAgentForLaunch({ ...base, sol: 0.5, perLaunchCapSol: 1, dailyCapSol: 0.1 });+ expect(r.ok).toBe(false);+ expect(r.reason).toMatch(/daily/);+ });++ it('refuses cleanly (never throws) when the master wallet is unconfigured', async () => {+ const prev = process.env.LAUNCHER_MASTER_SECRET_KEY_B64;+ const prevFb = process.env.PUMP_X402_LAUNCHER_SECRET_KEY_B64;+ delete process.env.LAUNCHER_MASTER_SECRET_KEY_B64;+ delete process.env.PUMP_X402_LAUNCHER_SECRET_KEY_B64;+ try {+ const r = await fundAgentForLaunch({ ...base, sol: 0.02, perLaunchCapSol: 1, dailyCapSol: 1 });+ expect(r.ok).toBe(false);+ expect(r.reason).toMatch(/not configured/);+ } finally {+ if (prev) process.env.LAUNCHER_MASTER_SECRET_KEY_B64 = prev;+ if (prevFb) process.env.PUMP_X402_LAUNCHER_SECRET_KEY_B64 = prevFb;+ }+ });+});++describe('loadMasterSigner', () => {+ it('returns null when no master secret is set', async () => {+ const prev = process.env.LAUNCHER_MASTER_SECRET_KEY_B64;+ const prevFb = process.env.PUMP_X402_LAUNCHER_SECRET_KEY_B64;+ delete process.env.LAUNCHER_MASTER_SECRET_KEY_B64;+ delete process.env.PUMP_X402_LAUNCHER_SECRET_KEY_B64;+ try {+ expect(await loadMasterSigner()).toBeNull();+ } finally {+ if (prev) process.env.LAUNCHER_MASTER_SECRET_KEY_B64 = prev;+ if (prevFb) process.env.PUMP_X402_LAUNCHER_SECRET_KEY_B64 = prevFb;+ }+ });+});diff --git a/tests/launcher-sources.test.js b/tests/launcher-sources.test.jsnew file mode 100644index 000000000..862e4e537--- /dev/null+++ b/tests/launcher-sources.test.js@@ -0,0 +1,42 @@+import { describe, it, expect } from 'vitest';+import { randomCoin, sanitizeName, sanitizeSymbol } from '../api/_lib/launcher-sources.js';++describe('sanitizeName', () => {+ it('collapses whitespace and trims', () => {+ expect(sanitizeName(' Turbo Otter ')).toBe('Turbo Otter');+ });+ it('caps at 32 chars (pump.fun limit)', () => {+ expect(sanitizeName('x'.repeat(80)).length).toBe(32);+ });+ it('never throws on null/undefined', () => {+ expect(sanitizeName(null)).toBe('');+ expect(sanitizeName(undefined)).toBe('');+ });+});++describe('sanitizeSymbol', () => {+ it('uppercases and strips non-alphanumerics', () => {+ expect(sanitizeSymbol('tur-bo!')).toBe('TURBO');+ });+ it('caps at 10 chars', () => {+ expect(sanitizeSymbol('ABCDEFGHIJKLMNOP').length).toBe(10);+ });+ it('falls back to a valid ticker when empty', () => {+ expect(sanitizeSymbol('@@@')).toBe('THREE3');+ expect(sanitizeSymbol('')).toBe('THREE3');+ });+});++describe('randomCoin', () => {+ it('always returns a launch-valid coin within pump.fun caps', () => {+ for (let i = 0; i < 200; i++) {+ const c = randomCoin();+ expect(c.kind).toBe('random');+ expect(c.name.length).toBeGreaterThan(0);+ expect(c.name.length).toBeLessThanOrEqual(32);+ expect(c.symbol).toMatch(/^[A-Z0-9]{1,10}$/);+ expect(typeof c.description).toBe('string');+ expect(c.trigger_source).toBe('random');+ }+ });+});diff --git a/vite.config.js b/vite.config.jsindex 6aad97823..cbf26aaec 100644--- a/vite.config.js+++ b/vite.config.js@@ -422,6 +422,7 @@ const appConfig = {arm: resolve(__dirname, 'pages/arm.html'),ca2x402: resolve(__dirname, 'pages/ca2x402.html'),activity: resolve(__dirname, 'pages/activity.html'),+ pipeline: resolve(__dirname, 'pages/pipeline.html'),'coin-intel': resolve(__dirname, 'pages/coin-intel.html'),trending: resolve(__dirname, 'pages/trending.html'),compose: resolve(__dirname, 'pages/compose.html'),@@ -484,6 +485,7 @@ const appConfig = {animations: resolve(__dirname, 'pages/animations.html'),'avatar-engines': resolve(__dirname, 'pages/avatar-engines.html'),splat: resolve(__dirname, 'pages/splat.html'),+ capture: resolve(__dirname, 'pages/capture.html'),club: resolve(__dirname, 'pages/club.html'),theater: resolve(__dirname, 'pages/theater.html'),stage: resolve(__dirname, 'pages/stage.html'),@@ -891,6 +893,8 @@ support: resolve(__dirname, 'pages/support.html'),'/ca2x402/': resolve(root, 'pages/ca2x402.html'),'/activity': resolve(root, 'pages/activity.html'),'/activity/': resolve(root, 'pages/activity.html'),+ '/pipeline': resolve(root, 'pages/pipeline.html'),+ '/pipeline/': resolve(root, 'pages/pipeline.html'),'/trending': resolve(root, 'pages/trending.html'),'/trending/': resolve(root, 'pages/trending.html'),'/coin-intel': resolve(root, 'pages/coin-intel.html'),@@ -991,6 +995,8 @@ support: resolve(__dirname, 'pages/support.html'),'/avatar-engines/': resolve(root, 'pages/avatar-engines.html'),'/splat': resolve(root, 'pages/splat.html'),'/splat/': resolve(root, 'pages/splat.html'),+ '/capture': resolve(root, 'pages/capture.html'),+ '/capture/': resolve(root, 'pages/capture.html'),'/brain': resolve(root, 'pages/brain.html'),'/brain/': resolve(root, 'pages/brain.html'),'/lipsync': resolve(root, 'public/demos/lipsync-tts.html'),diff --git a/workers/model-video2scene/.dockerignore b/workers/model-video2scene/.dockerignorenew file mode 100644index 000000000..b8b1451e4--- /dev/null+++ b/workers/model-video2scene/.dockerignore@@ -0,0 +1,6 @@+__pycache__/+*.pyc+.venv/+weights/+*.ply+*.mp4diff --git a/workers/model-video2scene/Dockerfile b/workers/model-video2scene/Dockerfilenew file mode 100644index 000000000..e8e2e6856--- /dev/null+++ b/workers/model-video2scene/Dockerfile@@ -0,0 +1,49 @@+FROM nvidia/cuda:12.8.0-cudnn-devel-ubuntu22.04++# devel (not runtime) base: LingBot-Map pulls FlashInfer and NVIDIA Kaolin, which+# build/JIT CUDA kernels and need nvcc + headers. TORCH_CUDA_ARCH_LIST targets the+# Cloud Run L4 (compute capability 8.9) so kernels build for it.+ENV PYTHONDONTWRITEBYTECODE=1 \+ PYTHONUNBUFFERED=1 \+ PIP_NO_CACHE_DIR=1 \+ DEBIAN_FRONTEND=noninteractive \+ TORCH_CUDA_ARCH_LIST="8.9+PTX" \+ PYTHONPATH=/opt/lingbot-map++RUN apt-get update && apt-get install -y --no-install-recommends \+ python3.10 python3.10-dev python3-pip \+ git curl wget build-essential ninja-build \+ ffmpeg libgl1 libglib2.0-0 \+ && rm -rf /var/lib/apt/lists/* \+ && ln -sf /usr/bin/python3.10 /usr/bin/python3 \+ && ln -sf /usr/bin/python3.10 /usr/bin/python \+ && pip install --upgrade pip setuptools wheel++# torch first (cached layer), matching the CUDA 12.8 base and LingBot-Map's pin.+RUN pip install torch==2.8.0 torchvision==0.23.0 --index-url https://download.pytorch.org/whl/cu128++# LingBot-Map (Apache-2.0). Clone, install the package + its deps, then put the+# repo on PYTHONPATH so demo.py (load_model/load_images/postprocess) is importable.+RUN git clone --depth 1 https://github.com/Robbyant/lingbot-map.git /opt/lingbot-map \+ && pip install -e /opt/lingbot-map++# Accelerated paged-KV attention (recommended by upstream for streaming inference).+RUN pip install --index-url https://pypi.org/simple flashinfer-python++COPY requirements.txt /app/requirements.txt+RUN pip install -r /app/requirements.txt++WORKDIR /app+COPY worker_security.py /app/worker_security.py+COPY main.py /app/main.py++EXPOSE 8080++# Long sequences run for minutes — keep the keep-alive generous; Cloud Run's own+# request timeout (cloudbuild --timeout) bounds the synchronous /infer 202 return,+# while the reconstruction itself runs in a FastAPI BackgroundTask.+CMD ["uvicorn", "main:app", \+ "--host", "0.0.0.0", \+ "--port", "8080", \+ "--workers", "1", \+ "--timeout-keep-alive", "600"]diff --git a/workers/model-video2scene/README.md b/workers/model-video2scene/README.mdnew file mode 100644index 000000000..2f36e9185--- /dev/null+++ b/workers/model-video2scene/README.md@@ -0,0 +1,51 @@+# model-video2scene++Streaming **video → 3D point-cloud** reconstruction on Cloud Run GPU.++Wraps [LingBot-Map](https://github.com/Robbyant/lingbot-map) (Apache-2.0) — a+feed-forward "Geometric Context Transformer" that reconstructs a dense+world-space point cloud from a monocular video or image sequence at ~20 FPS over+sequences of 10,000+ frames, using paged-KV-cache attention (FlashInfer).++The worker runs the model's documented inference path, fuses the per-frame world+points + RGB into a single coloured cloud, writes a binary PLY, and uploads it to+Cloud Storage. The three.ws **Scene Capture** page (`/capture`) renders that PLY+directly in a WebGL point-cloud viewer.++## API++```+POST /infer { video_url | images[], mode?, fps?, keyframe_interval?, ... } → 202 { task_id }+GET /tasks/:id → { status, result_gcs_url?, num_points?, frames?, error? }+GET /health → { ok, gpu_available, model_loaded }+```++Bearer auth on `/infer` and `/tasks/:id` (`Authorization: Bearer $API_KEY`). The+three.ws API (`api/scene-capture.js`) holds the matching `GCP_RECONSTRUCTION_KEY`+and points at `GCP_VIDEO2SCENE_URL`.++See the module docstring in [`main.py`](main.py) for the full request schema.++## Model weights++Mounted read-only from the shared weights bucket at `WEIGHTS_DIR/MODEL_FILE`+(default `/weights/lingbot-map/lingbot-map-long.pt`). Pre-populate once:++```bash+huggingface-cli download robbyant/lingbot-map-long --local-dir /tmp/lm+gsutil -m cp -r /tmp/lm/* gs://three-ws-model-weights/lingbot-map/+```++## Deploy++```bash+gcloud builds submit --config workers/model-video2scene/cloudbuild.yaml .+```++Then set `GCP_VIDEO2SCENE_URL` (the Cloud Run service URL) on the Vercel+deployment. `GCP_RECONSTRUCTION_KEY` is already shared across the model workers.++## Hardware++NVIDIA L4 (CUDA 12.8), 8 vCPU / 32 GiB. For very long clips, callers can lower+memory pressure with `mode: "windowed"` and a smaller `num_scale_frames`.diff --git a/workers/model-video2scene/cloudbuild.yaml b/workers/model-video2scene/cloudbuild.yamlnew file mode 100644index 000000000..8aa835bb7--- /dev/null+++ b/workers/model-video2scene/cloudbuild.yaml@@ -0,0 +1,68 @@+substitutions:+ _REGION: us-central1+ _RUN_SA: avatar-reconstruction-sa@aerial-vehicle-466722-p5.iam.gserviceaccount.com+ _SERVICE: model-video2scene+ _REPO: model-video2scene+ _GCS_BUCKET: three-ws-avatar-reconstructions+ _WEIGHTS_BUCKET: three-ws-model-weights+ _MIN_INSTANCES: "0"+ _MAX_INSTANCES: "2"++steps:+ - id: build+ name: gcr.io/cloud-builders/docker+ dir: workers/model-video2scene+ args:+ - build+ - --tag+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - --tag+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest+ - --cache-from+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest+ - .++ - id: push+ name: gcr.io/cloud-builders/docker+ args:+ - push+ - --all-tags+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server++ - id: deploy+ name: gcr.io/google.com/cloudsdktool/cloud-sdk:slim+ entrypoint: gcloud+ args:+ - run+ - deploy+ - ${_SERVICE}+ - --image=${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - --region=${_REGION}+ - --service-account=${_RUN_SA}+ - --platform=managed+ - --port=8080+ - --gpu=1+ - --gpu-type=nvidia-l4+ - --no-gpu-zonal-redundancy+ - --no-cpu-throttling+ - --cpu=8+ - --memory=32Gi+ - --min-instances=${_MIN_INSTANCES}+ - --max-instances=${_MAX_INSTANCES}+ # Streaming reconstruction over a long clip runs for minutes; /infer returns+ # 202 immediately and the job runs in a BackgroundTask, but Cloud Run still+ # bounds the instance request lifetime — give it headroom.+ - --timeout=900+ - --allow-unauthenticated+ - --add-volume=name=weights,type=cloud-storage,bucket=${_WEIGHTS_BUCKET}+ - --add-volume-mount=volume=weights,mount-path=/weights+ - --set-env-vars=GCS_BUCKET=${_GCS_BUCKET},WEIGHTS_DIR=/weights/lingbot-map,MODEL_FILE=lingbot-map-long.pt,MAX_CONCURRENT=1+ - --set-secrets=API_KEY=avatar-reconstruction-key:latest++images:+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:$SHORT_SHA+ - ${_REGION}-docker.pkg.dev/$PROJECT_ID/${_REPO}/server:latest++options:+ machineType: E2_HIGHCPU_32+ logging: CLOUD_LOGGING_ONLYdiff --git a/workers/model-video2scene/main.py b/workers/model-video2scene/main.pynew file mode 100644index 000000000..86c4cf4b9--- /dev/null+++ b/workers/model-video2scene/main.py@@ -0,0 +1,418 @@+"""+model-video2scene — streaming video → 3D point-cloud reconstruction.++Wraps LingBot-Map (Apache-2.0, github.com/Robbyant/lingbot-map), a feed-forward+"Geometric Context Transformer" that reconstructs a dense world-space point cloud+from a monocular video or image sequence. We run the model's documented inference+path, fuse the per-frame world points + RGB into a single coloured point cloud,+write a binary little-endian PLY, and upload it to Cloud Storage. The three.ws+Scene Capture page renders that PLY directly with a WebGL point-cloud viewer.++API contract (mirrors the other three.ws model workers — triposr, hunyuan3d):+ POST /infer+ {+ video_url?: https URL to an .mp4/.mov/.webm (one of video_url+ images?: [https url | data-uri, ...], or images required)+ mode?: "streaming" | "windowed" (default streaming)+ fps?: int, frames/sec to sample from video (default 8)+ keyframe_interval? int, cache every N-th frame (default 4)+ num_scale_frames? int, bidirectional scale frames (default 8)+ window_size?: int, windowed mode window (default 128)+ overlap_size?: int, windowed mode overlap (default 16)+ mask_sky?: bool, drop sky points (default true)+ conf_percentile?: 0..95, drop low-confidence points (default 30)+ max_points?: int, downsample budget (default 1_500_000)+ job_id?: str caller correlation id+ }+ → 202 { task_id, status: "queued" }++ GET /tasks/:id → { task_id, status, result_gcs_url?, num_points?, frames?, error? }+ GET /health → { ok, model, gpu_available, model_loaded }++Model weights are mounted read-only from the shared weights bucket at+ WEIGHTS_DIR/lingbot-map-long.pt+(see cloudbuild.yaml --add-volume). Pre-populate once with:+ huggingface-cli download robbyant/lingbot-map-long --local-dir /tmp/lm+ gsutil -m cp -r /tmp/lm/* gs://three-ws-model-weights/lingbot-map/++Environment variables:+ API_KEY — shared bearer secret (Cloud Run secret)+ GCS_BUCKET — Cloud Storage bucket for output point clouds+ WEIGHTS_DIR — local mount of model weights (default /weights/lingbot-map)+ MODEL_FILE — checkpoint filename (default lingbot-map-long.pt)+ LINGBOT_DIR — repo checkout on PYTHONPATH (default /opt/lingbot-map)+ MAX_CONCURRENT — max parallel reconstructions (default 1 — heavy, long jobs)+"""++from __future__ import annotations++import asyncio+import base64+import logging+import os+import struct+import tempfile+import time+import uuid+from contextlib import asynccontextmanager+from types import SimpleNamespace+from typing import Optional++import numpy as np+import torch+from fastapi import BackgroundTasks, FastAPI, Header, HTTPException+from google.cloud import storage+from pydantic import BaseModel, Field++from worker_security import (+ UnsafeUrlError,+ fetch_remote_bytes,+ require_api_key,+ safe_error,+)++logging.basicConfig(+ level=logging.INFO,+ format="%(asctime)s %(levelname)s %(name)s %(message)s",+)+log = logging.getLogger("video2scene")++API_KEY = os.environ["API_KEY"]+GCS_BUCKET = os.environ["GCS_BUCKET"]+WEIGHTS_DIR = os.environ.get("WEIGHTS_DIR", "/weights/lingbot-map")+MODEL_FILE = os.environ.get("MODEL_FILE", "lingbot-map-long.pt")+LINGBOT_DIR = os.environ.get("LINGBOT_DIR", "/opt/lingbot-map")+MAX_CONCURRENT = int(os.environ.get("MAX_CONCURRENT", "1"))++# Hard ceilings so a caller can't ask for an unbounded job.+MAX_FRAMES = 4000+MAX_POINT_BUDGET = 4_000_000++_model = None+_bucket: Optional[storage.Bucket] = None+_sem: Optional[asyncio.Semaphore] = None+_tasks: dict[str, dict] = {}+_device = "cuda" if torch.cuda.is_available() else "cpu"+++# ── model loading ─────────────────────────────────────────────────────────────+++def _default_args() -> SimpleNamespace:+ """The CLI arg surface LingBot-Map's demo.load_model() reads from.++ demo.load_model(args, device) reconstructs GCTStream and loads the checkpoint+ from args.model_path. We feed it the same namespace the CLI would build so the+ sanctioned loader (which reads model config out of the checkpoint) stays the+ single source of truth — no hand-reconstructed constructor args to drift.+ """+ return SimpleNamespace(+ model_path=os.path.join(WEIGHTS_DIR, MODEL_FILE),+ mode="streaming",+ num_scale_frames=8,+ keyframe_interval=4,+ window_size=128,+ overlap_size=16,+ overlap_keyframes=16,+ camera_num_iterations=4,+ downsample_factor=1,+ mask_sky=True,+ offload_to_cpu=False,+ )+++def _load_model():+ global _model+ import sys++ if LINGBOT_DIR not in sys.path:+ sys.path.insert(0, LINGBOT_DIR)+ # demo.py is the repo's own entrypoint; load_model() is the documented,+ # checkpoint-config-driven constructor used by demo.py and demo_render.+ from demo import load_model++ ckpt = os.path.join(WEIGHTS_DIR, MODEL_FILE)+ if not os.path.exists(ckpt):+ raise FileNotFoundError(f"checkpoint not found: {ckpt}")+ log.info("Loading LingBot-Map checkpoint %s on %s", ckpt, _device)+ _model = load_model(_default_args(), torch.device(_device))+ _model.eval()+ log.info("LingBot-Map model loaded")+++@asynccontextmanager+async def lifespan(app: FastAPI):+ global _bucket, _sem+ _bucket = storage.Client().bucket(GCS_BUCKET)+ _sem = asyncio.Semaphore(MAX_CONCURRENT)+ loop = asyncio.get_event_loop()+ await loop.run_in_executor(None, _load_model)+ log.info("Service ready — max_concurrent=%d device=%s", MAX_CONCURRENT, _device)+ yield+++app = FastAPI(title="model-video2scene", lifespan=lifespan)+++def _require_api_key(authorization: str) -> None:+ try:+ require_api_key(authorization, API_KEY)+ except PermissionError as exc:+ raise HTTPException(status_code=401, detail=str(exc)) from exc+++# ── input acquisition ─────────────────────────────────────────────────────────+++def _fetch_video(video_url: str, dst_dir: str) -> str:+ try:+ data = fetch_remote_bytes(video_url, timeout=120, max_bytes=512 * 1024 * 1024)+ except UnsafeUrlError as exc:+ raise ValueError(f"refused to fetch video source: {exc}") from exc+ ext = os.path.splitext(video_url.split("?", 1)[0])[1].lower()+ if ext not in (".mp4", ".mov", ".webm", ".mkv", ".avi"):+ ext = ".mp4"+ path = os.path.join(dst_dir, f"input{ext}")+ with open(path, "wb") as fh:+ fh.write(data)+ return path+++def _materialize_images(images: list[str], dst_dir: str) -> str:+ """Write caller-supplied frames to a folder LingBot-Map's loader can read."""+ folder = os.path.join(dst_dir, "frames")+ os.makedirs(folder, exist_ok=True)+ for i, src in enumerate(images[:MAX_FRAMES]):+ if src.startswith("data:image"):+ payload = base64.b64decode(src.split(",", 1)[1])+ elif src.startswith("https://"):+ try:+ payload = fetch_remote_bytes(src, timeout=30)+ except UnsafeUrlError as exc:+ raise ValueError(f"refused to fetch frame {i}: {exc}") from exc+ else:+ raise ValueError(f"unsupported image source at {i}: {src[:48]}")+ with open(os.path.join(folder, f"{i:06d}.jpg"), "wb") as fh:+ fh.write(payload)+ return folder+++# ── point-cloud fusion + PLY export ───────────────────────────────────────────+++def _to_np(x) -> np.ndarray:+ if isinstance(x, torch.Tensor):+ return x.detach().to("cpu").float().numpy()+ return np.asarray(x)+++def _fuse_point_cloud(+ predictions: dict,+ conf_percentile: float,+ max_points: int,+) -> 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 aligned+ world_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.+ """+ pts = _to_np(predictions["world_points"]).reshape(-1, 3)++ imgs = _to_np(predictions["images"])+ # Images may arrive as (..., 3) HWC or (..., 3, H, W) CHW. Normalize to (-1, 3).+ if imgs.shape[-1] == 3:+ cols = imgs.reshape(-1, 3)+ elif imgs.ndim >= 3 and imgs.shape[-3] == 3:+ cols = np.moveaxis(imgs, -3, -1).reshape(-1, 3)+ else:+ cols = imgs.reshape(-1, 3)+ if cols.shape[0] != pts.shape[0]:+ # Defensive: fall back to a neutral grey if the loader changed layout.+ cols = np.full((pts.shape[0], 3), 0.7, dtype=np.float32)+ if cols.max() <= 1.0 + 1e-6:+ cols = cols * 255.0+ cols = np.clip(cols, 0, 255).astype(np.uint8)++ conf = predictions.get("world_points_conf")+ mask = np.isfinite(pts).all(axis=1)+ if conf is not None:+ conf = _to_np(conf).reshape(-1)+ if conf.shape[0] == pts.shape[0] and conf_percentile > 0:+ thresh = np.percentile(conf[np.isfinite(conf)], conf_percentile)+ mask &= conf >= thresh+ pts, cols = pts[mask], cols[mask]++ 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)+ pts, cols = pts[idx], cols[idx]++ return pts.astype(np.float32), cols+++def _write_ply(points: np.ndarray, colors: np.ndarray) -> bytes:+ """Binary little-endian PLY: x y z float + red green blue uchar."""+ n = points.shape[0]+ header = (+ "ply\n"+ "format binary_little_endian 1.0\n"+ f"comment generated by three.ws model-video2scene (LingBot-Map)\n"+ f"element vertex {n}\n"+ "property float x\nproperty float y\nproperty float z\n"+ "property uchar red\nproperty uchar green\nproperty uchar blue\n"+ "end_header\n"+ ).encode("ascii")+ # Interleave xyz(f32) + rgb(u8) into a packed structured buffer.+ body = np.empty(n, dtype=[("xyz", "<f4", 3), ("rgb", "u1", 3)])+ body["xyz"] = points+ body["rgb"] = colors+ return header + body.tobytes()+++# ── inference ─────────────────────────────────────────────────────────────────+++def _run(req: "InferRequest", dst_dir: str) -> tuple[bytes, int, int]:+ import sys++ if LINGBOT_DIR not in sys.path:+ sys.path.insert(0, LINGBOT_DIR)+ from demo import load_images, postprocess++ if req.video_url:+ video_path = _fetch_video(req.video_url, dst_dir)+ images = load_images(video_path=video_path, fps=req.fps)+ else:+ folder = _materialize_images(req.images or [], dst_dir)+ images = load_images(image_folder=folder)++ frames = int(images.shape[0]) if hasattr(images, "shape") else len(images)+ if frames == 0:+ raise ValueError("no frames decoded from input")++ images = images.to(_device)+ with torch.no_grad():+ if req.mode == "windowed":+ predictions = _model.inference_windowed(+ images,+ window_size=req.window_size,+ overlap_size=req.overlap_size,+ num_scale_frames=req.num_scale_frames,+ keyframe_interval=req.keyframe_interval,+ output_device=torch.device("cpu"),+ )+ else:+ predictions = _model.inference_streaming(+ images,+ num_scale_frames=req.num_scale_frames,+ keyframe_interval=req.keyframe_interval,+ output_device=torch.device("cpu"),+ )+ predictions, _ = postprocess(predictions, images.to("cpu"))++ pts, cols = _fuse_point_cloud(predictions, req.conf_percentile, req.max_points)+ if pts.shape[0] == 0:+ raise ValueError("reconstruction produced no points above the confidence floor")+ return _write_ply(pts, cols), pts.shape[0], frames+++async def _run_inference(task_id: str, req: "InferRequest") -> None:+ async with _sem:+ _tasks[task_id]["status"] = "running"+ loop = asyncio.get_event_loop()+ t0 = time.time()+ try:+ with tempfile.TemporaryDirectory() as dst_dir:+ ply_bytes, num_points, frames = await loop.run_in_executor(+ None, _run, req, dst_dir+ )++ blob_name = f"scenes/video2scene/{task_id}.ply"+ blob = _bucket.blob(blob_name)+ await loop.run_in_executor(+ None,+ lambda: blob.upload_from_string(+ ply_bytes, content_type="application/octet-stream"+ ),+ )+ gcs_url = f"https://storage.googleapis.com/{GCS_BUCKET}/{blob_name}"++ elapsed = time.time() - t0+ _tasks[task_id].update(+ {+ "status": "done",+ "result_gcs_url": gcs_url,+ "num_points": num_points,+ "frames": frames,+ "bytes": len(ply_bytes),+ "elapsed_ms": int(elapsed * 1000),+ }+ )+ log.info(+ "[%s] done in %.1fs — %d frames → %d points (%d bytes) → %s",+ task_id, elapsed, frames, num_points, len(ply_bytes), gcs_url,+ )+ except Exception as exc: # noqa: BLE001 — surfaced opaquely below+ _tasks[task_id].update(+ {+ "status": "failed",+ "error": safe_error(exc, context=f"[{task_id}] reconstruction"),+ "elapsed_ms": int((time.time() - t0) * 1000),+ }+ )+++# ── API ───────────────────────────────────────────────────────────────────────+++class InferRequest(BaseModel):+ video_url: str | None = None+ images: list[str] | None = Field(default=None, max_length=MAX_FRAMES)+ mode: str = "streaming"+ fps: int = Field(default=8, ge=1, le=30)+ keyframe_interval: int = Field(default=4, ge=1, le=64)+ num_scale_frames: int = Field(default=8, ge=2, le=16)+ window_size: int = Field(default=128, ge=16, le=512)+ overlap_size: int = Field(default=16, ge=0, le=128)+ mask_sky: bool = True+ conf_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)+ job_id: str | None = None++[email protected]("/infer", status_code=202)+async def infer(+ body: InferRequest,+ background_tasks: BackgroundTasks,+ authorization: str = Header(...),+) -> dict:+ _require_api_key(authorization)+ if not body.video_url and not (body.images and len(body.images) > 0):+ raise HTTPException(status_code=400, detail="provide video_url or images[]")+ if body.mode not in ("streaming", "windowed"):+ raise HTTPException(status_code=400, detail="mode must be streaming or windowed")+ task_id = str(uuid.uuid4())+ _tasks[task_id] = {"task_id": task_id, "status": "queued", "model": "video2scene"}+ background_tasks.add_task(_run_inference, task_id, body)+ return {"task_id": task_id, "status": "queued"}++[email protected]("/tasks/{task_id}")+async def get_task(task_id: str, authorization: str = Header(...)) -> dict:+ _require_api_key(authorization)+ task = _tasks.get(task_id)+ if task is None:+ raise HTTPException(status_code=404, detail="task not found")+ return task++[email protected]("/health")+async def health() -> dict:+ return {+ "ok": True,+ "model": "video2scene",+ "gpu_available": torch.cuda.is_available(),+ "gpu_name": torch.cuda.get_device_name(0) if torch.cuda.is_available() else None,+ "model_loaded": _model is not None,+ }diff --git a/workers/model-video2scene/requirements.txt b/workers/model-video2scene/requirements.txtnew file mode 100644index 000000000..aeb94387a--- /dev/null+++ b/workers/model-video2scene/requirements.txt@@ -0,0 +1,17 @@+# ── LingBot-Map (Robbyant/lingbot-map, Apache-2.0) ────────────────────────────+# The package + its own deps are installed from the cloned repo in the Dockerfile+# (pip install -e /opt/lingbot-map). torch/torchvision are pinned in the Dockerfile+# to match the CUDA 12.8 base. These are the extra runtime deps this worker needs+# on top of LingBot-Map's own requirements.++numpy>=1.26.0+opencv-python-headless>=4.9.0++# ── Server ────────────────────────────────────────────────────────────────────+fastapi==0.115.0+uvicorn[standard]==0.32.0+pydantic>=2.0.0+httpx>=0.27.0++# ── GCP ───────────────────────────────────────────────────────────────────────+google-cloud-storage==2.18.0diff --git a/workers/model-video2scene/worker_security.py b/workers/model-video2scene/worker_security.pynew file mode 100644index 000000000..1e569c4e2--- /dev/null+++ b/workers/model-video2scene/worker_security.py@@ -0,0 +1,222 @@+"""+Shared security helpers for the three.ws GPU/CPU workers.++This module is intentionally dependency-light (stdlib only) so it can be+COPYed verbatim into every worker's Docker build context. The same canonical+file lives in each worker directory; keep them byte-identical when editing.++It provides three primitives that every worker needs:++ 1. ``require_api_key`` — constant-time bearer-token check (timing-safe).+ 2. ``fetch_remote_bytes`` — SSRF-hardened HTTP(S) fetch of caller-supplied+ URLs: https-only, DNS resolution with private/loopback/link-local/metadata+ IP rejection, per-hop redirect re-validation, and a bounded response size.+ 3. ``safe_error`` — turns an exception into an opaque, correlation-id-tagged+ message safe to persist/return to callers, after logging the full+ traceback server-side only.+"""++from __future__ import annotations++import hmac+import ipaddress+import logging+import socket+import uuid+from typing import Iterable, Optional+from urllib.parse import urlsplit++import httpx++log = logging.getLogger("worker_security")++# ── auth ────────────────────────────────────────────────────────────────────────+++def require_api_key(authorization: Optional[str], api_key: str) -> None:+ """Validate a ``Bearer <token>`` header in constant time.++ Raises ``PermissionError`` on any failure so callers can translate it into+ the framework's 401 (FastAPI workers map this to HTTPException(401)).+ """+ if not authorization or not authorization.startswith("Bearer "):+ raise PermissionError("missing bearer token")+ token = authorization[len("Bearer "):].strip()+ # hmac.compare_digest is timing-safe and accepts str (ASCII) operands.+ if not hmac.compare_digest(token, api_key):+ raise PermissionError("invalid api key")+++# ── SSRF-hardened fetch ─────────────────────────────────────────────────────────++# Default cap on a fetched response. Avatar selfies / driving audio / raw meshes+# are comfortably under this; anything larger is almost certainly abuse.+DEFAULT_MAX_BYTES = 64 * 1024 * 1024 # 64 MiB+_MAX_REDIRECTS = 4+++class UnsafeUrlError(ValueError):+ """Raised when a URL targets a disallowed scheme or a private/internal IP."""+++def _is_blocked_ip(ip: ipaddress._BaseAddress) -> bool:+ """Reject any address that could reach internal infrastructure.++ Covers loopback, RFC1918 private ranges, link-local (incl. the cloud+ metadata server at 169.254.169.254), unique-local IPv6 (fc00::/7),+ multicast, reserved, and unspecified addresses. IPv4-mapped IPv6 addresses+ are unwrapped first so a mapped private v4 can't slip through.+ """+ if isinstance(ip, ipaddress.IPv6Address) and ip.ipv4_mapped is not None:+ ip = ip.ipv4_mapped+ return (+ ip.is_private+ or ip.is_loopback+ or ip.is_link_local+ or ip.is_multicast+ or ip.is_reserved+ or ip.is_unspecified+ )+++def _resolve_safe_host(host: str) -> None:+ """DNS-resolve ``host`` and raise UnsafeUrlError if ANY address is internal.++ Resolving and checking every returned address closes the gap where a name+ resolves to both a public and a private address.+ """+ if not host:+ raise UnsafeUrlError("missing host")+ try:+ infos = socket.getaddrinfo(host, None, proto=socket.IPPROTO_TCP)+ except socket.gaierror as exc:+ raise UnsafeUrlError(f"could not resolve host: {host}") from exc++ addrs = {info[4][0] for info in infos}+ if not addrs:+ raise UnsafeUrlError(f"no addresses for host: {host}")+ for addr in addrs:+ ip = ipaddress.ip_address(addr)+ if _is_blocked_ip(ip):+ raise UnsafeUrlError(f"host resolves to a disallowed address: {host}")+++def assert_safe_url(url: str, *, allow_http: bool = False) -> str:+ """Validate scheme + resolved IPs for a single URL. Returns it unchanged.++ https is required by default; ``allow_http`` exists only for callers that+ legitimately need cleartext (not used by the workers).+ """+ parts = urlsplit(url)+ scheme = parts.scheme.lower()+ allowed = ("https", "http") if allow_http else ("https",)+ if scheme not in allowed:+ raise UnsafeUrlError(f"scheme not allowed: {scheme or '(none)'}")+ if not parts.hostname:+ raise UnsafeUrlError("missing host")+ _resolve_safe_host(parts.hostname)+ return url+++def fetch_remote_bytes(+ url: str,+ *,+ timeout: float = 30.0,+ max_bytes: int = DEFAULT_MAX_BYTES,+ allow_http: bool = False,+ headers: Optional[dict] = None,+) -> bytes:+ """Fetch ``url`` safely and return its body bytes.++ Hardening applied:+ * https-only (unless ``allow_http``).+ * every URL — including each redirect target — is DNS-resolved and+ rejected if it maps to a private/loopback/link-local/metadata address.+ * redirects are followed manually (max ``_MAX_REDIRECTS``) so each hop is+ re-validated; httpx's own redirect following is disabled.+ * the response body is streamed and aborted once it exceeds ``max_bytes``.++ Raises ``UnsafeUrlError`` for disallowed targets and ``httpx.HTTPError`` /+ ``ValueError`` for transport or size failures.+ """+ current = assert_safe_url(url, allow_http=allow_http)+ with httpx.Client(follow_redirects=False, timeout=timeout) as client:+ for _ in range(_MAX_REDIRECTS + 1):+ with client.stream("GET", current, headers=headers) as resp:+ if resp.is_redirect:+ location = resp.headers.get("location")+ if not location:+ raise UnsafeUrlError("redirect without Location header")+ current = assert_safe_url(+ str(resp.url.join(location)), allow_http=allow_http+ )+ continue+ resp.raise_for_status()+ declared = resp.headers.get("content-length")+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:+ raise ValueError(f"response too large: {declared} bytes")+ chunks: list[bytes] = []+ total = 0+ for chunk in resp.iter_bytes(65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError(f"response exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")+++async def fetch_remote_bytes_async(+ client: "httpx.AsyncClient",+ url: str,+ *,+ max_bytes: int = DEFAULT_MAX_BYTES,+ allow_http: bool = False,+ headers: Optional[dict] = None,+) -> bytes:+ """Async variant of ``fetch_remote_bytes`` using a caller-provided client.++ The provided ``client`` MUST be constructed with ``follow_redirects=False``+ so this function can re-validate each redirect hop itself.+ """+ current = assert_safe_url(url, allow_http=allow_http)+ for _ in range(_MAX_REDIRECTS + 1):+ async with client.stream("GET", current, headers=headers) as resp:+ if resp.is_redirect:+ location = resp.headers.get("location")+ if not location:+ raise UnsafeUrlError("redirect without Location header")+ current = assert_safe_url(+ str(resp.url.join(location)), allow_http=allow_http+ )+ continue+ resp.raise_for_status()+ declared = resp.headers.get("content-length")+ if declared is not None and declared.isdigit() and int(declared) > max_bytes:+ raise ValueError(f"response too large: {declared} bytes")+ chunks: list[bytes] = []+ total = 0+ async for chunk in resp.aiter_bytes(65536):+ total += len(chunk)+ if total > max_bytes:+ raise ValueError(f"response exceeded {max_bytes} bytes")+ chunks.append(chunk)+ return b"".join(chunks)+ raise UnsafeUrlError(f"too many redirects (>{_MAX_REDIRECTS})")+++# ── opaque error handling ───────────────────────────────────────────────────────+++def safe_error(exc: BaseException, *, context: str = "") -> str:+ """Log the full traceback server-side and return an opaque client message.++ Never leak ``traceback.format_exc()`` (absolute paths, library versions,+ internal hostnames, fragments of upstream responses) to callers. A short+ correlation id is embedded in both the log line and the returned string so+ operators can join a client-reported failure to the server log.+ """+ correlation_id = uuid.uuid4().hex[:12]+ label = f"{context} " if context else ""+ log.exception("%serror [correlation_id=%s]", label, correlation_id)+ return f"internal error (ref {correlation_id})"