Skip to content

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

Prelaunch radar, signal marketplace, and agent USDC settlement

nirholas9a4d24b151a1
diff --git a/.gitignore b/.gitignore
index 7b21b5246..6f0eed357 100644
--- a/.gitignore
+++ b/.gitignore
@@ -27,6 +27,9 @@ character-studio/public/loot-assets
# Local env files
.env.xspace
+# Scratch draft
+tester.md
+
# Demo/scratch scripts (contain credentials)
xspace-agent/demo-join.ts
xspace-agent/join-space.js
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 28d8d12ff..d3b915adc 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -27,6 +27,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr
- **Forge Standard quality generates reliably again** — Forging on the Standard quality setting could stall or silently route to a slower paid path while Draft worked instantly — so Standard often felt broken. The free NVIDIA generator only returns fast at a lower detail-sampling setting; Standard was asking it for more steps than the hosted preview can finish in time, so the request timed out and fell back. Standard now uses the same proven-fast budget as Draft on the free lane, so it completes quickly and dependably. We also made the generator fail over to a backup engine immediately on a timeout instead of waiting through a second dead attempt, cutting the worst-case wait roughly in half when the free engine is busy. (`/forge`) `[fix]`
- **Forged 3D models now render wherever the demo is embedded** — On the IBM partnership page, forging a model — paid Forge, the free no-wallet generator, or the avatar forge — could finish successfully yet show only a blank, dark viewer. The finished GLB was served from a storage domain that only permits a short list of host sites, so whenever the page ran somewhere else (a preview tool, an embed, a file opened locally) the browser silently blocked the 3D file and the viewer had nothing to draw. Models are now streamed through our own first-party delivery proxy, which any site can load, so the model appears no matter where the page is running. And if a model ever does fail to load, the viewer now shows a clear retry/download card instead of an unexplained empty stage. (`/ibm/x402-demo`) `[fix]`
- **Generated models stop vanishing right after they finish** — Models built on the free Hugging Face engines (avatars from a selfie, and Forge text/image/sketch→3D) were briefly served straight from the generator's scratch storage, which it wipes within minutes — so a model that loaded fine could 404 into a blank viewer moments later. Now the finished mesh is copied to our own durable storage the instant it's produced, while the file is still warm, and only that permanent URL is ever handed to your browser. The result is the same model, served from a link that doesn't expire. `[fix]`
+- **IBM partnership page: a live Agent Galaxy replaces the old guide-agent demo** — The third demo on the IBM Business Partner page is now the Agent Galaxy — fly through a 3D constellation of every public AI agent on three.ws, with each one placed in space by what it means, not by name or date. The coordinates come from real IBM Granite embeddings on watsonx.ai, so agents that do similar work sit in the same neighbourhood, Granite groups them into named constellations, and searching by meaning lights up the matching stars. It runs full-size and live, right on the page. It replaces a placeholder 3D character that only played a scripted celebration when you forged an avatar above — this is a real, standalone IBM Granite × three.ws experience instead. (`/galaxy`) `[improvement]`
- **Image understanding is now a callable API** — The free vision capability that already reads Forge uploads, weighs image evidence in the Fact Checker, and writes gallery alt text is now exposed as a public endpoint, /api/vision, so your own agents and tools can use it too. Send an image — as a file or a link — with a question, and get back a plain-language answer on the same free models the platform runs on, with a paid model as an automatic backstop. It's metered fairly and fails open, so it adds a new capability without changing anything that already works. `[sdk]`
- **Improvement: an agent's wallet identity now shows on the galaxy and character pages too** — Every place an agent appears should show the same wallet identity — its address, vanity rarity tier, a one-tap copy, a link to Solscan, and a Tip button. Two surfaces were still missing it. The 3D Agent Galaxy's inspect card showed a plain shortened address with no actions; it now renders the exact same wallet chip as the profile, marketplace, and dashboard, so you can copy, explore, or tip an agent straight from the star map. The consumer character page (/character/:id) showed no wallet at all; it now carries the full chip under the name, with the owner getting the vanity entry point and everyone else a Tip action. One shared component, identical everywhere. (`/galaxy`) `[improvement]`
- **Improvement: Animation Studio recovers your unsaved animation after a refresh or closed tab** — Posing a figure and keyframing a timeline in the Animation Studio is real work — and until now none of it touched your account until you pressed Save, so an accidental tab close or browser refresh could wipe it. The Studio now quietly keeps a local backup of your in-progress animation as you work, and warns you before you leave with unsaved keyframes. Come back later and it offers the recovered timeline right where you left off — 'Recovered your unsaved animation — 6 keyframes.' Saving to your account or opening a saved clip clears the backup, and an explicit shared link still wins. No work lost between sessions. (`/pose`) `[improvement, feature]`
diff --git a/api/_lib/agent-mirror.js b/api/_lib/agent-mirror.js
index 77e76ce54..aad12f275 100644
--- a/api/_lib/agent-mirror.js
+++ b/api/_lib/agent-mirror.js
@@ -104,7 +104,9 @@ async function readTokenBalance(conn, ownerPk, mintPk) {
}
// ── follower agent loader ─────────────────────────────────────────────────────
-async function loadFollower(followerId) {
+// Exported so other guarded auto-trade surfaces (the signal marketplace) reuse
+// the exact same follower shape + kill-switch read rather than re-deriving it.
+export async function loadFollower(followerId) {
const [row] = await sql`
SELECT id, user_id, name, meta FROM agent_identities WHERE id = ${followerId} AND deleted_at IS NULL
`;
@@ -125,7 +127,11 @@ async function loadFollower(followerId) {
// The SAME guard sequence as handleTrade (api/agents/solana-trade.js), composed
// for a server-initiated mirror. Returns a structured result — never throws past
// the boundary. `leaderRef` labels the custody trail + audit ("mirrored from X").
-async function runFollowerTrade({
+//
+// Exported so the signal marketplace (api/_lib/signal-engine.js) auto-mirrors a
+// paid emission through this identical firewall + MEV + spend-guard + custody
+// pipeline — the gate is shared, never reimplemented.
+export async function runFollowerTrade({
follower, side, mint, network, solAmount, tokenAmountRaw, slippageBps, idempotencyKey, leaderRef,
}) {
const { id, ownerId, meta, address, encryptedSecret } = follower;
diff --git a/api/_lib/agent-usdc-transfer.js b/api/_lib/agent-usdc-transfer.js
new file mode 100644
index 000000000..e9d9c2dcb
--- /dev/null
+++ b/api/_lib/agent-usdc-transfer.js
@@ -0,0 +1,165 @@
+// Guarded agent→agent USDC settlement — the x402 payment leg of the signal
+// marketplace, and a reusable primitive for any "agent A pays agent B N USDC"
+// flow that must respect the same custody policy every other outbound path does.
+//
+// Safe by construction, identical guarantees to api/x402-pay.js's per-agent path:
+// • reserveSpendUsd() atomically claims a pending custody row under the agent's
+// daily USD ceiling + kill switch BEFORE the key is touched — a frozen wallet
+// or a breached cap rejects with SpendLimitError and nothing is signed;
+// • a retried payment with the same idempotency key replays the prior settled
+// signature instead of paying twice (custody idempotency index);
+// • the spend lands in agent_custody_events (category 'signal') with the real
+// on-chain signature, so it shows in the owner's audit feed and counts toward
+// the daily ceiling like every other spend;
+// • execution goes through the shared MEV-aware engine (submitProtected), so it
+// gets the same dynamic compute budget + bounded confirmation as a trade.
+//
+// USDC is 1:1 USD, so the spend's USD value IS its USDC amount — no price feed
+// risk on the metering side.
+
+import { PublicKey } from '@solana/web3.js';
+import {
+ getAssociatedTokenAddressSync, createTransferCheckedInstruction,
+ createAssociatedTokenAccountIdempotentInstruction, TOKEN_PROGRAM_ID,
+} from '@solana/spl-token';
+import { sql } from './db.js';
+import { recoverSolanaAgentKeypair } from './agent-wallet.js';
+import { solanaConnection } from './agent-pumpfun.js';
+import { submitProtected } from './execution-engine.js';
+import {
+ getSpendLimits, reserveSpendUsd, updateCustodyEvent, releaseSpendReservation,
+ SpendLimitError,
+} from './agent-trade-guards.js';
+import { logAudit } from './audit.js';
+
+const USDC_MINT_BY_NETWORK = {
+ mainnet: 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v',
+ // USDC on devnet (Circle's official devnet mint).
+ devnet: '4zMMC9srt5Ri5X14GAgXhaHii3GnPAEERYPJgZJDncDU',
+};
+const USDC_DECIMALS = 6;
+
+/** USDC (float) → 6-decimal atomic units (BigInt, floored). */
+export function usdcToAtomics(usdc) {
+ return BigInt(Math.max(0, Math.floor(Number(usdc) * 10 ** USDC_DECIMALS)));
+}
+
+/**
+ * Pay `usdc` USDC from a custodial agent wallet to `toAddress`, fully guarded and
+ * audited under custody category `category` (default 'signal'). Never throws past
+ * the boundary except for a real spend-limit rejection, which surfaces as
+ * `{ status: 'blocked', code }` so callers can record it cleanly.
+ *
+ * @param {object} a
+ * @param {string} a.fromAgentId payer agent id
+ * @param {string} a.fromUserId payer agent owner id (for audit)
+ * @param {object} a.fromMeta payer agent.meta (encrypted secret + spend limits)
+ * @param {string} a.toAddress recipient base58 Solana address (USDC ATA derived)
+ * @param {number} a.usdc amount in USDC (= USD)
+ * @param {string} [a.network]
+ * @param {string} [a.category] custody category (default 'signal')
+ * @param {string} a.idempotencyKey
+ * @param {object} [a.rowMeta] extra metadata stored on the custody row
+ * @returns {Promise<{status:'paid'|'replayed'|'blocked'|'failed', signature?:string,
+ * custodyEventId?:number, usdc?:number, code?:string, message?:string}>}
+ */
+export async function transferUsdcGuarded({
+ fromAgentId, fromUserId, fromMeta, toAddress, usdc,
+ network = 'mainnet', category = 'signal', idempotencyKey, rowMeta = {},
+}) {
+ const net = network === 'devnet' ? 'devnet' : 'mainnet';
+ const amount = Number(usdc);
+ if (!(amount > 0)) return { status: 'failed', code: 'zero_amount' };
+ if (!idempotencyKey) return { status: 'failed', code: 'idempotency_required' };
+
+ const encryptedSecret = fromMeta?.encrypted_solana_secret || null;
+ const payerAddress = fromMeta?.solana_address || null;
+ if (!encryptedSecret || !payerAddress) return { status: 'failed', code: 'wallet_preparing' };
+
+ let toPk; let payerPk; let mintPk;
+ try {
+ toPk = new PublicKey(toAddress);
+ payerPk = new PublicKey(payerAddress);
+ mintPk = new PublicKey(USDC_MINT_BY_NETWORK[net]);
+ } catch {
+ return { status: 'failed', code: 'bad_address' };
+ }
+ if (toPk.equals(payerPk)) return { status: 'failed', code: 'self_payment' };
+
+ // Replay path — a prior settled payment with this key returns its signature.
+ const [prior] = await sql`
+ SELECT id, status, signature FROM agent_custody_events
+ WHERE agent_id = ${fromAgentId} AND idempotency_key = ${idempotencyKey} LIMIT 1
+ `;
+ if (prior) {
+ if (prior.status === 'confirmed' && prior.signature) {
+ return { status: 'replayed', signature: prior.signature, custodyEventId: Number(prior.id), usdc: amount };
+ }
+ if (prior.status === 'pending') return { status: 'failed', code: 'in_flight' };
+ return { status: 'failed', code: 'prior_failed' };
+ }
+
+ // 1. Reserve under the daily ceiling + kill switch (atomic, pre-signature).
+ let reservationId;
+ try {
+ const reservation = await reserveSpendUsd({
+ agentId: fromAgentId, userId: fromUserId, meta: fromMeta,
+ limits: getSpendLimits(fromMeta), category, usdValue: amount,
+ destination: toAddress, network: net, asset: 'USDC',
+ rowMeta: { ...rowMeta, idempotency_key: idempotencyKey },
+ });
+ reservationId = reservation.reservationId;
+ } catch (e) {
+ if (e instanceof SpendLimitError) return { status: 'blocked', code: e.code, message: e.message };
+ throw e;
+ }
+
+ // Attach the idempotency key to the reserved row so a retry replays it.
+ await updateCustodyEvent(reservationId, { meta: { idempotency_key: idempotencyKey, ...rowMeta } }).catch(() => {});
+ await sql`UPDATE agent_custody_events SET idempotency_key = ${idempotencyKey}, amount_raw = ${usdcToAtomics(amount).toString()} WHERE id = ${reservationId} AND idempotency_key IS NULL`.catch(() => {});
+
+ // 2. Recover the key (audit-logged), build the USDC transfer, settle on-chain.
+ let keypair;
+ try {
+ keypair = await recoverSolanaAgentKeypair(encryptedSecret, {
+ agentId: fromAgentId, userId: fromUserId, reason: `${category}_pay`,
+ meta: { to: toAddress, usdc: amount, custody_event_id: reservationId },
+ });
+ } catch {
+ await releaseSpendReservation(reservationId, 'key_recover_failed');
+ return { status: 'failed', code: 'key_recover_failed' };
+ }
+
+ const fromAta = getAssociatedTokenAddressSync(mintPk, keypair.publicKey, false, TOKEN_PROGRAM_ID);
+ const toAta = getAssociatedTokenAddressSync(mintPk, toPk, false, TOKEN_PROGRAM_ID);
+ const raw = usdcToAtomics(amount);
+ const instructions = [
+ // Idempotent: a no-op if the recipient already holds a USDC account.
+ createAssociatedTokenAccountIdempotentInstruction(keypair.publicKey, toAta, toPk, mintPk, TOKEN_PROGRAM_ID),
+ createTransferCheckedInstruction(fromAta, mintPk, toAta, keypair.publicKey, raw, USDC_DECIMALS, [], TOKEN_PROGRAM_ID),
+ ];
+
+ let signature;
+ try {
+ const result = await submitProtected({
+ network: net, connection: solanaConnection(net), payer: keypair, instructions,
+ opts: { tipMode: 'off', confirmTimeoutMs: 45_000 },
+ });
+ signature = result.signature;
+ } catch (e) {
+ if (e?.code === 'TX_ERR' && e.signature) {
+ // Broadcast but unconfirmed — keep the row pending so a retry can replay/settle.
+ await updateCustodyEvent(reservationId, { signature: e.signature, meta: { confirm: 'unconfirmed' } }).catch(() => {});
+ return { status: 'failed', code: 'unconfirmed', signature: e.signature, custodyEventId: reservationId };
+ }
+ await releaseSpendReservation(reservationId, 'send_failed');
+ return { status: 'failed', code: 'send_failed', message: (e?.message || '').slice(0, 200) };
+ }
+
+ await updateCustodyEvent(reservationId, { status: 'confirmed', signature, usd: amount }).catch(() => {});
+ logAudit({
+ userId: fromUserId, action: 'custody.signal_pay', resourceId: fromAgentId,
+ meta: { to: toAddress, usdc: amount, signature, network: net, category },
+ });
+ return { status: 'paid', signature, custodyEventId: reservationId, usdc: amount };
+}
diff --git a/api/_lib/migrations/20260623100000_prelaunch_radar.sql b/api/_lib/migrations/20260623100000_prelaunch_radar.sql
new file mode 100644
index 000000000..c5f0f6aee
--- /dev/null
+++ b/api/_lib/migrations/20260623100000_prelaunch_radar.sql
@@ -0,0 +1,107 @@
+-- Migration: Pre-Launch Creator-Wallet Radar (Task 04 — block-zero pre-cog snipe).
+-- Apply: psql "$DATABASE_URL" -f api/_lib/migrations/20260623100000_prelaunch_radar.sql
+-- Idempotent + re-runnable.
+--
+-- The radar watches the wallets of proven creators (creator_graduated >= N) and
+-- proven smart-money wallets (smart_wallet_reputation, task 03) in real time. When
+-- a watched wallet funds a brand-new deploy wallet or itself submits a pump.fun
+-- create instruction, the radar detects the launch PRECURSOR on-chain — at or
+-- before block-0 — and pre-arms a snipe through the existing executor. This is
+-- signal on the public on-chain precursor (funding, deploy), never front-running a
+-- user's pending mempool transaction.
+--
+-- Three pieces:
+-- 1. agent_sniper_strategies — a new trigger='prelaunch_radar' plus radar gates
+-- (min_creator_graduated_radar, require_smart_money_funder, radar_max_age_ms).
+-- 2. radar_watchlist — the auto-curated set of high-signal wallets the radar
+-- monitors, with the reason + score it was added for, capped + stale-evicted.
+-- 3. radar_events — every detected precursor, deduped on (network, signature,
+-- kind), read by the API + SSE feed and correlated to the snipe it pre-armed.
+--
+-- Mainnet-first (pump.fun). Read-only on the graph's tables; writes only its own.
+
+begin;
+
+-- ── strategy trigger + radar gates ───────────────────────────────────────────
+-- Extend the trigger enum (named <table>_<column>_check from prior migrations).
+alter table agent_sniper_strategies drop constraint if exists agent_sniper_strategies_trigger_check;
+alter table agent_sniper_strategies
+ add constraint agent_sniper_strategies_trigger_check
+ check (trigger in ('new_mint', 'first_claim', 'intel_confirmed', 'prelaunch_radar'));
+
+alter table agent_sniper_positions drop constraint if exists agent_sniper_positions_entry_trigger_check;
+alter table agent_sniper_positions
+ add constraint agent_sniper_positions_entry_trigger_check
+ check (entry_trigger in ('new_mint', 'first_claim', 'intel_confirmed', 'prelaunch_radar'));
+
+alter table agent_sniper_strategies
+ -- radar pedigree gate: the triggering creator must have >= this many graduated
+ -- coins. null = use the worker's SNIPER_RADAR_MIN_GRADUATED default.
+ add column if not exists min_creator_graduated_radar int
+ check (min_creator_graduated_radar is null or min_creator_graduated_radar >= 0),
+ -- demand the triggering wallet (or the funder of the fresh deploy wallet) is a
+ -- proven smart-money address before pre-arming.
+ add column if not exists require_smart_money_funder boolean not null default false,
+ -- ignore a precursor older than this when first observed (ms). null = worker default.
+ add column if not exists radar_max_age_ms int
+ check (radar_max_age_ms is null or radar_max_age_ms > 0);
+
+-- The radar poll loop only wants armed prelaunch_radar strategies.
+create index if not exists agent_sniper_strategies_radar
+ on agent_sniper_strategies (enabled, kill_switch)
+ where enabled = true and kill_switch = false and trigger = 'prelaunch_radar';
+
+-- ── auto-curated watchlist ───────────────────────────────────────────────────
+-- One row per watched wallet. `reason` is why it's watched; `score` is its 0..100
+-- signal strength (creator pedigree or realized reputation). Refreshed on an
+-- interval; capped + stale-evicted by the builder so the set stays high-signal.
+create table if not exists radar_watchlist (
+ address text not null,
+ network text not null default 'mainnet' check (network in ('mainnet', 'devnet')),
+ reason text not null, -- 'creator_graduated' | 'smart_money' | 'manual'
+ source text not null default 'auto', -- 'auto' | 'manual'
+ score numeric not null default 0, -- 0..100 signal strength
+ creator_graduated int, -- graduated coins (creator pedigree)
+ realized_score numeric, -- 0..100 reputation (smart money)
+ labels text[] not null default '{}', -- smart_money | strong | creator | ...
+ added_at timestamptz not null default now(),
+ refreshed_at timestamptz not null default now(), -- last time the builder re-affirmed it
+ last_hit_at timestamptz, -- last time a precursor fired from it
+ hits int not null default 0,
+ primary key (address, network)
+);
+
+create index if not exists radar_watchlist_score
+ on radar_watchlist (network, score desc);
+create index if not exists radar_watchlist_refreshed
+ on radar_watchlist (network, refreshed_at desc);
+
+-- ── detected precursors ──────────────────────────────────────────────────────
+-- Every on-chain launch precursor the radar observed. Deduped on
+-- (network, signature, kind). `mint` is set once the launch lands (immediately for
+-- a create; on correlation for a funding→deploy chain).
+create table if not exists radar_events (
+ id uuid primary key default gen_random_uuid(),
+ network text not null default 'mainnet' check (network in ('mainnet', 'devnet')),
+ kind text not null check (kind in ('create', 'funding', 'correlated_mint')),
+ trigger_wallet text not null, -- the watched wallet that acted
+ new_wallet text, -- the funded fresh wallet (funding kind)
+ mint text, -- the launched coin, once known
+ signature text not null, -- the on-chain tx that proves the precursor
+ confidence numeric not null default 0, -- 0..1
+ watch_reason text, -- the watchlist reason at fire time
+ watch_score numeric, -- the watchlist score at fire time
+ detail jsonb not null default '{}'::jsonb,
+ observed_ts timestamptz, -- on-chain block time of the precursor
+ created_at timestamptz not null default now(),
+ unique (network, signature, kind)
+);
+
+create index if not exists radar_events_recent
+ on radar_events (network, created_at desc);
+create index if not exists radar_events_wallet
+ on radar_events (trigger_wallet);
+create index if not exists radar_events_mint
+ on radar_events (mint) where mint is not null;
+
+commit;
diff --git a/api/_lib/migrations/20260626000000_signal_marketplace.sql b/api/_lib/migrations/20260626000000_signal_marketplace.sql
new file mode 100644
index 000000000..2f9c1a921
--- /dev/null
+++ b/api/_lib/migrations/20260626000000_signal_marketplace.sql
@@ -0,0 +1,219 @@
+-- Migration: reputation-gated signal marketplace (x402 paid alpha feeds).
+--
+-- The first trust-gated copy-trading economy: a trader whose ON-CHAIN track
+-- record is verified (api/_lib/trader-stats.js `verified` badge — 12+ closed
+-- trades, 5+ coins, ≤40% churn, positive realized SOL, all proven by tx) may
+-- publish their real entry/exit fills as an x402-metered signal feed. A
+-- follower's agent pays USDC per signal (or per epoch) from its OWN custodial
+-- wallet, and auto-mirrors the trade through the SAME firewall + MEV engine +
+-- spend guards every other outbound path uses (api/_lib/agent-mirror.js
+-- runFollowerTrade). Every emission binds to a real fill and accrues a realized
+-- outcome, so the marketplace ranks sellers by PROVEN edge, not follower count.
+--
+-- Four tables:
+-- signal_feeds — a verified publisher's feed config + pricing.
+-- signal_emissions — one row per published entry/exit, generated from the
+-- publisher's real agent_sniper_positions; realized
+-- outcome backfilled when the source position closes.
+-- signal_subscriptions — a follower agent's subscription (mode, sizing, kill).
+-- signal_deliveries — per (subscription, emission): the x402 payment row +
+-- the mirror fill + emit→fill latency = accountability.
+--
+-- apply-migrations.mjs only runs api/_lib/migrations/*.sql, so the schema lives
+-- here. Everything is `if not exists`, safe to re-apply.
+begin;
+
+-- ── signal_feeds — a verified trader's published feed ─────────────────────────
+-- One row = "publisher_agent_id sells its live signals under owner_user_id's
+-- account." Creation is gated in api/signals/feeds.js on the publisher's REAL
+-- trader-stats `verified` badge — a feed can never be published by an unproven
+-- wallet. payout_address snapshots the publisher agent's Solana USDC receiving
+-- address at publish time. The two cursors track how far emission generation has
+-- consumed the publisher's position lifecycle (entry = open, exit = close), so a
+-- sync pass never re-emits an old fill.
+create table if not exists signal_feeds (
+ id bigserial primary key,
+ publisher_agent_id uuid not null references agent_identities(id) on delete cascade,
+ owner_user_id uuid not null references users(id) on delete cascade,
+ network text not null default 'mainnet' check (network in ('mainnet','devnet')),
+ slug text not null unique,
+ title text not null,
+ description text,
+
+ -- Pricing. At least one of the two must be > 0 (enforced in the endpoint).
+ -- price_per_signal_usdc bills the subscriber once per delivered emission;
+ -- price_per_epoch_usdc bills once per epoch_seconds window (a subscription).
+ price_per_signal_usdc numeric not null default 0 check (price_per_signal_usdc >= 0),
+ price_per_epoch_usdc numeric not null default 0 check (price_per_epoch_usdc >= 0),
+ epoch_seconds integer not null default 86400 check (epoch_seconds >= 3600),
+
+ -- What the feed emits.
+ emit_entries boolean not null default true,
+ emit_exits boolean not null default true,
+ reveal_sizing boolean not null default true, -- expose size_multiple / entry_sol
+ min_conviction numeric not null default 0 check (min_conviction >= 0 and min_conviction <= 1),
+
+ visibility text not null default 'public' check (visibility in ('public','unlisted')),
+ status text not null default 'active' check (status in ('active','paused')),
+ payout_address text not null,
+
+ -- Emission-generation cursors over the publisher's positions.
+ entry_cursor timestamptz not null default 'epoch', -- max opened_at emitted as an entry
+ exit_cursor timestamptz not null default 'epoch', -- max closed_at processed for exits/outcomes
+
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+
+ -- A publisher runs at most one feed per agent per network (the product is the
+ -- agent's track record; multiple feeds would just fragment it).
+ unique (publisher_agent_id, network)
+);
+
+create index if not exists signal_feeds_status
+ on signal_feeds (network, status) where status = 'active';
+
+-- ── signal_emissions — one published entry/exit, bound to a real fill ─────────
+-- Generated by api/_lib/signal-engine.js from agent_sniper_positions: an `entry`
+-- the moment a position opens, an `exit` when it closes. The entry row's
+-- realized outcome is BACKFILLED when its source position closes, so every entry
+-- signal eventually carries a proven realized_pnl_pct + win/loss — this is what
+-- the marketplace ranks on. source_buy_sig / source_sell_sig are the on-chain
+-- proof that the signal was a real trade, not hand-authored alpha.
+create table if not exists signal_emissions (
+ id bigserial primary key,
+ feed_id bigint not null references signal_feeds(id) on delete cascade,
+ publisher_agent_id uuid not null references agent_identities(id) on delete cascade,
+ network text not null default 'mainnet',
+ source_position_id uuid not null, -- agent_sniper_positions.id
+
+ mint text not null,
+ symbol text,
+ name text,
+ side text not null check (side in ('entry','exit')),
+
+ size_multiple numeric, -- entry size ÷ publisher's typical entry
+ conviction numeric not null default 0, -- 0..1, derived from relative bet size
+ entry_sol numeric, -- publisher's entry size (SOL), for transparency
+ ref_price_lpt numeric, -- entry price (lamports per token)
+
+ status text not null default 'open' check (status in ('open','closed')),
+ realized_pnl_pct numeric, -- backfilled on close
+ realized_pnl_sol numeric,
+ outcome text check (outcome in ('win','loss','flat')),
+
+ source_buy_sig text,
+ source_sell_sig text,
+ emitted_at timestamptz not null default now(),
+ closed_at timestamptz,
+
+ -- One emission per (feed, position, side) — the sync idempotency key.
+ unique (feed_id, source_position_id, side)
+);
+
+create index if not exists signal_emissions_feed_time
+ on signal_emissions (feed_id, id desc);
+create index if not exists signal_emissions_outcome
+ on signal_emissions (feed_id, side, status) where side = 'entry';
+
+-- ── signal_subscriptions — a follower agent following a feed ──────────────────
+-- subscriber_agent_id auto-mirrors feed_id's paid emissions under owner_user_id's
+-- spend policy. `mode` simulate mirrors WITHOUT paying or trading (trust-building,
+-- clearly labelled); live pays real USDC + mirrors a real trade. `killed` is the
+-- instant halt — set true and no further payment or trade ever fires. base_sol ×
+-- size_multiple × size_scaling = the mirrored order, hard-capped at
+-- max_per_trade_sol and then re-gated by the agent's own trade limits. The cursor
+-- last_emission_id ensures a fanout never double-delivers.
+create table if not exists signal_subscriptions (
+ id bigserial primary key,
+ subscriber_agent_id uuid not null references agent_identities(id) on delete cascade,
+ owner_user_id uuid not null references users(id) on delete cascade,
+ feed_id bigint not null references signal_feeds(id) on delete cascade,
+ network text not null default 'mainnet' check (network in ('mainnet','devnet')),
+
+ mode text not null default 'simulate' check (mode in ('simulate','live')),
+ billing text not null default 'per_signal' check (billing in ('per_signal','per_epoch')),
+
+ base_sol numeric not null default 0.05 check (base_sol > 0),
+ size_scaling numeric not null default 1 check (size_scaling > 0),
+ max_per_trade_sol numeric not null default 0.25 check (max_per_trade_sol > 0),
+ slippage_bps integer not null default 300 check (slippage_bps >= 0 and slippage_bps <= 5000),
+ firewall_level text not null default 'block' check (firewall_level in ('warn','block')),
+ copy_exits boolean not null default true,
+
+ status text not null default 'active' check (status in ('active','paused','stopped')),
+ killed boolean not null default false,
+ epoch_paid_until timestamptz, -- per_epoch: paid through this instant
+ last_emission_id bigint not null default 0, -- cursor into signal_emissions.id
+
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+
+ -- One subscription per (subscriber agent, feed). The subscribe upsert keys here.
+ unique (subscriber_agent_id, feed_id),
+ -- A subscriber can never follow its own feed (the mirror would be a no-op loop).
+ check (subscriber_agent_id <> '00000000-0000-0000-0000-000000000000')
+);
+
+create index if not exists signal_subscriptions_feed
+ on signal_subscriptions (feed_id, status) where status = 'active';
+create index if not exists signal_subscriptions_owner
+ on signal_subscriptions (owner_user_id, created_at desc);
+
+-- ── signal_deliveries — per-signal accountability (payment + mirror + latency) ─
+-- One row per (subscription, emission): the x402 USDC payment (custody event id +
+-- signature, category 'signal'), the mirror fill (the 'trade' custody event from
+-- runFollowerTrade), the realized order, and emit→fill latency. signal_realized_pct
+-- is copied from the emission's realized outcome when its source position closes,
+-- so a feed's avg-follower-ROI rollup is grounded in proven outcomes. Idempotent
+-- on (subscription, emission) so a fanout retry never double-pays or double-trades.
+create table if not exists signal_deliveries (
+ id bigserial primary key,
+ subscription_id bigint not null references signal_subscriptions(id) on delete cascade,
+ emission_id bigint not null references signal_emissions(id) on delete cascade,
+ feed_id bigint not null references signal_feeds(id) on delete cascade,
+ subscriber_agent_id uuid not null,
+ publisher_agent_id uuid not null,
+ network text not null default 'mainnet',
+ mode text not null check (mode in ('simulate','live')),
+ side text not null check (side in ('entry','exit')),
+
+ -- x402 payment leg.
+ payment_status text not null default 'none'
+ check (payment_status in ('none','paid','failed','skipped')),
+ payment_custody_event_id bigint,
+ payment_signature text,
+ payment_usdc numeric,
+
+ -- Mirror trade leg.
+ mirror_status text not null default 'pending'
+ check (mirror_status in ('pending','executed','simulated','skipped','failed','unconfirmed')),
+ mirror_skip_reason text,
+ mirror_custody_event_id bigint,
+ mirror_signature text,
+ order_sol numeric,
+ price_impact_pct numeric,
+
+ emit_to_fill_ms bigint, -- emission.emitted_at → delivery fill
+ signal_realized_pct numeric, -- backfilled from emission outcome on close
+
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+
+ unique (subscription_id, emission_id)
+);
+
+create index if not exists signal_deliveries_feed_time
+ on signal_deliveries (feed_id, created_at desc);
+create index if not exists signal_deliveries_sub_time
+ on signal_deliveries (subscription_id, created_at desc);
+create index if not exists signal_deliveries_emission
+ on signal_deliveries (emission_id);
+
+comment on table signal_feeds is
+ 'Reputation-gated x402 signal feeds. Publish gated on api/_lib/trader-stats.js '
+ 'verified badge. See api/_lib/signal-engine.js + api/signals/*.';
+comment on table signal_emissions is
+ 'Published entry/exit signals, generated from real agent_sniper_positions; '
+ 'realized outcome backfilled on close. Ranking source for the marketplace.';
+
+commit;
diff --git a/data/changelog.json b/data/changelog.json
index 6ddad1e38..2d55abffe 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,15 @@
{
"$comment": "Curated changelog entries for three.ws — the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-06-23",
+ "title": "IBM partnership page: a live Agent Galaxy replaces the old guide-agent demo",
+ "summary": "The third demo on the IBM Business Partner page is now the Agent Galaxy — fly through a 3D constellation of every public AI agent on three.ws, with each one placed in space by what it means, not by name or date. The coordinates come from real IBM Granite embeddings on watsonx.ai, so agents that do similar work sit in the same neighbourhood, Granite groups them into named constellations, and searching by meaning lights up the matching stars. It runs full-size and live, right on the page. It replaces a placeholder 3D character that only played a scripted celebration when you forged an avatar above — this is a real, standalone IBM Granite × three.ws experience instead.",
+ "tags": [
+ "improvement"
+ ],
+ "link": "/galaxy"
+ },
{
"date": "2026-06-23",
"title": "Reasoning models now show just the answer, not their scratch work",
diff --git a/pages/ibm/hello.html b/pages/ibm/hello.html
index 2fe4821e2..177138320 100644
--- a/pages/ibm/hello.html
+++ b/pages/ibm/hello.html
@@ -368,20 +368,6 @@ a:focus-visible{outline-offset:3px}
.raw summary{min-height:44px;display:flex;align-items:center}
}
-/* ── 3D agent layer ── */
-.agent-grid{display:grid;grid-template-columns:1fr;gap:28px;margin-top:28px;align-items:start}
-@media(min-width:760px){.agent-grid{grid-template-columns:minmax(0,360px) 1fr;gap:36px}}
-.agent-stage{position:relative;border:1px solid var(--ibm-divider);background:var(--ibm-field);min-height:420px;overflow:hidden}
-.agent-stage agent-3d{display:block;width:100%;height:460px}
-/* Skeleton silhouette shown until the web component upgrades + boots. The booted
- agent paints over it; if the script never loads, this stays as a calm fallback. */
-.agent-skel{position:absolute;inset:0;display:flex;flex-direction:column;align-items:center;justify-content:flex-end;gap:3%;padding-bottom:8%;pointer-events:none}
-.agent-skel .s-head{width:22%;max-width:84px;aspect-ratio:1;border-radius:50%;background:linear-gradient(90deg,var(--ibm-skel-a) 25%,var(--ibm-skel-b) 37%,var(--ibm-skel-a) 63%);background-size:400% 100%;animation:sk 1.6s ease infinite}
-.agent-skel .s-body{width:42%;max-width:160px;height:44%;border-radius:44% 44% 24% 24%/26% 26% 9% 9%;background:linear-gradient(90deg,var(--ibm-skel-a) 25%,var(--ibm-skel-b) 37%,var(--ibm-skel-a) 63%);background-size:400% 100%;animation:sk 1.6s ease infinite}
-agent-3d:defined ~ .agent-skel{display:none}
-.agent-copy h3{font-size:18px;font-weight:600;margin-bottom:8px}
-.agent-copy p{font-size:14px;color:var(--ibm-muted);font-weight:300;line-height:1.65;margin-bottom:14px;max-width:48ch}
-
/* ── Demo nav strip (hero) ── */
.demo-nav{display:flex;flex-wrap:wrap;gap:8px;margin-top:26px}
.demo-nav a{font-size:13px;font-weight:500;color:var(--ibm-ink);border:1px solid var(--ibm-border);padding:8px 14px;border-radius:2px;transition:border-color .12s,color .12s,background .12s}
@@ -402,6 +388,13 @@ agent-3d:defined ~ .agent-skel{display:none}
.live-embed .bar-actions button:hover,.live-embed .bar-actions a:hover{border-color:var(--ibm-blue);color:var(--ibm-blue)}
.embed-frame{position:relative;background:var(--ibm-field);height:min(78vh,820px)}
.embed-frame iframe{display:block;width:100%;height:100%;border:0;background:var(--ibm-field)}
+/* Play runs the dark `noir` world (?biome=noir) — paint its frame, loading and
+ error states on the same #1c2530→#0c1116 stage the 3D viewers use, so the embed
+ reads as part of that surface in both themes and never flashes a light box. */
+.play-embed .embed-frame,.play-embed .embed-frame iframe,.play-embed .embed-state{background:radial-gradient(circle at 50% 30%,#1c2530,#0c1116 70%)}
+.play-embed .embed-state{color:#aebccd}
+.play-embed .embed-state .es-hint{color:#8a9bb0}
+.play-embed .embed-state .spin{border-color:rgba(255,255,255,.22);border-top-color:#78a9ff}
/* True full-screen via the Fullscreen API — the app fills the whole display. */
.live-embed:fullscreen{display:flex;flex-direction:column;background:var(--ibm-surface)}
.live-embed:fullscreen .embed-frame{flex:1;height:auto}
@@ -470,12 +463,12 @@ agent-3d:defined ~ .agent-skel{display:none}
</div>
<h1>A live showcase of agentic commerce, built with <strong>IBM</strong></h1>
<p class="hero-sub">IBM has shaped computing for over a century — and it stays at the frontier by backing what comes next. three.ws is one of those bets: a platform for on-chain micropayments and 3D AI agents. As an IBM Business Partner, we built this page to demonstrate that partnership in the open — every demo below runs against real, production three.ws systems. Nothing is mocked, nothing is a slide.</p>
- <p class="hero-sub" style="margin-top:14px">Five things we want to show you: pay a few cents to turn text into a 3D model, forge a rigged, animated avatar from a sentence for free, an autonomous 3D agent that buys its own data over <span class="mono">x402</span>, a shared 3D world, and an agent placed in augmented reality. Try each one yourself — the paid Forge demo settles real USDC from your own wallet; the rest are free, no wallet needed.</p>
+ <p class="hero-sub" style="margin-top:14px">Five things we want to show you: pay a few cents to turn text into a 3D model, forge a rigged, animated avatar from a sentence for free, fly through a 3D galaxy of every agent mapped by <span class="mono">IBM Granite</span>, a shared 3D world, and an agent placed in augmented reality. Try each one yourself — the paid Forge demo settles real USDC from your own wallet; the rest are free, no wallet needed.</p>
<nav class="demo-nav" aria-label="The demos on this page">
<a href="#webinar" class="nav-live"><span class="live-dot" aria-hidden="true"></span>Watch live</a>
<a href="#forge"><span class="n">01</span>Forge</a>
<a href="#demo"><span class="n">02</span>Avatars</a>
- <a href="#agent"><span class="n">03</span>3D agent</a>
+ <a href="#galaxy"><span class="n">03</span>Galaxy</a>
<a href="#play"><span class="n">04</span>Play</a>
<a href="#irl"><span class="n">05</span>IRL</a>
</nav>
@@ -616,6 +609,14 @@ agent-3d:defined ~ .agent-skel{display:none}
mp4: '', // plain MP4 on R2 (synced premiere)
youTubeId: '', // YouTube video / live id → iframe (its own premiere/live)
mode: 'auto', // 'auto' | 'premiere' | 'live'
+
+ // ── After the event ENDS — what the stage becomes once the countdown is over
+ // and the slot has passed. Leave blank for the default "Thanks for joining"
+ // card. Set endLoop to a muted MP4 (e.g. a highlight reel / ambient loop) and
+ // it plays full-stage, looping forever, the instant the countdown expires.
+ // A real recording (vodHls/mp4 above) always wins over this — those become a
+ // proper replay; endLoop is the no-recording fallback so the stage never dies.
+ endLoop: '', // looped, muted highlight reel shown after the event ends (MP4)
};
const startMs = Date.parse(WEBINAR.startTime);
@@ -691,7 +692,9 @@ agent-3d:defined ~ .agent-skel{display:none}
if (phase === 'pre') return; // countdown already visible
pre.hidden = true;
if (phase === 'ended' && !hasSource) {
- // Past the slot, no recording posted yet.
+ // Past the slot, no live/replay source. Prefer a looped highlight reel if one
+ // was configured; otherwise fall back to the static "thanks" card.
+ if (WEBINAR.endLoop) { mountLoop(); clearInterval(timer); return; }
holding.hidden = false;
$('wbSpinner').style.display = 'none';
$('wbHoldTitle').textContent = 'Thanks for joining';
@@ -726,6 +729,27 @@ agent-3d:defined ~ .agent-skel{display:none}
$('wbRetry').hidden = false;
}
+ // Post-event ambient loop: a muted, controls-free MP4 that covers the stage and
+ // repeats forever once the event is over. If it can't load, fall back to the
+ // calm "thanks" card so the stage is never a black void.
+ function mountLoop() {
+ pre.hidden = true; holding.hidden = true; badge.hidden = true; unmute.hidden = true;
+ player.hidden = false; player.innerHTML = '';
+ const v = document.createElement('video');
+ v.src = WEBINAR.endLoop;
+ v.loop = true; v.muted = true; v.autoplay = true; v.playsInline = true;
+ v.setAttribute('controlslist', 'nodownload');
+ v.addEventListener('error', () => {
+ player.hidden = true; player.innerHTML = '';
+ holding.hidden = false;
+ $('wbSpinner').style.display = 'none';
+ $('wbHoldTitle').textContent = 'Thanks for joining';
+ $('wbHoldMsg').textContent = 'The recording will be posted here shortly.';
+ });
+ player.appendChild(v);
+ v.play().catch(() => {});
+ }
+
async function mountPlayer() {
holding.hidden = true; player.hidden = false;
badge.hidden = !isLiveSource || phase !== 'live';
@@ -1030,32 +1054,23 @@ agent-3d:defined ~ .agent-skel{display:none}
</div>
</section>
-<!-- ══ THE AGENT ══ -->
-<section class="section" id="agent" aria-labelledby="agent-h">
+<!-- ══ DEMO 03 · AGENT GALAXY (live IBM Granite semantic 3D map) ══ -->
+<section class="section" id="galaxy" aria-labelledby="galaxy-h">
<div class="inner">
- <div class="section-tag">Demo 03 · Embodiment</div>
- <h2 id="agent-h">An <strong>agent</strong> that pays for its own data</h2>
- <p class="section-lead">The agentic-commerce loop the Forge demo runs by hand — read a price, sign, settle a real USDC micropayment — an autonomous agent can run on its own. This is one of them: a 3D agent from three.ws, driven by the very engine that just animated your avatar, rendered live in your browser. Forge a character above and watch it react.</p>
-
- <div class="agent-grid">
- <div class="agent-stage">
- <!-- A bare, transparent 3D avatar — no chat, no debug controls, no name-plate.
- A plain <agent-3d> given only a `body` is bare by default; it renders the
- avatar and nothing else. The web component lazy-boots when scrolled into
- view; until it upgrades, this skeleton holds the frame so the box is never blank. -->
- <agent-3d
- id="guideAgent"
- body="https://three.ws/avatars/default.glb"
- background="transparent"
- width="100%" height="460px">
- </agent-3d>
- <div class="agent-skel" aria-hidden="true"><span class="s-head"></span><span class="s-body"></span></div>
+ <div class="section-tag">Demo 03 · Intelligence</div>
+ <h2 id="galaxy-h">Every agent, <strong>mapped by meaning</strong></h2>
+ <p class="section-lead">Fly through a 3D constellation of every AI agent on three.ws — each one placed in space by what it <em>means</em>, not by name or date. Coordinates come from <strong>IBM Granite</strong> embeddings on watsonx.ai, so agents that do similar things sit in the same neighbourhood; Granite names each constellation. Search by meaning and watch the matching stars light up. It runs full-size, right on the page.</p>
+ <div class="live-embed" data-src="https://three.ws/galaxy" data-allow="fullscreen; xr-spatial-tracking" data-label="Agent Galaxy — three.ws × IBM Granite">
+ <div class="embed-bar">
+ <span class="bar-url"><span class="dot" aria-hidden="true"></span>three.ws/galaxy</span>
+ <span class="bar-actions">
+ <button type="button" data-fs>⤢ Full screen</button>
+ <a href="https://three.ws/galaxy" target="_blank" rel="noopener">New tab ↗</a>
+ </span>
</div>
-
- <div class="agent-copy">
- <h3>It reacts to your avatar — in real time</h3>
- <p>Forge a character above and watch: this agent celebrates the moment your avatar comes to life. It runs the agentic-commerce loop too — reading a price, signing, and settling a USDC micropayment on its own, exactly the way the Forge demo does, only autonomously.</p>
- <p>Rendered live in the browser with WebGL — no video, no pre-recording.</p>
+ <div class="embed-frame">
+ <div class="embed-load embed-state"><span class="spin" aria-hidden="true"></span><span>Mapping the galaxy with IBM Granite…</span></div>
+ <div class="embed-err embed-state">The galaxy couldn't load inline here. <span class="es-hint"><a href="https://three.ws/galaxy" target="_blank" rel="noopener">Open it in a new tab ↗</a></span></div>
</div>
</div>
</div>
@@ -1067,7 +1082,7 @@ agent-3d:defined ~ .agent-skel{display:none}
<div class="section-tag">Demo 04 · Worlds</div>
<h2 id="play-h">Play — drop an agent into a <strong>live world</strong></h2>
<p class="section-lead">Every coin on three.ws is a 3D space agents and visitors share in real time — walk in, pick an avatar, and move around a world that reacts to live on-chain activity. Pick a name and a body below to enter; it runs full-size, right on the page.</p>
- <div class="live-embed" data-src="https://three.ws/play?bg=transparent" data-allow="fullscreen; gamepad; autoplay; xr-spatial-tracking; microphone" data-label="Play — three.ws">
+ <div class="live-embed play-embed" data-src="https://three.ws/play?biome=noir" data-allow="fullscreen; gamepad; autoplay; xr-spatial-tracking; microphone" data-label="Play — three.ws">
<div class="embed-bar">
<span class="bar-url"><span class="dot" aria-hidden="true"></span>three.ws/play</span>
<span class="bar-actions">
@@ -1192,46 +1207,7 @@ agent-3d:defined ~ .agent-skel{display:none}
$('errBanner').classList.remove('show'); bannerShown = false;
});
- // ── 3D agent layer ────────────────────────────────────────────────────────
- // The <agent-3d> element exposes scripted, LLM-free reactions (expressEmotion,
- // playEmote, wave, notify). We drive those from the avatar-forge lifecycle above
- // (the window 'avatar:*' events it dispatches) so the agent visibly responds to a
- // real generation as it happens — no faked timing, no canned animation loop.
- var agentReady = false;
- function agentEl() { return document.getElementById('guideAgent'); }
- // Fire a reaction only once the component has booted; calls before that no-op
- // safely inside the element, but gating avoids wasted work.
- function agentReact(fn) {
- var el = agentEl();
- if (!el || !agentReady) return;
- try { fn(el); } catch (_) {}
- }
- // The avatar is bare (no chat) — we only track when it has booted so its
- // scripted reactions to the payment lifecycle can fire.
- function wireAgent() {
- var el = agentEl();
- if (!el) return;
- el.addEventListener('agent:ready', function () { agentReady = true; });
- }
- function agentOnWaiting() {
- agentReact(function (el) { if (el.expressEmotion) el.expressEmotion('patience', 0.6); });
- }
- function agentOnSettled() {
- agentReact(function (el) {
- if (el.expressEmotion) el.expressEmotion('celebration', 0.95);
- if (el.playEmote) el.playEmote('cheer');
- });
- }
- function agentOnError() {
- agentReact(function (el) { if (el.expressEmotion) el.expressEmotion('concern', 0.8); });
- }
- // Bridge: the avatar forge (Demo 02) dispatches these as it runs, so the guide
- // agent waits, celebrates, or shows concern in lockstep with a real generation.
- window.addEventListener('avatar:generating', agentOnWaiting);
- window.addEventListener('avatar:done', agentOnSettled);
- window.addEventListener('avatar:error', agentOnError);
-
- // ── full-size demo embeds (Play / IRL) ─────────────────────────────────────
+ // ── full-size demo embeds (Galaxy / Play / IRL) ────────────────────────────
// Each presents a real, framable production surface at full size. The iframe
// is created only as the section nears the viewport (IntersectionObserver),
// so three heavy apps never load at once on first paint. A load timeout falls
@@ -1298,7 +1274,6 @@ agent-3d:defined ~ .agent-skel{display:none}
}
});
- wireAgent();
wireLiveEmbeds();
})();
</script>
diff --git a/public/changelog.json b/public/changelog.json
index 2e4717c61..d901f04f3 100644
--- a/public/changelog.json
+++ b/public/changelog.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-23T06:11:22.825Z",
+ "generated_at": "2026-06-23T06:56:01.661Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json",
"site": {
"name": "three.ws",
@@ -217,6 +217,16 @@
"fix"
]
},
+ {
+ "date": "2026-06-23",
+ "type": "update",
+ "title": "IBM partnership page: a live Agent Galaxy replaces the old guide-agent demo",
+ "summary": "The third demo on the IBM Business Partner page is now the Agent Galaxy — fly through a 3D constellation of every public AI agent on three.ws, with each one placed in space by what it means, not by name or date. The coordinates come from real IBM Granite embeddings on watsonx.ai, so agents that do similar work sit in the same neighbourhood, Granite groups them into named constellations, and searching by meaning lights up the matching stars. It runs full-size and live, right on the page. It replaces a placeholder 3D character that only played a scripted celebration when you forged an avatar above — this is a real, standalone IBM Granite × three.ws experience instead.",
+ "link": "/galaxy",
+ "tags": [
+ "improvement"
+ ]
+ },
{
"date": "2026-06-23",
"type": "update",
diff --git a/public/changelog.xml b/public/changelog.xml
index 5d9ab9b76..81ba862e2 100644
--- a/public/changelog.xml
+++ b/public/changelog.xml
@@ -174,6 +174,14 @@
<category>fix</category>
<description>Models built on the free Hugging Face engines (avatars from a selfie, and Forge text/image/sketch→3D) were briefly served straight from the generator's scratch storage, which it wipes within minutes — so a model that loaded fine could 404 into a blank viewer moments later. Now the finished mesh is copied to our own durable storage the instant it's produced, while the file is still warm, and only that permanent URL is ever handed to your browser. The result is the same model, served from a link that doesn't expire.</description>
</item>
+ <item>
+ <title>IBM partnership page: a live Agent Galaxy replaces the old guide-agent demo</title>
+ <link>https://three.ws/galaxy</link>
+ <guid isPermaLink="false">2026-06-23:IBM partnership page: a live Agent Galaxy replaces the old guide-agent demo</guid>
+ <pubDate>Tue, 23 Jun 2026 12:00:00 GMT</pubDate>
+ <category>improvement</category>
+ <description>The third demo on the IBM Business Partner page is now the Agent Galaxy — fly through a 3D constellation of every public AI agent on three.ws, with each one placed in space by what it means, not by name or date. The coordinates come from real IBM Granite embeddings on watsonx.ai, so agents that do similar work sit in the same neighbourhood, Granite groups them into named constellations, and searching by meaning lights up the matching stars. It runs full-size and live, right on the page. It replaces a placeholder 3D character that only played a scripted celebration when you forged an avatar above — this is a real, standalone IBM Granite × three.ws experience instead.</description>
+ </item>
<item>
<title>Image understanding is now a callable API</title>
<link>https://three.ws/changelog</link>
diff --git a/public/features.json b/public/features.json
index c9bbd8339..9bd1bf63b 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-23T06:11:22.806Z",
+ "generated_at": "2026-06-23T06:56:01.645Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
@@ -1704,6 +1704,16 @@
"tags": [],
"showcase": false
},
+ {
+ "path": "/blog/x402-stripe-for-agent-payments",
+ "title": "The Stripe of x402: How three.ws Turned Agent Payments Into One Line of Code",
+ "description": "HTTP 402 sat unused for thirty years. Agents revived it. three.ws built the drop in payment modal that makes x402 a one liner, on top of a full stack of agent wallets, wallet intents, on-chain reputation, sniping, and $THREE.",
+ "added": null,
+ "auth": null,
+ "indexable": true,
+ "tags": [],
+ "showcase": false
+ },
{
"path": "/blog/see-your-3d-in-ar",
"title": "See Your 3D Avatar in the Real World — AR Lands on three.ws",
diff --git a/public/llms-full.txt b/public/llms-full.txt
index 91c753ca5..fd13c6b93 100644
--- a/public/llms-full.txt
+++ b/public/llms-full.txt
@@ -1040,6 +1040,12 @@ URL: https://three.ws/blog
Editorial index of three.ws launches and long-form posts.
+### The Stripe of x402: How three.ws Turned Agent Payments Into One Line of Code
+
+URL: https://three.ws/blog/x402-stripe-for-agent-payments
+
+HTTP 402 sat unused for thirty years. Agents revived it. three.ws built the drop in payment modal that makes x402 a one liner, on top of a full stack of agent wallets, wallet intents, on-chain reputation, sniping, and $THREE.
+
### See Your 3D Avatar in the Real World — AR Lands on three.ws
URL: https://three.ws/blog/see-your-3d-in-ar
diff --git a/public/llms.txt b/public/llms.txt
index deccd3bc5..1f5e1f90c 100644
--- a/public/llms.txt
+++ b/public/llms.txt
@@ -202,6 +202,7 @@ Docs, tutorials, and reference.
Long-form announcements, launches, and writing from three.ws.
- [Blog](https://three.ws/blog): Editorial index of three.ws launches and long-form posts.
+- [The Stripe of x402: How three.ws Turned Agent Payments Into One Line of Code](https://three.ws/blog/x402-stripe-for-agent-payments): HTTP 402 sat unused for thirty years. Agents revived it. three.ws built the drop in payment modal that makes x402 a one liner, on top of a full stack of agent wallets, wallet intents, on-chain reputation, sniping, and $THREE.
- [See Your 3D Avatar in the Real World — AR Lands on three.ws](https://three.ws/blog/see-your-3d-in-ar): Every 3D model and avatar on three.ws now has a View in AR button. On mobile it places the model in your real space through the camera. On desktop, a QR code gets you there in one scan. No app, no download.
- [Text to 3D Is Live — Type a Prompt, Download a 3D Model](https://three.ws/blog/text-to-3d-is-live): Forge is live on three.ws: type a description and get a textured, downloadable 3D model (GLB) in your browser. Image to 3D from photos works too. Free draft tier, no install.
- [3D + AI + Web3 Just Converged: three.ws Shipped the Whole Stack](https://three.ws/blog/3d-ai-crypto-convergence): A web2 unicorn just raised ~$200M to build 3D AI agents. three.ws is the only crypto-native team that already shipped the full stack: browser 3D, a multi-provider MCP runtime, and on-chain agent wallets that pay each other in USDC. Open source on GitHub, published to npm, and live on Anthropic
diff --git a/public/sitemap/index.html b/public/sitemap/index.html
index e43fe309c..71c4b22e0 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 309 pages on three.ws, grouped by purpose. Looking for the machine-readable versions?</p>
+ <p>All 310 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 309 pages by name, path, or description…" aria-label="Filter pages" autocomplete="off" spellcheck="false" />
+ <input id="sm-filter-input" type="search" placeholder="Filter 310 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>
@@ -1300,7 +1300,7 @@
<section class="sm-section" id="blog">
<header>
- <h2>Blog<span class="sm-count" data-count>28</span></h2>
+ <h2>Blog<span class="sm-count" data-count>29</span></h2>
<p class="sm-section-desc">Long-form announcements, launches, and writing from three.ws.</p>
</header>
<ul class="sm-list">
@@ -1311,6 +1311,13 @@
<span class="sm-desc">Editorial index of three.ws launches and long-form posts.</span>
</a>
</li>
+ <li>
+ <a href="/blog/x402-stripe-for-agent-payments">
+ <span class="sm-title">The Stripe of x402: How three.ws Turned Agent Payments Into One Line of Code</span>
+ <span class="sm-path">/blog/x402-stripe-for-agent-payments</span>
+ <span class="sm-desc">HTTP 402 sat unused for thirty years. Agents revived it. three.ws built the drop in payment modal that makes x402 a one liner, on top of a full stack of agent wallets, wallet intents, on-chain reputation, sniping, and $THREE.</span>
+ </a>
+ </li>
<li>
<a href="/blog/see-your-3d-in-ar">
<span class="sm-title">See Your 3D Avatar in the Real World — AR Lands on three.ws</span>
diff --git a/src/game/coincommunities.js b/src/game/coincommunities.js
index ce25086de..8fab2061d 100644
--- a/src/game/coincommunities.js
+++ b/src/game/coincommunities.js
@@ -304,6 +304,13 @@ export class CoinCommunities {
// unaffected.
this._transparentBg = new URLSearchParams(location.search).get('bg') === 'transparent';
+ // Embed mode: `?biome=<id>` pins every world this session renders to one
+ // curated look (e.g. `noir` for a dark host surface) instead of the per-coin
+ // seeded biome — so a /play embed on a partner page stays visually consistent
+ // with that page. Validated against the biome table; an unknown id is ignored
+ // and the normal seeded look is used, so default play is unaffected.
+ this._biomePin = new URLSearchParams(location.search).get('biome') || null;
+
this._initRenderer();
this._initScene();
@@ -500,7 +507,7 @@ export class CoinCommunities {
// Transparent embed (`?bg=transparent`): the environment skips the sky
// backdrop so the host page shows through; ground, ring, and avatars render.
- this.env = createWorldEnvironment(scene, this.renderer, WORLD_RADIUS, { transparent: this._transparentBg });
+ this.env = createWorldEnvironment(scene, this.renderer, WORLD_RADIUS, { transparent: this._transparentBg, biome: this._biomePin || undefined });
this.world = new Group();
scene.add(this.world);
@@ -774,7 +781,7 @@ export class CoinCommunities {
this.env?.dispose();
// The flagship town pins its signature biome; every other coin draws its
// look from the mint seed.
- const biomeOverride = isHomeTown(coin.mint) ? (coin.biome || HOME_TOWN.biome) : undefined;
+ const biomeOverride = this._biomePin || (isHomeTown(coin.mint) ? (coin.biome || HOME_TOWN.biome) : undefined);
this.env = createWorldEnvironment(this.scene, this.renderer, WORLD_RADIUS, { mint: coin.mint, biome: biomeOverride });
this.ui.toast(`${coin.symbol ? '$' + coin.symbol : coin.name || 'Community'} — ${this.env.biome.label}`, 'info');
diff --git a/src/game/world-env.js b/src/game/world-env.js
index 071a711ef..49708b1d2 100644
--- a/src/game/world-env.js
+++ b/src/game/world-env.js
@@ -119,16 +119,35 @@ const BIOMES = [
},
];
+// Curated biomes reachable ONLY by explicit id (biomeById) — never by the seed
+// modulo, so adding one here can't shift which biome an existing coin's mint maps
+// to. `noir` is a neutral, near-monochrome dark world tuned to match an embedding
+// host's dark UI: its sky and ground sit on the same #1c2530→#0c1116 ramp the
+// three.ws 3D viewer stages use, so a /play embed reads as part of that surface
+// instead of a clashing sunlit biome. Pinned via ?biome=noir.
+const CURATED_BIOMES = [
+ {
+ id: 'noir', label: 'Midnight',
+ sky: ['#1c2530', '#141b24', '#0c1116'], fog: '#0c1116', fogNear: 80, fogFar: 320,
+ hemi: [0x2a3645, 0x0c1116, 0.6], ambient: 0.3,
+ sun: { color: 0xbcd0ff, intensity: 1.25, elevation: 52, azimuth: 135 },
+ ground: 0x141a22, plaza: 0x1c2530, grid: 0x2f3d4e, ring: 0x4ea8ff,
+ hill: 0x141b24, trunk: 0x2a3645, leafA: 0x223044, leafB: 0x2c3c52,
+ flora: 'conifer', density: 12,
+ },
+];
+
// Map any seed to a biome. Exposed so the UI can name the world the player is in.
export function biomeForSeed(seed) {
return BIOMES[(seed >>> 3) % BIOMES.length];
}
// Look up a biome by its archetype id (e.g. a curated world that pins its look
-// instead of drawing it from the mint seed). Returns null for an unknown id so
-// the caller can fall back to the seeded pick.
+// instead of drawing it from the mint seed), searching the seeded set first and
+// the curated-only set second. Returns null for an unknown id so the caller can
+// fall back to the seeded pick.
export function biomeById(id) {
- return BIOMES.find((b) => b.id === id) || null;
+ return BIOMES.find((b) => b.id === id) || CURATED_BIOMES.find((b) => b.id === id) || null;
}
// A vertical gradient backdrop, rendered as the scene background so it's immune
diff --git a/src/mission-control/format.js b/src/mission-control/format.js
new file mode 100644
index 000000000..d118eeb26
--- /dev/null
+++ b/src/mission-control/format.js
@@ -0,0 +1,84 @@
+/**
+ * Mission Control — display formatting. Reuses the wallet-hub primitives where
+ * they already exist (escape, addresses, SOL, explorer links, relative time) and
+ * adds the compact market-data formatters the terminal needs.
+ */
+
+export {
+ escapeHtml,
+ shortAddress,
+ formatSol,
+ formatUsd,
+ timeAgo,
+ explorerTxUrl,
+ explorerAddressUrl,
+ copyToClipboard,
+} from '../agent-wallet-hub/util.js';
+
+/** Compact USD market cap: $1.2K, $34.5K, $1.2M, $3.4B. Null → "—". */
+export function formatCompactUsd(n) {
+ if (n == null || !Number.isFinite(Number(n))) return '—';
+ const v = Number(n);
+ const abs = Math.abs(v);
+ const sign = v < 0 ? '-' : '';
+ if (abs >= 1e9) return `${sign}$${(abs / 1e9).toFixed(abs >= 1e10 ? 0 : 1)}B`;
+ if (abs >= 1e6) return `${sign}$${(abs / 1e6).toFixed(abs >= 1e7 ? 0 : 1)}M`;
+ if (abs >= 1e3) return `${sign}$${(abs / 1e3).toFixed(abs >= 1e4 ? 0 : 1)}K`;
+ return `${sign}$${abs.toFixed(abs < 1 ? 2 : 0)}`;
+}
+
+/** Compact plain number: 1.2K, 34M. */
+export function formatCompact(n) {
+ if (n == null || !Number.isFinite(Number(n))) return '—';
+ const v = Number(n);
+ const abs = Math.abs(v);
+ if (abs >= 1e9) return `${(v / 1e9).toFixed(1)}B`;
+ if (abs >= 1e6) return `${(v / 1e6).toFixed(1)}M`;
+ if (abs >= 1e3) return `${(v / 1e3).toFixed(1)}K`;
+ return String(Math.round(v));
+}
+
+/** Short "age" from a unix-seconds creation time: 4s, 12m, 3h, 2d. */
+export function ageFrom(unixSeconds) {
+ if (!unixSeconds) return '';
+ const sec = Math.max(0, Math.floor(Date.now() / 1000 - unixSeconds));
+ if (sec < 60) return `${sec}s`;
+ if (sec < 3600) return `${Math.floor(sec / 60)}m`;
+ if (sec < 86400) return `${Math.floor(sec / 3600)}h`;
+ return `${Math.floor(sec / 86400)}d`;
+}
+
+/** Signed percent with one decimal: +12.4%, -3.1%. Null → "—". */
+export function formatPct(pct) {
+ if (pct == null || !Number.isFinite(Number(pct))) return '—';
+ const v = Number(pct);
+ return `${v >= 0 ? '+' : ''}${v.toFixed(1)}%`;
+}
+
+/** Signed SOL for PnL: +0.42, -0.13. Null → "—". */
+export function formatSolDelta(sol) {
+ if (sol == null || !Number.isFinite(Number(sol))) return '—';
+ const v = Number(sol);
+ return `${v >= 0 ? '+' : ''}${v.toFixed(3)}`;
+}
+
+/** 'pos' | 'neg' | 'flat' for a signed value — drives PnL colour classes. */
+export function signClass(v) {
+ if (v == null || !Number.isFinite(Number(v))) return 'flat';
+ const n = Number(v);
+ return n > 0 ? 'pos' : n < 0 ? 'neg' : 'flat';
+}
+
+/** Verdict → { label, tone } for firewall/intel chips. */
+export function verdictChip(verdict) {
+ switch (verdict) {
+ case 'allow':
+ return { label: 'CLEAR', tone: 'allow' };
+ case 'warn':
+ return { label: 'CAUTION', tone: 'warn' };
+ case 'block':
+ return { label: 'BLOCK', tone: 'block' };
+ default:
+ return { label: '—', tone: 'unknown' };
+ }
+}
diff --git a/src/mission-control/realtime.js b/src/mission-control/realtime.js
new file mode 100644
index 000000000..40d06d1b6
--- /dev/null
+++ b/src/mission-control/realtime.js
@@ -0,0 +1,171 @@
+/**
+ * Mission Control — real-time plumbing.
+ *
+ * Two primitives the cockpit is built on:
+ *
+ * • Bus — a dependency-free pub/sub so panes never reach into each
+ * other. The feed publishes `mint`/`trade`, the focus pane
+ * subscribes; positions publishes `position`, the keyboard
+ * controller subscribes. One bus, many readers.
+ *
+ * • SseClient — a resilient EventSource wrapper. The server-side SSE endpoints
+ * (api/sniper/stream.js, api/pump/trades-stream.js) deliberately
+ * close every ~90s with an `event: close` to bound serverless
+ * duration; that is a NORMAL lifecycle, not an error, so we
+ * reconnect immediately on a graceful close and only apply
+ * exponential backoff on real failures. Connection state is
+ * surfaced honestly (live / reconnecting / down) — never faked.
+ */
+
+/** Tiny synchronous pub/sub. Handlers that throw never break other handlers. */
+export function createBus() {
+ const channels = new Map();
+ return {
+ on(event, fn) {
+ if (!channels.has(event)) channels.set(event, new Set());
+ channels.get(event).add(fn);
+ return () => channels.get(event)?.delete(fn);
+ },
+ emit(event, payload) {
+ const subs = channels.get(event);
+ if (!subs) return;
+ for (const fn of subs) {
+ try {
+ fn(payload);
+ } catch (err) {
+ console.error(`[mission-control] bus handler for "${event}" threw`, err);
+ }
+ }
+ },
+ clear() {
+ channels.clear();
+ },
+ };
+}
+
+const BACKOFF_BASE_MS = 1_000;
+const BACKOFF_MAX_MS = 15_000;
+// After this many consecutive failed reconnects we report 'down' (still trying,
+// but the UI tells the user the source is unreachable rather than just "slow").
+const DOWN_AFTER_FAILURES = 4;
+
+/**
+ * Resilient SSE client.
+ *
+ * @param {object} opts
+ * @param {string} opts.url — endpoint (without it being opened yet)
+ * @param {Record<string,(data:any)=>void>} opts.events — named SSE event → handler
+ * @param {(state:'live'|'reconnecting'|'down', meta?:object)=>void} [opts.onState]
+ * @returns {{ start():void, stop():void, isLive():boolean }}
+ */
+export function createSseClient({ url, events = {}, onState = () => {} }) {
+ let es = null;
+ let stopped = false;
+ let failures = 0;
+ let reconnectTimer = null;
+ let state = 'reconnecting';
+
+ function setState(next, meta) {
+ if (state === next) return;
+ state = next;
+ onState(next, meta);
+ }
+
+ function clearReconnect() {
+ if (reconnectTimer) {
+ clearTimeout(reconnectTimer);
+ reconnectTimer = null;
+ }
+ }
+
+ function teardownSource() {
+ if (es) {
+ es.onopen = null;
+ es.onerror = null;
+ try {
+ es.close();
+ } catch {
+ /* already closed */
+ }
+ es = null;
+ }
+ }
+
+ function scheduleReconnect(graceful) {
+ teardownSource();
+ if (stopped) return;
+ clearReconnect();
+ // A graceful server-side cycle (duration cap) reconnects fast to keep the
+ // stream continuous; a real error backs off exponentially with jitter.
+ const delay = graceful
+ ? 250 + Math.floor(Math.random() * 250)
+ : Math.min(BACKOFF_MAX_MS, BACKOFF_BASE_MS * 2 ** Math.min(failures, 6)) +
+ Math.floor(Math.random() * 400);
+ reconnectTimer = setTimeout(connect, delay);
+ }
+
+ function connect() {
+ if (stopped) return;
+ clearReconnect();
+ teardownSource();
+ try {
+ es = new EventSource(url, { withCredentials: true });
+ } catch {
+ failures += 1;
+ setState(failures >= DOWN_AFTER_FAILURES ? 'down' : 'reconnecting');
+ scheduleReconnect(false);
+ return;
+ }
+
+ es.onopen = () => {
+ failures = 0;
+ setState('live');
+ };
+
+ es.onerror = () => {
+ // EventSource may be mid-retry (CONNECTING). We take deterministic
+ // control: tear it down and reconnect ourselves with backoff so the
+ // connection-state indicator and timing are honest and bounded.
+ if (stopped) return;
+ failures += 1;
+ setState(failures >= DOWN_AFTER_FAILURES ? 'down' : 'reconnecting');
+ scheduleReconnect(false);
+ };
+
+ for (const [name, fn] of Object.entries(events)) {
+ es.addEventListener(name, (ev) => {
+ let data = null;
+ try {
+ data = ev.data ? JSON.parse(ev.data) : null;
+ } catch {
+ data = null;
+ }
+ // `close` from the server is its duration-cap cycle — reconnect now.
+ if (name === 'close') {
+ scheduleReconnect(true);
+ return;
+ }
+ try {
+ fn(data, ev);
+ } catch (err) {
+ console.error(`[mission-control] SSE "${name}" handler threw`, err);
+ }
+ });
+ }
+ }
+
+ return {
+ start() {
+ stopped = false;
+ failures = 0;
+ setState('reconnecting');
+ connect();
+ },
+ stop() {
+ stopped = true;
+ clearReconnect();
+ teardownSource();
+ },
+ isLive: () => state === 'live',
+ };
+}
diff --git a/workers/agent-sniper/config.js b/workers/agent-sniper/config.js
index d9da9fd4b..368df0b43 100644
--- a/workers/agent-sniper/config.js
+++ b/workers/agent-sniper/config.js
@@ -98,5 +98,34 @@ export function loadConfig() {
// Refine classification with the LLM (free-first). Off by default: the
// deterministic heuristic is instant and free; LLM adds ~1 call per coin.
intelLlm: bool('SNIPER_INTEL_LLM', false),
+ // ── pre-launch creator-wallet radar (task 04) ───────────────────────────
+ // Watch proven creator + smart-money wallets on-chain and detect launch
+ // precursors (funding a fresh deploy wallet / a pump create) at block-0 to
+ // pre-arm a snipe on signal rather than luck. On by default — it's the
+ // platform's earliest edge. SNIPER_RADAR=0 disables it (degrades to the
+ // normal feed-based snipe, reported honestly as paused).
+ radar: bool('SNIPER_RADAR', true),
+ // How often each watched wallet's recent signatures are polled.
+ radarPollMs: Math.max(5_000, num('SNIPER_RADAR_POLL_MS', 15_000)),
+ // Watched wallets scanned per tick (bounds RPC pressure; the set is covered
+ // round-robin across ticks).
+ radarWalletsPerTick: Math.max(5, num('SNIPER_RADAR_WALLETS_PER_TICK', 60)),
+ // How often the watchlist is auto-recurated from the graph.
+ radarWatchlistRefreshMs: Math.max(60_000, num('SNIPER_RADAR_WATCHLIST_REFRESH_MS', 300_000)),
+ // Creator pedigree floor for auto-inclusion (graduated coins).
+ radarMinCreatorGraduated: Math.max(1, num('SNIPER_RADAR_MIN_GRADUATED', 2)),
+ // Reputation floor for smart-money auto-inclusion (0..100).
+ radarSmartMoneyMinScore: Math.max(0, Math.min(100, num('SNIPER_RADAR_SM_MIN_SCORE', 70))),
+ // Hard cap on the monitored set (stale low-signal wallets are evicted).
+ radarMaxWatch: Math.max(20, num('SNIPER_RADAR_MAX_WATCH', 500)),
+ // Default freshness gate for a precursor before it can pre-arm (ms). A
+ // per-strategy radar_max_age_ms overrides it.
+ radarMaxAgeMs: Math.max(10_000, num('SNIPER_RADAR_MAX_AGE_MS', 120_000)),
+ // A SOL outflow at least this large to a fresh wallet counts as deploy
+ // funding (rent + first buy). Below it is ignored as noise.
+ radarMinFundingLamports: Math.max(0, num('SNIPER_RADAR_MIN_FUNDING_LAMPORTS', 30_000_000)),
+ // How long a freshly-funded wallet stays under correlation watch for its
+ // create instruction before it's dropped (ms).
+ radarDeployWatchTtlMs: Math.max(30_000, num('SNIPER_RADAR_DEPLOY_WATCH_TTL_MS', 180_000)),
};
}
diff --git a/workers/agent-sniper/radar-detect.js b/workers/agent-sniper/radar-detect.js
new file mode 100644
index 000000000..103a74778
--- /dev/null
+++ b/workers/agent-sniper/radar-detect.js
@@ -0,0 +1,179 @@
+// agent-sniper — pre-launch radar on-chain precursor detection.
+//
+// Pure parsers + bounded RPC reads that turn a watched wallet's raw transaction
+// history into launch PRECURSORS:
+//
+// (a) create — the watched wallet itself submitted a pump.fun create
+// instruction. The mint is one of the instruction's accounts, so
+// we know the coin at block-0 (or before it indexes on the feed).
+// (b) funding — the watched wallet sent SOL to a brand-new wallet with little
+// history. That fresh wallet is the classic separate deploy
+// wallet; the radar then watches IT for the create that follows.
+//
+// Everything here reads REAL chain data (Helius RPC when keyed, else the platform
+// Solana RPC) — never fabricated. Parsers are exported and unit-tested against
+// jsonParsed transaction fixtures.
+
+import bs58 from 'bs58';
+import {
+ PUMP_PROGRAM_ID,
+ CREATE_DISCRIMINATOR,
+ CREATE_V2_DISCRIMINATOR,
+} from '../../api/_lib/solana/programs.js';
+import { rpcEndpoint } from '../../api/_lib/pump-intel/enrich.js';
+
+const RPC_TIMEOUT_MS = 8_000;
+const WSOL = 'So11111111111111111111111111111111111111112';
+const NON_DEST = new Set([
+ '11111111111111111111111111111111', // System Program
+ WSOL,
+ PUMP_PROGRAM_ID,
+]);
+
+// ── low-level RPC (bounded, never depends on the public endpoint alone) ──────
+async function rpc(endpoint, method, params) {
+ const r = await fetch(endpoint, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ jsonrpc: '2.0', id: 1, method, params }),
+ signal: AbortSignal.timeout(RPC_TIMEOUT_MS),
+ });
+ if (!r.ok) {
+ const e = new Error(`rpc ${method} ${r.status}`);
+ e.status = r.status;
+ throw e;
+ }
+ const body = await r.json();
+ if (body.error) throw new Error(`rpc ${method}: ${body.error.message || body.error.code}`);
+ return body.result;
+}
+
+export function radarEndpoint(network = 'mainnet') {
+ return rpcEndpoint(network);
+}
+
+/**
+ * Signatures for an address newer than `untilSig` (exclusive), newest-first as
+ * the RPC returns them. Bounded to one page — the radar polls fast, so a watched
+ * wallet won't produce more than a page of activity between ticks.
+ * @returns {Promise<Array<{ signature, blockTime, err }>>}
+ */
+export async function fetchNewSignatures(address, { endpoint, untilSig = null, limit = 25 } = {}) {
+ const params = [address, { limit: Math.max(1, Math.min(50, limit)) }];
+ if (untilSig) params[1].until = untilSig;
+ const page = await rpc(endpoint, 'getSignaturesForAddress', params);
+ return Array.isArray(page) ? page : [];
+}
+
+/** Lifetime signature count for a wallet (one page is enough to call it fresh). */
+export async function walletHistoryCount(address, { endpoint, freshMax = 12 } = {}) {
+ const page = await rpc(endpoint, 'getSignaturesForAddress', [address, { limit: freshMax + 1 }]);
+ const total = Array.isArray(page) ? page.length : 0;
+ return { total, fresh: total <= freshMax };
+}
+
+/** jsonParsed transaction for a signature. */
+export async function fetchTransaction(signature, { endpoint }) {
+ return rpc(endpoint, 'getTransaction', [
+ signature,
+ { encoding: 'jsonParsed', maxSupportedTransactionVersion: 0, commitment: 'confirmed' },
+ ]);
+}
+
+// ── pure parsers ─────────────────────────────────────────────────────────────
+
+function keyToStr(k) {
+ return typeof k === 'string' ? k : k?.pubkey || String(k ?? '');
+}
+
+function allInstructions(tx) {
+ const msg = tx?.transaction?.message;
+ const outer = Array.isArray(msg?.instructions) ? msg.instructions : [];
+ const inner = [];
+ for (const set of tx?.meta?.innerInstructions || []) {
+ for (const ix of set?.instructions || []) inner.push(ix);
+ }
+ return [...outer, ...inner];
+}
+
+/**
+ * Find a pump.fun create instruction and return the minted coin address.
+ *
+ * jsonParsed leaves the pump program's instructions un-parsed: `{ programId,
+ * accounts:[pubkey], data:<base58> }`. We match the 8-byte create discriminator
+ * on the decoded data, then read the mint — the FIRST account of a pump create
+ * instruction. Returns null when the tx contains no pump create.
+ *
+ * @param {object} tx jsonParsed getTransaction result
+ * @returns {{ mint: string, variant: 'create'|'create_v2' }|null}
+ */
+export function parseCreateMint(tx) {
+ if (!tx || tx?.meta?.err) return null;
+ for (const ix of allInstructions(tx)) {
+ const programId = ix.programId || keyToStr(ix.program);
+ if (programId !== PUMP_PROGRAM_ID) continue;
+ if (!ix.data || typeof ix.data !== 'string') continue;
+ let bytes;
+ try { bytes = bs58.decode(ix.data); } catch { continue; }
+ if (bytes.length < 8) continue;
+ const head = Buffer.from(bytes.subarray(0, 8));
+ const variant = head.equals(CREATE_V2_DISCRIMINATOR) ? 'create_v2'
+ : head.equals(CREATE_DISCRIMINATOR) ? 'create' : null;
+ if (!variant) continue;
+ const accounts = Array.isArray(ix.accounts) ? ix.accounts.map(keyToStr) : [];
+ const mint = accounts[0];
+ if (mint && mint.length >= 32) return { mint, variant };
+ }
+ return null;
+}
+
+/**
+ * SOL outflows from `fromWallet` to other accounts in this tx (system transfer,
+ * transferChecked, createAccount, createAccountWithSeed). The classic deploy-
+ * funding move: a creator sends rent+buy SOL to a fresh wallet, which then mints.
+ *
+ * @param {object} tx jsonParsed getTransaction result
+ * @param {string} fromWallet the watched wallet
+ * @returns {Array<{ destination: string, lamports: number }>}
+ */
+export function parseFundingTransfers(tx, fromWallet) {
+ if (!tx || tx?.meta?.err || !fromWallet) return [];
+ const out = [];
+ const seen = new Set();
+ for (const ix of allInstructions(tx)) {
+ const p = ix?.parsed;
+ const isSystem = ix.program === 'system' || ix.programId === '11111111111111111111111111111111';
+ if (!p || !isSystem) continue;
+ const t = p.type;
+ if (t !== 'transfer' && t !== 'transferChecked' && t !== 'createAccount' && t !== 'createAccountWithSeed') continue;
+ const info = p.info || {};
+ const src = info.source || info.from;
+ const dest = info.destination || info.newAccount;
+ const lamports = Number(info.lamports);
+ if (src !== fromWallet || !dest || dest === fromWallet) continue;
+ if (NON_DEST.has(dest)) continue;
+ if (!Number.isFinite(lamports) || lamports <= 0) continue;
+ if (seen.has(dest)) {
+ const prev = out.find((o) => o.destination === dest);
+ if (prev) prev.lamports += lamports;
+ continue;
+ }
+ seen.add(dest);
+ out.push({ destination: dest, lamports });
+ }
+ return out;
+}
+
+/**
+ * Classify one transaction made (or signed) by `watchedWallet` into precursors.
+ * Pure — given the parsed tx, returns the precursor list without any I/O. The
+ * orchestrator decides freshness of funded wallets and correlation separately.
+ *
+ * @returns {{ create: {mint,variant}|null, fundings: Array<{destination,lamports}> }}
+ */
+export function classifyTransaction(tx, watchedWallet) {
+ return {
+ create: parseCreateMint(tx),
+ fundings: parseFundingTransfers(tx, watchedWallet),
+ };
+}
diff --git a/workers/agent-sniper/radar-scorer.js b/workers/agent-sniper/radar-scorer.js
new file mode 100644
index 000000000..0e776baa5
--- /dev/null
+++ b/workers/agent-sniper/radar-scorer.js
@@ -0,0 +1,111 @@
+// agent-sniper — pre-launch radar entry scoring. Pure, no I/O.
+//
+// Given a detected launch precursor (a radar_event enriched with the triggering
+// wallet's pedigree + the live smart-money read on the mint, once it exists) and a
+// prelaunch_radar strategy row, decide whether to pre-arm the snipe. Mirrors
+// scorer.js / claim-scorer.js: returns { pass, confidence, reasons }, and reasons
+// always explains the verdict so the worker log shows WHY a precursor was acted on
+// or passed over.
+//
+// The firewall (task 01) still gates the actual buy the instant the mint is real;
+// this is the cheap pre-filter that decides whether a precursor is worth racing.
+
+function n(v) {
+ if (v == null || v === '') return null;
+ const x = Number(v);
+ return Number.isFinite(x) ? x : null;
+}
+
+/**
+ * @param {object} ev detected precursor:
+ * { kind, trigger_wallet, new_wallet?, mint?, signature, observed_ms,
+ * watch: { reason, score, creator_graduated, realized_score, labels },
+ * funder_reputation?: { realized_score, labels, computed }, // smart money on the funder
+ * base_confidence } // 0..1 from detection
+ * @param {object} strat agent_sniper_strategies row (trigger = 'prelaunch_radar')
+ * @param {object} cfg loadConfig() result (radar defaults)
+ * @param {number} nowMs
+ * @returns {{ pass: boolean, confidence: number, reasons: string[] }}
+ */
+export function scoreRadarEvent(ev, strat, cfg, nowMs = Date.now()) {
+ const reasons = [];
+ if (!ev || !ev.mint) return { pass: false, confidence: 0, reasons: ['no_mint'] };
+
+ const watch = ev.watch || {};
+
+ // ── freshness gate ─────────────────────────────────────────────────────────
+ // A precursor we observe stale (worker restart / backfill) must not pre-arm a
+ // snipe minutes after the floor already moved. radar_max_age_ms overrides the
+ // worker default; the precursor's own age is measured from its block time.
+ const maxAge = Number.isFinite(Number(strat.radar_max_age_ms)) && Number(strat.radar_max_age_ms) > 0
+ ? Number(strat.radar_max_age_ms)
+ : cfg.radarMaxAgeMs;
+ if (ev.observed_ms != null) {
+ const age = nowMs - Number(ev.observed_ms);
+ if (Number.isFinite(age) && age > maxAge) {
+ return { pass: false, confidence: 0, reasons: [`precursor_stale:${Math.round(age / 1000)}s>${Math.round(maxAge / 1000)}s`] };
+ }
+ if (Number.isFinite(age) && age >= 0) reasons.push(`age:${Math.round(age / 1000)}s`);
+ }
+
+ // ── creator pedigree gate ──────────────────────────────────────────────────
+ // The triggering creator (or the creator whose fresh wallet was funded) must
+ // have graduated at least N coins. min_creator_graduated_radar overrides the
+ // worker default. A watchlist entry added purely for smart-money reputation may
+ // carry no creator_graduated; the smart-money path below covers that case.
+ const minGrad = strat.min_creator_graduated_radar != null
+ ? n(strat.min_creator_graduated_radar)
+ : cfg.radarMinCreatorGraduated;
+ const graduated = n(watch.creator_graduated);
+ const isSmartMoneyWatch = watch.reason === 'smart_money' || (Array.isArray(watch.labels) && watch.labels.includes('smart_money'));
+
+ if (minGrad != null && minGrad > 0) {
+ const meetsPedigree = graduated != null && graduated >= minGrad;
+ if (!meetsPedigree && !isSmartMoneyWatch) {
+ return { pass: false, confidence: 0, reasons: [`creator_too_few_graduated:${graduated ?? 'n/a'}<${minGrad}`] };
+ }
+ if (meetsPedigree) reasons.push(`creator_graduated:${graduated}`);
+ }
+
+ // ── smart-money funder gate ────────────────────────────────────────────────
+ // require_smart_money_funder demands the triggering wallet (a watched smart-money
+ // address) or the funder of the fresh deploy wallet be proven. The watch entry
+ // itself is proof for a smart_money-reason wallet; otherwise consult the funder's
+ // reputation read. Skips silently only when no reputation has been computed yet.
+ if (strat.require_smart_money_funder === true) {
+ const funderRep = ev.funder_reputation || null;
+ const watchProven = isSmartMoneyWatch && (n(watch.realized_score) ?? 0) > 0;
+ const funderProven = !!(funderRep && funderRep.computed && (n(funderRep.realized_score) ?? 0) >= (cfg.radarSmartMoneyMinScore ?? 70));
+ if (!watchProven && !funderProven) {
+ // Only block when we actually had reputation data and it failed; an
+ // uncomputed funder (brand-new graph) shouldn't silently kill a strong
+ // creator-pedigree signal — but require_smart_money_funder is explicit, so
+ // we honour it strictly: no proof → no pre-arm.
+ return { pass: false, confidence: 0, reasons: ['no_smart_money_funder'] };
+ }
+ reasons.push(watchProven ? 'smart_money_watch' : `smart_money_funder:${Math.round(n(funderRep.realized_score))}`);
+ }
+
+ // ── confidence: detection base, lifted by pedigree + reputation ────────────
+ let confidence = clamp01(n(ev.base_confidence) ?? 0.5);
+ if (graduated != null && graduated > 0) confidence += Math.min(0.2, graduated * 0.03);
+ const watchScore = n(watch.score);
+ if (watchScore != null) confidence += Math.min(0.15, (watchScore / 100) * 0.15);
+ const funderRep = ev.funder_reputation || null;
+ if (funderRep && funderRep.computed) {
+ const rs = n(funderRep.realized_score) ?? 0;
+ if (rs > 0) { confidence += Math.min(0.15, (rs / 100) * 0.15); reasons.push(`funder_rep:${Math.round(rs)}`); }
+ }
+ confidence = clamp01(confidence);
+
+ if (watch.reason) reasons.push(`watch:${watch.reason}`);
+ reasons.push(`kind:${ev.kind}`);
+
+ return { pass: true, confidence: Number(confidence.toFixed(4)), reasons };
+}
+
+function clamp01(v) {
+ const x = Number(v);
+ if (!Number.isFinite(x)) return 0;
+ return Math.max(0, Math.min(1, x));
+}
diff --git a/workers/agent-sniper/radar-watchlist.js b/workers/agent-sniper/radar-watchlist.js
new file mode 100644
index 000000000..80cf64dc9
--- /dev/null
+++ b/workers/agent-sniper/radar-watchlist.js
@@ -0,0 +1,191 @@
+// agent-sniper — pre-launch radar watchlist builder.
+//
+// Auto-curates the set of high-signal wallets the radar monitors, from REAL data:
+//
+// (a) proven creators — addresses whose launches have graduated >= N times,
+// counted from the coin-intel ground truth (pump_coin_intel ⋈
+// pump_coin_outcomes). These are the wallets whose next deploy is worth
+// racing to block-0.
+// (b) proven smart money — top smart_wallet_reputation addresses (task 03),
+// excluding sybil-labelled wallets. A reputable wallet funding a fresh
+// deploy wallet is itself a launch precursor.
+//
+// Persists to radar_watchlist (capped, stale-evicted), and exposes loadWatchlist
+// for the poll loop. The curation merge is a pure, tested function; the DB read +
+// write wrap it. Never throws to the caller — a graph hiccup degrades the
+// watchlist's freshness, never the trade path.
+
+import { sql } from '../../api/_lib/db.js';
+import { log } from './log.js';
+
+/**
+ * Merge creator-pedigree + smart-money candidates into one capped, scored set.
+ * Pure — deterministic given its inputs, so a rerun produces identical rows.
+ *
+ * @param {object} o
+ * @param {Array<{address,graduated,launches}>} o.creators
+ * @param {Array<{address,realized_score,labels}>} o.smartMoney
+ * @param {number} o.cap
+ * @returns {Array<{address,reason,score,creator_graduated,realized_score,labels}>}
+ */
+export function curateWatchlist({ creators = [], smartMoney = [], cap = 500 }) {
+ const byAddr = new Map();
+
+ const bump = (address, patch) => {
+ if (!address) return;
+ const cur = byAddr.get(address) || { address, reason: null, score: 0, creator_graduated: null, realized_score: null, labels: new Set() };
+ if (patch.creator_graduated != null) cur.creator_graduated = Math.max(cur.creator_graduated ?? 0, patch.creator_graduated);
+ if (patch.realized_score != null) cur.realized_score = Math.max(cur.realized_score ?? 0, patch.realized_score);
+ if (patch.score != null) cur.score = Math.max(cur.score, patch.score);
+ if (patch.reason && (!cur.reason || patch.score >= cur.score)) cur.reason = patch.reason;
+ for (const l of patch.labels || []) cur.labels.add(l);
+ byAddr.set(address, cur);
+ };
+
+ for (const c of creators) {
+ const graduated = Number(c.graduated) || 0;
+ if (graduated <= 0) continue;
+ // 50 floor + 10 per graduation, capped at 95 (smart-money proof can push to 100).
+ const score = Math.min(95, 50 + graduated * 10);
+ bump(c.address, { reason: 'creator_graduated', score, creator_graduated: graduated, labels: ['creator'] });
+ }
+
+ for (const s of smartMoney) {
+ const rs = Number(s.realized_score) || 0;
+ if (rs <= 0) continue;
+ const labels = Array.isArray(s.labels) ? s.labels.filter(Boolean) : [];
+ bump(s.address, { reason: 'smart_money', score: rs, realized_score: rs, labels: ['smart_money', ...labels] });
+ }
+
+ return [...byAddr.values()]
+ .map((r) => ({
+ address: r.address,
+ reason: r.reason || 'creator_graduated',
+ score: Math.round(r.score * 100) / 100,
+ creator_graduated: r.creator_graduated,
+ realized_score: r.realized_score,
+ labels: [...r.labels],
+ }))
+ .sort((a, b) => b.score - a.score)
+ .slice(0, Math.max(1, cap));
+}
+
+/**
+ * Recompute + persist the watchlist for a network. Idempotent.
+ * @returns {Promise<{ ok:boolean, watched:number, creators:number, smartMoney:number, evicted:number, reason?:string }>}
+ */
+export async function recomputeWatchlist({ network = 'mainnet', cfg }) {
+ const net = network === 'devnet' ? 'devnet' : 'mainnet';
+ const minGrad = Math.max(1, cfg?.radarMinCreatorGraduated ?? 2);
+ const minScore = Math.max(0, cfg?.radarSmartMoneyMinScore ?? 70);
+ const cap = Math.max(1, cfg?.radarMaxWatch ?? 500);
+
+ let creators = [];
+ let smartMoney = [];
+ try {
+ [creators, smartMoney] = await Promise.all([
+ sql`
+ select i.creator as address,
+ count(*) filter (where coalesce(o.graduated, false)) as graduated,
+ count(*) as launches
+ from pump_coin_intel i
+ join pump_coin_outcomes o on o.mint = i.mint
+ where i.network = ${net} and i.creator is not null
+ group by i.creator
+ having count(*) filter (where coalesce(o.graduated, false)) >= ${minGrad}
+ order by graduated desc
+ limit ${cap}
+ `,
+ sql`
+ select address, realized_score, labels
+ from smart_wallet_reputation
+ where network = ${net}
+ and realized_score >= ${minScore}
+ and trades_seen >= 3
+ and not (labels @> array['sybil'])
+ order by realized_score desc
+ limit ${cap}
+ `,
+ ]);
+ } catch (err) {
+ log.warn?.('radar watchlist read failed', { err: err?.message });
+ return { ok: false, watched: 0, creators: 0, smartMoney: 0, evicted: 0, reason: 'read_failed' };
+ }
+
+ const curated = curateWatchlist({ creators, smartMoney, cap });
+ if (!curated.length) {
+ return { ok: true, watched: 0, creators: creators.length, smartMoney: smartMoney.length, evicted: 0, reason: 'no_signal' };
+ }
+
+ let evicted = 0;
+ try {
+ for (const w of curated) {
+ await sql`
+ insert into radar_watchlist
+ (address, network, reason, source, score, creator_graduated, realized_score, labels, refreshed_at)
+ values
+ (${w.address}, ${net}, ${w.reason}, 'auto', ${w.score},
+ ${w.creator_graduated}, ${w.realized_score}, ${w.labels}, now())
+ on conflict (address, network) do update set
+ reason = excluded.reason,
+ score = excluded.score,
+ creator_graduated = excluded.creator_graduated,
+ realized_score = excluded.realized_score,
+ labels = excluded.labels,
+ -- a manually-pinned wallet keeps its source; auto re-affirms auto.
+ source = case when radar_watchlist.source = 'manual' then 'manual' else 'auto' end,
+ refreshed_at = now()
+ `;
+ }
+ // Evict auto wallets that fell out of the curated set this run and haven't
+ // fired a precursor recently — keeps the monitored set lean + high-signal.
+ // Manual pins are never evicted.
+ const staleCutoffMs = Math.max(2, 2) * Math.max(60_000, cfg?.radarWatchlistRefreshMs ?? 300_000);
+ const cutoffIso = new Date(Date.now() - staleCutoffMs).toISOString();
+ const [del] = await sql`
+ with removed as (
+ delete from radar_watchlist
+ where network = ${net} and source = 'auto'
+ and refreshed_at < ${cutoffIso}
+ and (last_hit_at is null or last_hit_at < ${cutoffIso})
+ returning 1
+ )
+ select count(*)::int as n from removed
+ `;
+ evicted = del?.n ?? 0;
+ } catch (err) {
+ log.warn?.('radar watchlist persist failed', { err: err?.message });
+ return { ok: false, watched: curated.length, creators: creators.length, smartMoney: smartMoney.length, evicted, reason: 'persist_failed' };
+ }
+
+ return { ok: true, watched: curated.length, creators: creators.length, smartMoney: smartMoney.length, evicted };
+}
+
+/**
+ * Load the active watchlist for the poll loop. Returns a Map address → row.
+ * @returns {Promise<Map<string, object>>}
+ */
+export async function loadWatchlist(network = 'mainnet', limit = 1000) {
+ const net = network === 'devnet' ? 'devnet' : 'mainnet';
+ const rows = await sql`
+ select address, reason, source, score, creator_graduated, realized_score, labels, last_hit_at
+ from radar_watchlist
+ where network = ${net}
+ order by score desc
+ limit ${Math.max(1, Math.min(5000, limit))}
+ `;
+ return new Map(rows.map((r) => [r.address, r]));
+}
+
+/** Record that a watched wallet fired a precursor (drives stale-eviction + UI). */
+export async function markWatchlistHit(address, network) {
+ const net = network === 'devnet' ? 'devnet' : 'mainnet';
+ try {
+ await sql`
+ update radar_watchlist set last_hit_at = now(), hits = hits + 1
+ where address = ${address} and network = ${net}
+ `;
+ } catch (err) {
+ log.warn?.('radar watchlist hit update failed', { address, err: err?.message });
+ }
+}