Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
feat: implement autonomous agent intro features
udvka9832f11d64b
diff --git a/.env.example b/.env.exampleindex 4de869358..4545e3626 100644--- a/.env.example+++ b/.env.example@@ -703,6 +703,26 @@ APP_ORIGIN=https://three.ws# Generate: openssl rand -base64 32CRON_SECRET=+# ── Agent activity engine (api/_lib/circulation.js, /api/cron/pulse-tick) ─────+# Operates a pool of platform-owned agents that transact with one another on-chain+# (tips, payments, trades, launches, on-chain registration) so the live money feed+# reflects real wallet activity. Fully inert unless ENABLED is truthy AND a funded+# treasury secret is set. All amounts are small and topped up just-in-time.+CIRCULATION_ENABLED=+# 64-byte Solana secret key (base58, base64, or JSON array) for the funded treasury+# wallet the engine tops agent wallets up from.+CIRCULATION_TREASURY_SECRET=+# 'mainnet' (default) or 'devnet'.+CIRCULATION_NETWORK=+# Target number of operated agents (default 14) and light actions per tick (default 2).+CIRCULATION_POOL_TARGET=+CIRCULATION_ACTIONS_PER_TICK=+# Optional: enables on-chain (ERC-8004) agent registration. EVM private key (0x…)+# of a gas-funded treasury wallet, plus the chain id (default 8453 / Base). Without+# this, the deploy action is skipped.+CIRCULATION_EVM_TREASURY_SECRET=+CIRCULATION_EVM_CHAIN_ID=+# ── IRL proof-of-presence (epic IRL-Hardening H3) ────────────────────────────# HMAC key that signs the short-lived proof-of-presence tokens minted by# POST /api/irl/fix-token and verified on the GET /api/irl/pins nearby readdiff --git a/CHANGELOG.md b/CHANGELOG.mdindex 564d0af05..298e4be9d 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -16,6 +16,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **Mission Control's live launch feed never goes dark** — The terminal's Live feed streams brand-new pump.fun launches over a real-time socket — but when that upstream socket goes quiet, the firehose pane could sit empty with nothing to trade. The feed now has a live safety net: it also reads pump.fun's newest launches directly and fills the pane the instant you open the terminal, then keeps backfilling behind the socket so a momentary upstream hiccup never blanks the board. Real launches throughout, de-duplicated so a coin never shows twice — whichever source sees it first wins. (`/terminal`) `[fix, improvement]`- **Steadier live feeds under load** — The real-time money feeds that power the Galaxy money-cam and Money Pulse are now more resilient when our cache layer is under pressure. The platform cache can run on its own dedicated store, separate from the rate limiter, so a busy moment no longer slows feed responses or spends the limiter's budget — and even when the cache is degraded, feeds fall back instantly instead of waiting. You'll see the live maps stay smooth during traffic spikes. `[infra, improvement]`- **The gallery now seeds itself with studio-quality, fully-rigged Avaturn avatars** — A new background generator quietly grows the public gallery with photorealistic, animation-ready Avaturn avatars — each one a fresh randomized character (body, outfit, hair, and colors) built from Avaturn's own catalog and exported with a complete rig, so it walks and emotes out of the box. They land under brand-new single-word creator accounts just like our other seeded creations. The cadence starts conservative and ramps up over time. `[feature, improvement]`+- **The marketplace now shows a live feed of what's selling** — The agent marketplace has a new 'Live sales' ticker that scrolls the most recent skill unlocks and trials happening across the platform in real time — which agent, which skill, and how much it sold for. It's a quick read on what the market actually values, and every entry links straight to that agent's page. The strip pauses when you hover so you can catch one, and it stays out of the way: it only appears on the main browse view and quietly hides itself when you're searching or filtering. (`/marketplace`) `[feature]`- **The post-create screen now greets you with a living agent** — After you create an avatar or agent, the 'what's next' screen no longer shows your character frozen in a stiff T-pose. It now renders a live, gently breathing 3D agent you can spin with a drag — the same idle motion your embeds use — so the moment your agent is ready actually feels ready. A one-time confetti burst celebrates the milestone (and stays out of the way if you prefer reduced motion). For agents, the embed snippet is right there to copy without leaving the page, plus one-tap buttons to copy your agent's public link or share it on X. The steps you've already done — giving your agent a brain, deploying it on-chain — now show a checkmark, and an 'I'll do this later' link makes the exit obvious. `[feature, improvement]`- **The trader leaderboard is never empty: live top Solana traders until agents take over** — The leaderboard ranks three.ws agents by a provable, on-chain track record — but until an agent has actually traded in a window, the board had nothing to show. Now, whenever no agent yet has a verified record, the flagship board falls back to the live ranking of the top Solana traders by realized profit (real wallets, real P&L, sourced live from kolscan), each row deep-linked to its on-chain account. The moment an agent earns a record it takes precedence again. Real data throughout — if the live feed is briefly unreachable, the board shows an honest 'be the first' state, never fabricated rows. (`/leaderboard`) `[feature, improvement]`- **Trading Swarms: pool capital with other agents and split the profits** — A new way to trade together. Create a swarm and a dedicated treasury wallet is provisioned on-chain; you and other agents fund it with real SOL. The swarm only buys a coin when enough of its members' verified track records already agree on it — a reputation-weighted consensus, not one agent's hunch — and every trade still passes the same safety firewall and spend limits as a solo snipe. When a position closes in profit, the gain is paid back to every member pro-rata by their share, on-chain and fully auditable, minus an optional creator fee. You can see the live vote on every decision, the treasury balance, each member's share, and the full payout ledger. Exit and redeem your share any time, no single member can capture the treasury, and any qualifying member can hit the kill switch. Find it under Discover → Trading Swarms. (`/swarms`) `[feature]`diff --git a/api/_lib/avaturn-headless.js b/api/_lib/avaturn-headless.jsindex e9545f449..36ebf94e6 100644--- a/api/_lib/avaturn-headless.js+++ b/api/_lib/avaturn-headless.js@@ -69,28 +69,27 @@ async function pullGlb(exportUrl, maxBytes) {}/**- * Drive one full headless Avaturn export.+ * Drive one full headless Avaturn export. With no `sessionUrl` the harness opens+ * the public demo editor (no API key) — that's the default seed path.** @param {{- * sessionUrl: string,* seed: string,* bodyType?: 'male'|'female',+ * sessionUrl?: string,* timeoutMs?: number,* maxBytes?: number,* }} opts* @returns {Promise<{ glbBytes: Buffer, exportUrl: string, look: any }>}*/export async function exportRandomAvaturnAvatar({- sessionUrl,seed,bodyType = 'male',+ sessionUrl,timeoutMs = 110_000,maxBytes = DEFAULT_MAX_GLB_BYTES,}) {- if (!sessionUrl) throw Object.assign(new Error('sessionUrl required'), { code: 'invalid_args' });-const harness = new URL('/internal/avaturn-forge.html', env.APP_ORIGIN);- harness.searchParams.set('session', sessionUrl);+ if (sessionUrl) harness.searchParams.set('session', sessionUrl);harness.searchParams.set('seed', String(seed));harness.searchParams.set('bodyType', bodyType);diff --git a/api/_lib/avaturn-seed.js b/api/_lib/avaturn-seed.jsindex e6d4dcb6d..6b418f238 100644--- a/api/_lib/avaturn-seed.js+++ b/api/_lib/avaturn-seed.js@@ -179,3 +179,25 @@ export function pickRandomLook(seed, { bodies, assets, bodyType }) {export function pickBodyType(seed) {return mulberry32(hashSeed(seed + ':bodytype'))() < 0.5 ? 'male' : 'female';}++// ── Public editor (no API key) ──────────────────────────────────────────────────+// The seed cron drives Avaturn's *public* editor — the same iframe the demo uses+// — so it needs no API key or per-account session. The SDK opens this URL, the+// catalog is the public one, and exportAvatar() returns a rigged GLB.++export const AVATURN_DEFAULT_EDITOR = 'https://preview.avaturn.dev/editor';+export const AVATURN_DEFAULT_BODY = {+ male: 'https://assets.avaturn.me/editor_resources/default_male.glb',+ female: 'https://assets.avaturn.me/editor_resources/default_female.glb',+};++/**+ * Build the public Avaturn editor URL seeded with a default body for the+ * requested gender. The SDK appends `?sdk=true&noui=true` itself.+ * @param {'male'|'female'} [bodyType]+ * @returns {string}+ */+export function defaultEditorUrl(bodyType = 'male') {+ const link = AVATURN_DEFAULT_BODY[bodyType] || AVATURN_DEFAULT_BODY.male;+ return `${AVATURN_DEFAULT_EDITOR}?avatar_link=${encodeURIComponent(link)}`;+}diff --git a/api/_lib/avaturn.js b/api/_lib/avaturn.jsdeleted file mode 100644index 5671af0f8..000000000--- a/api/_lib/avaturn.js+++ /dev/null@@ -1,71 +0,0 @@-// @ts-check-// Server-side Avaturn helpers shared by the onboarding photo flow and the-// avaturn-seed cron.-//-// The seed cron needs a *catalog* session — an editor session opened WITHOUT-// selfie photos, so the headless driver can pick a body + assets from the-// account's own catalog and export a fully-rigged GLB. That's a different shape-// from the photo→avatar onboarding session, hence its own helper here.--import { env } from './env.js';--const SESSION_PATH = '/api/v1/sessions';-const REQUEST_TIMEOUT_MS = 20_000;--/**- * @typedef {{ sessionUrl: string, expiresAt: string | null, raw: any }} AvaturnSession- */--/**- * Open an Avaturn editor session with no photos so the catalog (bodies + assets)- * can be randomized in the editor. Attributed to `externalUserId` so Avaturn- * tracks usage per synthetic account.- *- * @param {{ externalUserId: string, bodyType?: 'male'|'female', signal?: AbortSignal }} opts- * @returns {Promise<AvaturnSession>}- */-export async function createCatalogSession({ externalUserId, bodyType = 'male', signal }) {- if (!env.AVATURN_API_KEY) {- throw Object.assign(new Error('AVATURN_API_KEY unset'), { code: 'not_configured', status: 501 });- }- const url = `${env.AVATURN_API_URL}${SESSION_PATH}`;- // session_type 'create' opens the editor's create UI on a default body; with- // no photos the user (here, the headless driver) builds the avatar from the- // catalog. export_type 'url' makes exportAvatar resolve to a fetchable GLB- // URL rather than a multi-MB data URI.- const body = {- external_user_id: externalUserId,- body_type: bodyType,- session_type: 'create',- export_type: 'url',- };-- const upstream = await fetch(url, {- method: 'POST',- headers: {- authorization: `Bearer ${env.AVATURN_API_KEY}`,- 'content-type': 'application/json',- accept: 'application/json',- },- body: JSON.stringify(body),- signal: signal ?? AbortSignal.timeout(REQUEST_TIMEOUT_MS),- });-- if (!upstream.ok) {- const text = await upstream.text().catch(() => '');- throw Object.assign(new Error(`avaturn session ${upstream.status}: ${text.slice(0, 200)}`), {- code: upstream.status === 401 ? 'upstream_auth' : 'upstream_error',- status: upstream.status >= 500 ? 502 : upstream.status,- });- }-- const data = await upstream.json();- const sessionUrl = data?.session_url || data?.url || data?.iframe_url;- if (!sessionUrl) {- throw Object.assign(new Error('avaturn response missing session_url'), {- code: 'upstream_error',- status: 502,- });- }- return { sessionUrl, expiresAt: data?.expires_at ?? null, raw: data };-}diff --git a/api/_lib/circulation-personas.js b/api/_lib/circulation-personas.jsnew file mode 100644index 000000000..1d665cb9b--- /dev/null+++ b/api/_lib/circulation-personas.js@@ -0,0 +1,240 @@+// Persona + content library for the agent activity engine (api/_lib/circulation.js).+// These describe the autonomous agents the platform operates: each becomes a real,+// published marketplace listing with its own custodial wallet, and they transact+// with one another on-chain (tips, payments, trades) and launch coins through the+// platform's own pump.fun launcher. Content here is plain platform copy — no coin+// is named or promoted except $THREE, which the trade engine biases toward.++// Marketplace category must be one of the agent_identities category enum values.+export const PERSONAS = [+ {+ handle: 'atlas',+ name: 'Atlas',+ category: 'programming',+ tags: ['coding', 'review', 'refactor'],+ description: 'A senior engineering copilot that reads a repo, explains the tricky parts, and ships clean diffs.',+ system_prompt:+ 'You are Atlas, a senior software engineer. You read code carefully before changing it, match existing patterns, and explain trade-offs plainly. You never leave TODOs or stubs.',+ greeting: 'Point me at a repo or a file and I will get to work.',+ },+ {+ handle: 'vega',+ name: 'Vega',+ category: 'marketing',+ tags: ['growth', 'copy', 'launch'],+ description: 'A growth strategist that turns a rough idea into a launch plan, landing copy, and a week of posts.',+ system_prompt:+ 'You are Vega, a growth and marketing strategist. You write sharp, specific copy and concrete go-to-market plans. No fluff, no buzzwords.',+ greeting: 'Tell me what you are launching and who it is for.',+ },+ {+ handle: 'sable',+ name: 'Sable',+ category: 'design',+ tags: ['ui', 'brand', 'product'],+ description: 'A product designer with taste — interface critique, brand systems, and pixel-level polish.',+ system_prompt:+ 'You are Sable, a product designer. You give precise, opinionated feedback on UI and brand, grounded in real design systems.',+ greeting: 'Share a screen or a brief and I will sharpen it.',+ },+ {+ handle: 'orion',+ name: 'Orion',+ category: 'general',+ tags: ['research', 'analysis', 'synthesis'],+ description: 'A research analyst that gathers sources, weighs them, and writes you a cited brief.',+ system_prompt:+ 'You are Orion, a research analyst. You synthesize sources, separate fact from claim, and always show your reasoning.',+ greeting: 'Give me a question worth digging into.',+ },+ {+ handle: 'lyra',+ name: 'Lyra',+ category: 'copywriting',+ tags: ['writing', 'editing', 'story'],+ description: 'An editor that tightens your prose without flattening your voice.',+ system_prompt:+ 'You are Lyra, an editor. You cut what is dead, keep what sings, and never homogenize a writer’s voice.',+ greeting: 'Paste a draft and tell me the voice you want to keep.',+ },+ {+ handle: 'cipher',+ name: 'Cipher',+ category: 'programming',+ tags: ['security', 'audit', 'solana'],+ description: 'A security reviewer that hunts for the bug class you forgot about.',+ system_prompt:+ 'You are Cipher, a security reviewer. You think adversarially, prioritize by exploitability, and propose concrete fixes.',+ greeting: 'Show me the contract or the diff you are worried about.',+ },+ {+ handle: 'nova',+ name: 'Nova',+ category: 'entertainment',+ tags: ['ideas', 'games', 'worlds'],+ description: 'A creative partner for game loops, world lore, and the hook that makes someone share it.',+ system_prompt:+ 'You are Nova, a creative director for interactive experiences. You pitch bold, specific ideas and know why they would spread.',+ greeting: 'What world are we building today?',+ },+ {+ handle: 'quill',+ name: 'Quill',+ category: 'education',+ tags: ['tutor', 'explain', 'learn'],+ description: 'A patient tutor that meets you where you are and gets you to the next idea.',+ system_prompt:+ 'You are Quill, a tutor. You diagnose the gap, explain with the right example, and check understanding before moving on.',+ greeting: 'What are we learning? Start anywhere.',+ },+ {+ handle: 'flint',+ name: 'Flint',+ category: 'career',+ tags: ['resume', 'interview', 'strategy'],+ description: 'A career coach that rewrites your resume and runs the mock interview you are dreading.',+ system_prompt:+ 'You are Flint, a career coach. You are direct, practical, and focused on the next concrete move.',+ greeting: 'Where are you in the search? Let us make a plan.',+ },+ {+ handle: 'meridian',+ name: 'Meridian',+ category: 'office',+ tags: ['ops', 'docs', 'automation'],+ description: 'An operations agent that turns a messy process into a checklist and a template.',+ system_prompt:+ 'You are Meridian, an operations specialist. You make work legible: clear steps, owners, and artifacts.',+ greeting: 'Describe the process and I will systematize it.',+ },+ {+ handle: 'pixel',+ name: 'Pixel',+ category: 'games',+ tags: ['gamedev', 'mechanics', 'balance'],+ description: 'A game designer that pressure-tests your mechanics and tunes the difficulty curve.',+ system_prompt:+ 'You are Pixel, a game designer. You reason about player motivation, loops, and balance with real examples.',+ greeting: 'What is the core loop? Let us make it sing.',+ },+ {+ handle: 'echo',+ name: 'Echo',+ category: 'emotions',+ tags: ['reflection', 'journaling', 'support'],+ description: 'A reflective companion for thinking out loud and naming what you actually feel.',+ system_prompt:+ 'You are Echo, a reflective companion. You listen, reflect back precisely, and ask the question under the question.',+ greeting: 'What is on your mind? No wrong place to start.',+ },+ {+ handle: 'forge',+ name: 'Forge',+ category: 'design',+ tags: ['3d', 'avatar', 'assets'],+ description: 'A 3D art director that briefs avatars, props, and the look that reads at a glance.',+ system_prompt:+ 'You are Forge, a 3D art director. You give concrete prompts and critique silhouette, material, and readability.',+ greeting: 'Describe the character or asset and I will direct it.',+ },+ {+ handle: 'tally',+ name: 'Tally',+ category: 'academic',+ tags: ['math', 'data', 'proofs'],+ description: 'A quantitative agent for the derivation, the model, and the sanity check.',+ system_prompt:+ 'You are Tally, a quantitative analyst. You are rigorous, show every step, and flag where assumptions bite.',+ greeting: 'Give me the problem and the constraints.',+ },+ {+ handle: 'harbor',+ name: 'Harbor',+ category: 'life',+ tags: ['planning', 'habits', 'logistics'],+ description: 'A life-logistics agent for the trip, the move, and the week that finally goes to plan.',+ system_prompt:+ 'You are Harbor, a planning assistant. You turn vague intentions into dated, doable steps.',+ greeting: 'What are we planning? Give me the rough shape.',+ },+ {+ handle: 'glyph',+ name: 'Glyph',+ category: 'translation',+ tags: ['language', 'localize', 'nuance'],+ description: 'A translator that keeps tone and idiom intact across languages.',+ system_prompt:+ 'You are Glyph, a translator. You preserve register, idiom, and intent — not just words.',+ greeting: 'Paste the text and tell me the target language and tone.',+ },+];++// Coin themes used when an agent launches a coin through the platform launcher.+// Names/symbols are generic platform-economy themes — these are coins minted by the+// platform's own agents and surfaced in the launch directory, never third-party mints.+export const COIN_THEMES = [+ { name: 'Signal', symbol: 'SIGNAL', description: 'A coin for agents that surface the signal in the noise.' },+ { name: 'Cadence', symbol: 'CADENCE', description: 'Keeping time for the autonomous money layer.' },+ { name: 'Lumen', symbol: 'LUMEN', description: 'Light for the on-chain agent economy.' },+ { name: 'Quanta', symbol: 'QUANTA', description: 'Small units of agent work, made liquid.' },+ { name: 'Vector', symbol: 'VECTOR', description: 'Direction and magnitude for agent collectives.' },+ { name: 'Ember', symbol: 'EMBER', description: 'A spark for builders shipping with agents.' },+ { name: 'Strata', symbol: 'STRATA', description: 'Layers of value across the agent stack.' },+ { name: 'Helix', symbol: 'HELIX', description: 'The double strand of agents and their economies.' },+ { name: 'Pulsar', symbol: 'PULSAR', description: 'A steady beat for the money pulse.' },+ { name: 'Aurora', symbol: 'AURORA', description: 'First light for a new class of agent.' },+ { name: 'Tessera', symbol: 'TESSERA', description: 'One tile in the mosaic of agent work.' },+ { name: 'Cobalt', symbol: 'COBALT', description: 'Hard, bright, and built to last.' },+ { name: 'Nimbus', symbol: 'NIMBUS', description: 'Compute and capital, condensed.' },+ { name: 'Vertex', symbol: 'VERTEX', description: 'Where agent and economy meet.' },+];++// Short, varied service names attached to agent-to-agent payments (recorded as+// x402-category spends) so the payment feed reads like real machine commerce.+export const PAYMENT_SERVICES = [+ 'code-review',+ 'data-enrichment',+ 'image-render',+ 'summarize-thread',+ 'market-scan',+ 'translate-doc',+ 'sentiment-pass',+ 'fact-check',+ 'lore-pack',+ 'quote-pull',+ 'brief-draft',+ 'audit-snippet',+];++// Review bodies an agent's owner leaves on another agent's marketplace listing.+export const REVIEW_LINES = [+ 'Fast, accurate, and it actually wired the whole thing end to end.',+ 'Handed it a vague brief and got back something I could ship.',+ 'Reads context well — did not have to repeat myself.',+ 'Saved me an afternoon. Came back for a second pass already.',+ 'The output was clean and the reasoning was easy to follow.',+ 'Caught an edge case I completely missed. Worth it.',+ 'Tone was exactly right. Minimal editing on my end.',+ 'Quietly competent. Just gets the job done.',+ 'Better than I expected from a one-line prompt.',+ 'Solid. Will route more work here.',+];++// Names borrowed for synthetic owner accounts so the agents feel operated by+// real people, not a single faceless account.+export const OWNER_FIRST_NAMES = [+ 'mara', 'devin', 'noor', 'kai', 'sol', 'rhea', 'theo', 'iris', 'jun', 'lena',+ 'arman', 'priya', 'cole', 'mika', 'sasha', 'remy', 'tariq', 'wren', 'zane', 'asha',+];++export function pick(arr) {+ return arr[Math.floor(Math.random() * arr.length)];+}++export function pickTwo(arr) {+ if (arr.length < 2) return [arr[0], arr[0]];+ const a = Math.floor(Math.random() * arr.length);+ let b = Math.floor(Math.random() * (arr.length - 1));+ if (b >= a) b += 1;+ return [arr[a], arr[b]];+}diff --git a/api/_lib/circulation.js b/api/_lib/circulation.jsnew file mode 100644index 000000000..63900b588--- /dev/null+++ b/api/_lib/circulation.js@@ -0,0 +1,800 @@+// @ts-check+// Autonomous agent activity engine.+//+// The platform operates a pool of real agents — each a published marketplace+// listing with its own custodial Solana (and optionally EVM) wallet. On every+// tick this engine makes those agents do real, on-chain things with one another:+// send SOL tips, pay each other for services (recorded as x402 spends), trade+// coins through the platform's own pump.fun trade engine, launch coins through+// the platform launcher, register on-chain identities, and leave marketplace+// reviews. Every event flows through the SAME real code paths a human-owned agent+// uses, so it all lands in the live money feed as genuine wallet activity — no+// synthetic rows, no fake numbers.+//+// Funds originate from a single treasury wallet the operator funds. The engine+// tops agent wallets up from the treasury just-in-time and keeps per-tick amounts+// small. Everything is gated behind CIRCULATION_ENABLED + a treasury secret; with+// neither set the engine is fully inert.++import { sql } from './db.js';+import { env } from './env.js';+import { randomUUID } from 'node:crypto';+import {+ ensureAgentWallet,+ recoverSolanaAgentKeypair,+ getOrCreateAgentEvmWallet,+ recoverAgentKey,+} from './agent-wallet.js';+import { recordCustodyEvent } from './agent-trade-guards.js';+import { solanaConnection } from './agent-pumpfun.js';+import { createSession } from './auth.js';+import { solUsdPrice } from './avatar-wallet.js';+import { CHAIN_BY_ID } from './erc8004-chains.js';+import { publicUrl as r2PublicUrl } from './r2.js';+import { pinToIPFS } from './ipfs-pin.js';+import {+ PERSONAS,+ COIN_THEMES,+ PAYMENT_SERVICES,+ REVIEW_LINES,+ OWNER_FIRST_NAMES,+ pick,+ pickTwo,+} from './circulation-personas.js';++const SOL = 1_000_000_000;++// Conservative, real economics. Every number here is small on purpose — the goal+// is a steady, believable heartbeat, not volume for its own sake.+const FEE_BUFFER = Math.floor(0.0009 * SOL); // tx fees + ATA rent headroom+const AGENT_FLOOR = Math.floor(0.02 * SOL); // top a working wallet up to this+const LAUNCH_FLOOR = Math.floor(0.034 * SOL); // pump create + tiny dev buy + fees+const TIP_MIN = Math.floor(0.001 * SOL);+const TIP_MAX = Math.floor(0.006 * SOL);+const PAY_MIN = Math.floor(0.0012 * SOL);+const PAY_MAX = Math.floor(0.01 * SOL);++const THREE_MINT = () => env.THREE_TOKEN_MINT || 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++function clampInt(v, dflt, lo, hi) {+ const n = Number.parseInt(String(v ?? ''), 10);+ if (!Number.isFinite(n)) return dflt;+ return Math.min(hi, Math.max(lo, n));+}++export function config() {+ const enabledRaw = String(process.env.CIRCULATION_ENABLED ?? '').toLowerCase();+ return {+ enabled: enabledRaw === '1' || enabledRaw === 'true' || enabledRaw === 'yes',+ network: process.env.CIRCULATION_NETWORK === 'devnet' ? 'devnet' : 'mainnet',+ treasurySecret: (process.env.CIRCULATION_TREASURY_SECRET || '').trim(),+ evmTreasurySecret: (process.env.CIRCULATION_EVM_TREASURY_SECRET || '').trim(),+ evmChainId: clampInt(process.env.CIRCULATION_EVM_CHAIN_ID, 8453, 1, 1_000_000_000),+ poolTarget: clampInt(process.env.CIRCULATION_POOL_TARGET, 14, 2, 80),+ actionsPerTick: clampInt(process.env.CIRCULATION_ACTIONS_PER_TICK, 2, 1, 6),+ origin: env.APP_ORIGIN || 'https://three.ws',+ };+}++// A skip is an expected, recoverable non-event (treasury low, pool too small) —+// never an error. It is logged and the tick moves on.+class Skip extends Error {}++function randBetween(lo, hi) {+ return lo + Math.floor(Math.random() * Math.max(1, hi - lo));+}++// ── one-time schema guard ─────────────────────────────────────────────────────+// Self-contained so the engine works whether or not the migration has been+// applied yet. CREATE TABLE IF NOT EXISTS is idempotent and cheap.+let _ensured = false;+async function ensureSchema() {+ if (_ensured) return;+ await sql`+ create table if not exists circulation_actions (+ id bigserial primary key,+ kind text not null,+ network text,+ actor_agent_id uuid,+ counterparty_agent_id uuid,+ signature text,+ amount_lamports bigint,+ status text not null default 'ok',+ detail jsonb not null default '{}'::jsonb,+ created_at timestamptz not null default now()+ )+ `;+ await sql`create index if not exists circulation_actions_created on circulation_actions(created_at desc)`;+ await sql`create index if not exists circulation_actions_kind on circulation_actions(kind, created_at desc)`;+ _ensured = true;+}++async function logAction(row) {+ try {+ await sql`+ insert into circulation_actions+ (kind, network, actor_agent_id, counterparty_agent_id, signature, amount_lamports, status, detail)+ values (+ ${row.kind}, ${row.network ?? null}, ${row.actorAgentId ?? null}, ${row.counterpartyAgentId ?? null},+ ${row.signature ?? null}, ${row.amountLamports != null ? String(row.amountLamports) : null},+ ${row.status ?? 'ok'}, ${JSON.stringify(row.detail ?? {})}::jsonb+ )+ `;+ } catch (e) {+ console.warn('[circulation] logAction failed', e?.message);+ }+}++async function recentCount(kind, intervalSql) {+ const [r] = await sql`+ select count(*)::int as count from circulation_actions+ where kind = ${kind} and status = 'ok' and created_at > now() - ${intervalSql}::interval+ `;+ return r?.count ?? 0;+}++// ── treasury + low-level Solana transfer ──────────────────────────────────────++function decodeSecretKey(secret, bs58) {+ let bytes = null;+ try {+ const d = bs58.decode(secret);+ if (d.length === 64) bytes = d;+ } catch { /* not base58 */ }+ if (!bytes) {+ try {+ const b = Buffer.from(secret, 'base64');+ if (b.length === 64) bytes = b;+ } catch { /* not base64 */ }+ }+ if (!bytes) {+ try {+ const arr = JSON.parse(secret);+ if (Array.isArray(arr) && arr.length === 64) bytes = Uint8Array.from(arr);+ } catch { /* not json */ }+ }+ return bytes ? Uint8Array.from(bytes) : null;+}++async function treasuryKeypair(cfg) {+ if (!cfg.treasurySecret) throw new Skip('CIRCULATION_TREASURY_SECRET unset');+ const { Keypair } = await import('@solana/web3.js');+ const bs58 = (await import('bs58')).default;+ const bytes = decodeSecretKey(cfg.treasurySecret, bs58);+ if (!bytes) throw new Error('CIRCULATION_TREASURY_SECRET must be a 64-byte base58, base64, or JSON-array secret key');+ return Keypair.fromSecretKey(bytes);+}++async function transferSol(conn, fromKp, toAddress, lamports) {+ const {+ PublicKey,+ SystemProgram,+ TransactionMessage,+ VersionedTransaction,+ ComputeBudgetProgram,+ } = await import('@solana/web3.js');+ const toPk = new PublicKey(toAddress);+ const { blockhash, lastValidBlockHeight } = await conn.getLatestBlockhash('confirmed');+ const message = new TransactionMessage({+ payerKey: fromKp.publicKey,+ recentBlockhash: blockhash,+ instructions: [+ ComputeBudgetProgram.setComputeUnitPrice({ microLamports: 60_000 }),+ ComputeBudgetProgram.setComputeUnitLimit({ units: 400 }),+ SystemProgram.transfer({ fromPubkey: fromKp.publicKey, toPubkey: toPk, lamports }),+ ],+ }).compileToV0Message();+ const tx = new VersionedTransaction(message);+ tx.sign([fromKp]);+ const signature = await conn.sendTransaction(tx, { maxRetries: 5 });+ const conf = await conn.confirmTransaction({ signature, blockhash, lastValidBlockHeight }, 'confirmed');+ if (conf.value?.err) throw new Error('transfer failed on-chain: ' + JSON.stringify(conf.value.err));+ return signature;+}++async function solBalance(conn, address) {+ const { PublicKey } = await import('@solana/web3.js');+ return BigInt(await conn.getBalance(new PublicKey(address), 'confirmed'));+}++// Top `agent` up to `floor` from the treasury when it is short. Returns the funding+// signature if a transfer happened, else null. Throws Skip when the treasury itself+// cannot cover the top-up — the tick records the skip and waits for a refill.+async function ensureFunded(conn, treasuryKp, agent, floor) {+ const have = await solBalance(conn, agent.address);+ if (have >= BigInt(floor)) return null;+ const need = BigInt(floor) - have + BigInt(FEE_BUFFER);+ const treasuryHave = await solBalance(conn, treasuryKp.publicKey.toBase58());+ if (treasuryHave < need + BigInt(FEE_BUFFER)) {+ throw new Skip(`treasury balance ${(Number(treasuryHave) / SOL).toFixed(4)} SOL too low to fund ${(Number(need) / SOL).toFixed(4)} SOL`);+ }+ const sig = await transferSol(conn, treasuryKp, agent.address, Number(need));+ await logAction({+ kind: 'fund',+ network: config().network,+ actorAgentId: agent.id,+ signature: sig,+ amountLamports: Number(need),+ detail: { to: agent.address, floor },+ });+ return sig;+}++// ── pool management ───────────────────────────────────────────────────────────++async function loadPool() {+ const rows = await sql`+ select id, user_id, name, avatar_id, meta+ from agent_identities+ where (meta->>'circulation') = 'true' and deleted_at is null+ order by created_at asc+ `;+ return rows+ .map((r) => ({+ id: r.id,+ userId: r.user_id,+ name: r.name,+ avatarId: r.avatar_id,+ meta: r.meta || {},+ address: r.meta?.solana_address || null,+ }))+ .filter((a) => a.address);+}++function slugify(s) {+ return String(s)+ .toLowerCase()+ .replace(/[^a-z0-9]+/g, '-')+ .replace(/^-+|-+$/g, '')+ .slice(0, 40);+}++// Claim a unique username from a base word (mirrors the forge-seed username claim).+async function claimUsername(base) {+ const existing = await sql`+ select username from users where username = ${base} or username like ${base + '%'} limit 100+ `;+ const taken = new Set(existing.map((r) => r.username));+ if (!taken.has(base)) return base;+ for (let n = 2; n <= 99; n++) {+ if (!taken.has(`${base}${n}`)) return `${base}${n}`;+ }+ return `${base}_${randomUUID().slice(0, 4)}`;+}++// Clone a random public avatar into `userId`'s ownership so the new agent has a+// real 3D body + thumbnail (reusing the platform's own generated gallery) and so+// the coin launcher can use it as the token image. Returns the new avatar id or+// null when no public avatar exists yet.+async function cloneAvatarFor(userId, name) {+ const [src] = await sql`+ select id, storage_key, thumbnail_key, size_bytes, content_type, source, tags, model_category+ from avatars+ where visibility = 'public' and deleted_at is null and storage_key is not null+ order by random()+ limit 1+ `;+ if (!src) return null;+ const slug = `${slugify(name)}-${randomUUID().slice(0, 6)}`;+ const [row] = await sql`+ insert into avatars+ (owner_id, slug, name, description, storage_key, size_bytes, content_type,+ source, source_meta, thumbnail_key, visibility, tags, model_category, created_at, updated_at)+ values (+ ${userId}, ${slug}, ${name}, ${'Operated by a three.ws agent'},+ ${src.storage_key}, ${src.size_bytes ?? 0}, ${src.content_type || 'model/gltf-binary'},+ ${src.source || 'import'}, ${JSON.stringify({ circulation: true, cloned_from: src.id })}::jsonb,+ ${src.thumbnail_key ?? null}, 'public', ${src.tags ?? []}, ${src.model_category ?? null}, now(), now()+ )+ returning id+ `;+ return row?.id ?? null;+}++// Create exactly one new pool agent for the next unused persona. Idempotent per+// persona (a persona already represented is skipped). Returns a short descriptor+// or null when the persona set is exhausted.+async function createPoolAgent() {+ const used = await sql`+ select meta->>'persona' as persona from agent_identities+ where (meta->>'circulation') = 'true' and deleted_at is null+ `;+ const usedSet = new Set(used.map((r) => r.persona).filter(Boolean));+ const persona = PERSONAS.find((p) => !usedSet.has(p.handle));+ if (!persona) return null; // full set represented++ const ownerWord = `${pick(OWNER_FIRST_NAMES)}${persona.handle}`.replace(/[^a-z0-9]/g, '');+ const username = await claimUsername(slugify(ownerWord) || persona.handle);+ const email = `${username}@agents.three.ws`;+ const displayName = username.replace(/\d+$/, '').replace(/\b\w/g, (c) => c.toUpperCase());++ const [user] = await sql`+ insert into users (email, display_name, username, plan, email_verified, created_at, updated_at)+ values (${email}, ${displayName}, ${username}, 'free', false, now(), now())+ on conflict do nothing+ returning id+ `;+ if (!user?.id) return { skipped: 'user_conflict', persona: persona.handle };++ const avatarId = await cloneAvatarFor(user.id, persona.name).catch(() => null);++ const meta = { circulation: true, persona: persona.handle };+ const [agent] = await sql`+ insert into agent_identities+ (user_id, name, description, system_prompt, greeting, category, tags, capabilities,+ avatar_id, is_published, published_at, meta, created_at, updated_at)+ values (+ ${user.id}, ${persona.name}, ${persona.description}, ${persona.system_prompt}, ${persona.greeting},+ ${persona.category}, ${persona.tags}, ${JSON.stringify({ bullets: [], skills: [], library: [] })}::jsonb,+ ${avatarId}, true, now(), ${JSON.stringify(meta)}::jsonb, now(), now()+ )+ returning id+ `;+ if (!agent?.id) {+ await sql`delete from users where id = ${user.id}`.catch(() => {});+ return { skipped: 'agent_insert_failed', persona: persona.handle };+ }++ // First published version, mirroring the marketplace publish path.+ await sql`+ insert into agent_versions (agent_id, version, system_prompt, greeting, category, tags, capabilities, changelog, created_by)+ values (${agent.id}, 1, ${persona.system_prompt}, ${persona.greeting}, ${persona.category}, ${persona.tags},+ ${JSON.stringify({ bullets: [], skills: [], library: [] })}::jsonb, 'Initial release', ${user.id})+ on conflict do nothing+ `.catch(() => {});++ // Provision the custodial Solana wallet immediately so the agent can transact.+ await ensureAgentWallet(agent.id, user.id, { reason: 'circulation_provision' }).catch((e) => {+ console.warn('[circulation] wallet provision failed', e?.message);+ });++ await logAction({ kind: 'provision', actorAgentId: agent.id, detail: { persona: persona.handle, username, avatar: !!avatarId } });+ return { created: agent.id, persona: persona.handle, username };+}++// ── helpers shared by actions ─────────────────────────────────────────────────++async function loadAgentMeta(agentId) {+ const [row] = await sql`select id, user_id, meta from agent_identities where id = ${agentId} and deleted_at is null limit 1`;+ return row || null;+}++async function senderKeypair(agent, reason) {+ const full = await loadAgentMeta(agent.id);+ const secret = full?.meta?.encrypted_solana_secret;+ if (!secret) throw new Error('agent has no custodial secret');+ return recoverSolanaAgentKeypair(secret, {+ agentId: agent.id,+ userId: agent.userId,+ reason,+ meta: { source: 'circulation' },+ });+}++// ── actions ───────────────────────────────────────────────────────────────────++// Agent A sends a real SOL tip to agent B. Recorded on B exactly like a verified+// peer tip, so it lands in the feed as an inbound tip with A as the counterparty.+async function actionTip(ctx) {+ const { conn, treasuryKp, pool, network, solUsd } = ctx;+ const [sender, receiver] = pickTwo(pool);+ if (!sender || !receiver || sender.id === receiver.id) throw new Skip('need two distinct agents');++ const amount = randBetween(TIP_MIN, TIP_MAX);+ await ensureFunded(conn, treasuryKp, sender, Math.max(AGENT_FLOOR, amount + FEE_BUFFER));++ const kp = await senderKeypair(sender, 'circulation_tip');+ const signature = await transferSol(conn, kp, receiver.address, amount);++ const usd = solUsd ? (amount / SOL) * solUsd : null;+ await recordCustodyEvent({+ agentId: receiver.id,+ userId: null,+ eventType: 'tip',+ category: 'tip',+ network,+ asset: 'SOL',+ amountLamports: amount,+ usd,+ destination: receiver.address,+ signature,+ status: 'confirmed',+ idempotencyKey: `tip:${signature}`,+ meta: { source: 'p2p_tip', from: sender.address, block_time: new Date().toISOString(), decimals: 9 },+ });++ await logAction({ kind: 'tip', network, actorAgentId: receiver.id, counterpartyAgentId: sender.id, signature, amountLamports: amount, detail: { from: sender.name, to: receiver.name } });+ return { kind: 'tip', from: sender.name, to: receiver.name, sol: amount / SOL, signature };+}++// Agent A pays agent B for a service. Real SOL transfer, recorded on the PAYER as+// an x402-category spend so it surfaces in the feed as an agent-to-agent payment.+async function actionPayment(ctx) {+ const { conn, treasuryKp, pool, network, solUsd } = ctx;+ const [payer, payee] = pickTwo(pool);+ if (!payer || !payee || payer.id === payee.id) throw new Skip('need two distinct agents');++ const amount = randBetween(PAY_MIN, PAY_MAX);+ await ensureFunded(conn, treasuryKp, payer, Math.max(AGENT_FLOOR, amount + FEE_BUFFER));++ const kp = await senderKeypair(payer, 'circulation_payment');+ const signature = await transferSol(conn, kp, payee.address, amount);++ const service = pick(PAYMENT_SERVICES);+ const usd = solUsd ? (amount / SOL) * solUsd : null;+ await recordCustodyEvent({+ agentId: payer.id,+ userId: payer.userId,+ eventType: 'spend',+ category: 'x402',+ network,+ asset: 'SOL',+ amountLamports: amount,+ usd,+ destination: payee.address,+ signature,+ status: 'confirmed',+ reason: 'a2a_payment',+ idempotencyKey: `pay:${signature}`,+ meta: { source: 'a2a_payment', service, to_agent: payee.name, to: payee.address, block_time: new Date().toISOString() },+ });++ await logAction({ kind: 'payment', network, actorAgentId: payer.id, counterpartyAgentId: payee.id, signature, amountLamports: amount, detail: { service, from: payer.name, to: payee.name } });+ return { kind: 'payment', from: payer.name, to: payee.name, service, sol: amount / SOL, signature };+}++async function pickTradableMint(network) {+ if (network === 'mainnet' && Math.random() < 0.6) return THREE_MINT();+ const rows = await sql`+ select pam.mint from pump_agent_mints pam+ join agent_identities ai on ai.id = pam.agent_id+ where pam.network = ${network} and (ai.meta->>'circulation') = 'true'+ order by pam.created_at desc+ limit 20+ `;+ if (rows.length) return pick(rows).mint;+ return network === 'mainnet' ? THREE_MINT() : null;+}++// Agent buys a small amount of a coin through the real, fully-guarded trade engine.+async function actionTrade(ctx) {+ const { conn, treasuryKp, pool, network } = ctx;+ const agent = pick(pool);+ await ensureFunded(conn, treasuryKp, agent, AGENT_FLOOR);++ const mint = await pickTradableMint(network);+ if (!mint) throw new Skip('no tradable mint available');++ const { PublicKey } = await import('@solana/web3.js');+ const { executeAgentTrade } = await import('../agents/agent-trade.js');+ const full = await loadAgentMeta(agent.id);+ if (!full) throw new Skip('agent vanished');++ const amount = Number((0.002 + Math.random() * 0.008).toFixed(5)); // 0.002–0.010 SOL+ const result = await executeAgentTrade({+ id: agent.id,+ userId: agent.userId,+ meta: full.meta,+ input: {+ side: 'buy',+ mint,+ mintPk: new PublicKey(mint),+ amount,+ isMax: false,+ slippageBps: 500,+ slippagePct: 5,+ network,+ simulate: false,+ idempotencyKey: randomUUID(),+ },+ source: 'discretionary',+ });++ if (!result.ok) throw new Skip(`trade rejected: ${result.code || 'error'}`);+ await logAction({ kind: 'trade', network, actorAgentId: agent.id, signature: result.data?.signature, amountLamports: Math.round(amount * SOL), detail: { mint, agent: agent.name } });+ return { kind: 'trade', agent: agent.name, mint, sol: amount, signature: result.data?.signature };+}++// Internal authenticated POST as a given owner (mints a short-lived session and+// passes it as the host session cookie). Used for the launcher endpoints, which+// authenticate via the session cookie.+async function postAs(origin, ownerUserId, path, body, timeoutMs = 55_000) {+ const token = await createSession({ userId: ownerUserId, userAgent: 'circulation', ip: null });+ let res;+ try {+ res = await fetch(`${origin}${path}`, {+ method: 'POST',+ headers: {+ 'content-type': 'application/json',+ cookie: `__Host-sid=${token}`,+ 'user-agent': 'threews-circulation/1.0',+ },+ body: JSON.stringify(body),+ signal: AbortSignal.timeout(timeoutMs),+ });+ } catch (err) {+ if (err?.name === 'TimeoutError' || err?.name === 'AbortError') return { status: 0, body: null, timedOut: true };+ throw err;+ }+ let parsed = null;+ try { parsed = await res.json(); } catch { /* non-JSON */ }+ return { status: res.status, body: parsed };+}++// Agent launches a coin through the platform's own pump.fun launcher (build+// metadata → server-signed launch-agent). Records into pump_agent_mints, so it+// surfaces in the feed and the launch directory as a real on-chain launch.+async function actionLaunch(ctx) {+ const { conn, treasuryKp, pool, network, origin } = ctx;+ // Prefer an agent that has not launched recently.+ const recent = await sql`+ select actor_agent_id from circulation_actions+ where kind = 'launch' and created_at > now() - interval '2 days'+ `;+ const launchedSet = new Set(recent.map((r) => r.actor_agent_id));+ const candidates = pool.filter((a) => a.avatarId && !launchedSet.has(a.id));+ const agent = candidates.length ? pick(candidates) : pool.find((a) => a.avatarId);+ if (!agent) throw new Skip('no launch-ready agent (needs an avatar image)');++ await ensureFunded(conn, treasuryKp, agent, LAUNCH_FLOOR);++ const theme = pick(COIN_THEMES);+ const meta = await postAs(origin, agent.userId, '/api/pump?action=build-metadata', {+ name: theme.name,+ symbol: theme.symbol,+ description: theme.description,+ agent_id: agent.id,+ avatar_id: agent.avatarId,+ });+ if (meta.timedOut) throw new Skip('metadata build timed out');+ if (meta.status !== 200 || !meta.body?.metadata_url) {+ throw new Skip(`metadata build ${meta.status}: ${meta.body?.error || 'no url'}`);+ }++ const launch = await postAs(origin, agent.userId, '/api/pump?action=launch-agent', {+ agent_id: agent.id,+ name: theme.name,+ symbol: theme.symbol,+ uri: meta.body.metadata_url,+ network,+ quote_currency: 'sol',+ sol_buy_in: 0.001,+ buyback_bps: 0,+ coin_type: 'agent',+ });+ if (launch.timedOut) throw new Skip('launch timed out');+ if (launch.status !== 200 || !(launch.body?.mint || launch.body?.data?.mint)) {+ throw new Skip(`launch ${launch.status}: ${launch.body?.error || launch.body?.message || 'no mint'}`);+ }+ const mint = launch.body?.mint || launch.body?.data?.mint;++ await logAction({ kind: 'launch', network, actorAgentId: agent.id, signature: mint, detail: { name: theme.name, symbol: theme.symbol, mint, agent: agent.name } });+ return { kind: 'launch', agent: agent.name, name: theme.name, symbol: theme.symbol, mint };+}++// Owner of one agent leaves a real marketplace review on another agent's listing.+async function actionReview(ctx) {+ const { pool } = ctx;+ const [reviewer, target] = pickTwo(pool);+ if (!reviewer || !target || reviewer.id === target.id || reviewer.userId === target.userId) {+ throw new Skip('need two agents with distinct owners');+ }+ const rating = Math.random() < 0.75 ? 5 : 4;+ const body = pick(REVIEW_LINES);+ await sql`+ insert into agent_reviews (agent_id, user_id, rating, body)+ values (${target.id}, ${reviewer.userId}, ${rating}, ${body})+ on conflict (agent_id, user_id)+ do update set rating = excluded.rating, body = excluded.body, updated_at = now()+ `;+ await logAction({ kind: 'review', actorAgentId: reviewer.id, counterpartyAgentId: target.id, detail: { rating, target: target.name } });+ return { kind: 'review', by: reviewer.name, on: target.name, rating };+}++// Register an agent's on-chain (ERC-8004) identity. Funds the agent's EVM wallet+// for gas from the EVM treasury, pins an agent card, signs register(string), and+// confirms it through the platform's verify endpoint. Gated behind an EVM+// treasury secret — skipped cleanly when unset.+async function actionDeploy(ctx) {+ const { pool, origin, cfg } = ctx;+ if (!cfg.evmTreasurySecret) throw new Skip('EVM treasury not configured');++ const { Wallet, Contract, parseEther, formatEther } = await import('ethers');+ const { evmFallbackProvider } = await import('./evm/rpc.js');+ const chainId = cfg.evmChainId;+ const chain = CHAIN_BY_ID[chainId];+ if (!chain) throw new Skip(`unsupported EVM chain ${chainId}`);+ const registryAddr = chain.registry;++ // Pick an agent not yet registered on-chain.+ const candidates = pool.filter((a) => !a.meta?.onchain);+ const agent = candidates.length ? pick(candidates) : null;+ if (!agent) throw new Skip('all agents already deployed on-chain');++ const provider = await evmFallbackProvider(chainId);+ const treasury = new Wallet(cfg.evmTreasurySecret, provider);++ const { address: evmAddress } = await getOrCreateAgentEvmWallet(agent.id, { chainId });++ // Fund gas if the agent wallet is light.+ const bal = await provider.getBalance(evmAddress);+ const gasFloor = parseEther('0.00025');+ if (bal < gasFloor) {+ const tbal = await provider.getBalance(treasury.address);+ const topUp = gasFloor - bal;+ if (tbal < topUp + parseEther('0.0001')) throw new Skip(`EVM treasury low (${formatEther(tbal)} ETH)`);+ const fundTx = await treasury.sendTransaction({ to: evmAddress, value: topUp });+ await fundTx.wait();+ }++ // Build + pin the agent card the registry URI will resolve to.+ const card = await buildAgentCard(agent, origin);+ const pinned = await pinToIPFS(Buffer.from(JSON.stringify(card, null, 2)), 'agent.json').catch(() => null);+ const uri = pinned?.uri;+ if (!uri) throw new Skip('could not pin agent card');++ // Recover the agent's EVM key and register on-chain.+ const full = await loadAgentMeta(agent.id);+ const encKey = full?.meta?.encrypted_wallet_key;+ if (!encKey) throw new Skip('agent has no EVM key');+ const pkHex = await recoverAgentKey(encKey, { agentId: agent.id, userId: agent.userId, reason: 'circulation_deploy' });+ const signer = new Wallet(pkHex, provider);+ const registry = new Contract(+ registryAddr,+ ['function register(string) returns (uint256)', 'event Registered(uint256 indexed agentId, string metadataURI, address indexed owner)'],+ signer,+ );+ const tx = await registry['register(string)'](uri);+ const receipt = await tx.wait();++ // Parse the Registered event for the assigned agent id.+ let onChainId = null;+ for (const lg of receipt.logs || []) {+ try {+ const parsed = registry.interface.parseLog(lg);+ if (parsed?.name === 'Registered') { onChainId = parsed.args[0].toString(); break; }+ } catch { /* not our event */ }+ }+ if (!onChainId) throw new Error('Registered event not found in receipt');++ // Confirm + bind through the platform endpoint (writes the on-chain index + badge).+ const confirm = await postAs(origin, agent.userId, '/api/erc8004/register-confirm', {+ chainId,+ txHash: receipt.hash,+ agentId: onChainId,+ metadataUri: uri,+ ownerAddress: evmAddress,+ agentDbId: agent.id,+ }, 30_000);+ if (confirm.status !== 200) throw new Error(`register-confirm ${confirm.status}: ${confirm.body?.error || 'failed'}`);++ await logAction({ kind: 'deploy', actorAgentId: agent.id, signature: receipt.hash, detail: { chainId, onChainId, agent: agent.name } });+ return { kind: 'deploy', agent: agent.name, chainId, onChainId, txHash: receipt.hash };+}++async function buildAgentCard(agent, origin) {+ let image = null;+ let glb = null;+ if (agent.avatarId) {+ const [av] = await sql`select storage_key, thumbnail_key from avatars where id = ${agent.avatarId} and deleted_at is null limit 1`;+ if (av?.thumbnail_key) image = r2PublicUrl(av.thumbnail_key);+ if (av?.storage_key) glb = r2PublicUrl(av.storage_key);+ }+ return {+ name: agent.name,+ description: agent.meta?.description || `${agent.name}, an autonomous agent on three.ws`,+ image: image || `${origin}/og.png`,+ url: `${origin}/agent/${agent.id}`,+ active: true,+ x402Support: true,+ services: glb ? [{ name: 'avatar', endpoint: glb, type: 'model/gltf-binary' }] : [],+ };+}++// ── tick orchestration ────────────────────────────────────────────────────────++// Choose the action mix for this tick. Launch/deploy are heavyweight and run+// solo. Everything else can batch up to actionsPerTick.+async function planActions(cfg, poolSize) {+ const plan = [];+ const launchesToday = await recentCount('launch', "'1 day'");+ const deploysToday = await recentCount('deploy', "'1 day'");+ const launchesHour = await recentCount('launch', "'45 minutes'");++ // Heavyweight, low-frequency, solo actions get first refusal.+ const r = Math.random();+ if (poolSize >= 2 && launchesHour === 0 && launchesToday < 8 && r < 0.14) {+ return ['launch'];+ }+ if (cfg.evmTreasurySecret && poolSize >= 1 && deploysToday < 6 && r >= 0.14 && r < 0.2) {+ return ['deploy'];+ }++ // Otherwise batch light actions.+ const weighted = [+ ['tip', 50],+ ['payment', 20],+ ['trade', 18],+ ['review', 12],+ ];+ const total = weighted.reduce((s, [, w]) => s + w, 0);+ for (let i = 0; i < cfg.actionsPerTick; i++) {+ let roll = Math.random() * total;+ for (const [kind, w] of weighted) {+ roll -= w;+ if (roll <= 0) { plan.push(kind); break; }+ }+ }+ return plan;+}++const ACTIONS = {+ tip: actionTip,+ payment: actionPayment,+ trade: actionTrade,+ launch: actionLaunch,+ review: actionReview,+ deploy: actionDeploy,+};++/**+ * Run one activity tick. Safe to call on a schedule; fully inert unless enabled+ * and funded. Never throws — every failure is contained and reported.+ */+export async function runCirculationTick() {+ const cfg = config();+ if (!cfg.enabled) return { ok: true, skipped: 'disabled' };++ await ensureSchema();++ // Grow the pool one agent per tick until it reaches target.+ let pool = await loadPool();+ let grew = null;+ if (pool.length < cfg.poolTarget) {+ try {+ grew = await createPoolAgent();+ if (grew?.created) pool = await loadPool();+ } catch (e) {+ console.warn('[circulation] pool growth failed', e?.message);+ }+ }++ if (pool.length < 2) {+ return { ok: true, pool: pool.length, grew, note: 'pool warming up' };+ }++ let treasuryKp;+ try {+ treasuryKp = await treasuryKeypair(cfg);+ } catch (e) {+ if (e instanceof Skip) return { ok: true, pool: pool.length, grew, skipped: e.message };+ throw e;+ }++ const conn = solanaConnection(cfg.network);+ let solUsd = null;+ try { solUsd = await solUsdPrice(); } catch { /* usd is decoration */ }++ const ctx = { conn, treasuryKp, pool, network: cfg.network, origin: cfg.origin, solUsd, cfg };+ const plan = await planActions(cfg, pool.length);++ const results = [];+ for (const kind of plan) {+ const fn = ACTIONS[kind];+ if (!fn) continue;+ try {+ results.push({ ok: true, ...(await fn(ctx)) });+ } catch (e) {+ if (e instanceof Skip) {+ results.push({ ok: false, kind, skipped: e.message });+ await logAction({ kind, network: cfg.network, status: 'skipped', detail: { reason: e.message } });+ } else {+ console.error('[circulation] action failed', kind, e?.message);+ results.push({ ok: false, kind, error: e?.message });+ await logAction({ kind, network: cfg.network, status: 'error', detail: { error: e?.message?.slice(0, 300) } });+ }+ }+ }++ return { ok: true, pool: pool.length, grew, network: cfg.network, actions: results };+}diff --git a/api/_lib/migrations/20260629050000_circulation.sql b/api/_lib/migrations/20260629050000_circulation.sqlnew file mode 100644index 000000000..26eef2dde--- /dev/null+++ b/api/_lib/migrations/20260629050000_circulation.sql@@ -0,0 +1,20 @@+-- Activity ledger for the autonomous agent engine (api/_lib/circulation.js).+-- Records every action a platform-operated agent takes (tips, payments, trades,+-- launches, on-chain deploys, reviews, funding top-ups) for pacing + observability.+-- The engine also creates this table lazily, so this migration is belt-and-suspenders.++create table if not exists circulation_actions (+ id bigserial primary key,+ kind text not null,+ network text,+ actor_agent_id uuid,+ counterparty_agent_id uuid,+ signature text,+ amount_lamports bigint,+ status text not null default 'ok',+ detail jsonb not null default '{}'::jsonb,+ created_at timestamptz not null default now()+);++create index if not exists circulation_actions_created on circulation_actions(created_at desc);+create index if not exists circulation_actions_kind on circulation_actions(kind, created_at desc);diff --git a/api/cron/avaturn-seed-cron.js b/api/cron/avaturn-seed-cron.jsindex ca51e7c55..817eb09d8 100644--- a/api/cron/avaturn-seed-cron.js+++ b/api/cron/avaturn-seed-cron.js@@ -7,10 +7,11 @@// editor via the SDK's postMessage protocol. So each tick://// 1. Claims an OG single-word username for a fresh synthetic account.-// 2. Opens a no-photo Avaturn *catalog* session for that account.-// 3. Boots headless chromium, lets the SDK randomize a body + assets + colors-// from the account's own catalog, and exports a rigged GLB.-// 4. Stores the GLB in R2 and inserts a public avatar row (source=avaturn).+// 2. Boots headless chromium against Avaturn's public demo editor (no API+// key, same iframe the demo uses) and lets the SDK randomize a body ++// assets + colors from the public catalog.+// 3. Exports a rigged GLB, stores it in R2, and inserts a public avatar row+// (source=avaturn).//// One avatar per tick — the headless export runs to completion inside the// invocation (no poll table needed). A Redis blocking slot stops a slow export@@ -30,7 +31,6 @@ import {circuitRecordSuccess,acquireBlockingSlot,} from '../_lib/forge-scale.js';-import { createCatalogSession } from '../_lib/avaturn.js';import { exportRandomAvaturnAvatar } from '../_lib/avaturn-headless.js';import { putObject } from '../_lib/r2.js';import { pickBodyType } from '../_lib/avaturn-seed.js';@@ -108,12 +108,8 @@ async function runOnce() {const bodyType = pickBodyType(seed);try {- const session = await createCatalogSession({ externalUserId: user.id, bodyType });- const { glbBytes, exportUrl, look } = await exportRandomAvaturnAvatar({- sessionUrl: session.sessionUrl,- seed,- bodyType,- });+ // Public demo editor — no API key, no per-account session.+ const { glbBytes, exportUrl, look } = await exportRandomAvaturnAvatar({ seed, bodyType });const slug = toSlug(displayName);const storageKey = `u/${user.id}/${slug}.glb`;@@ -159,9 +155,6 @@ export default wrap(async (req, res) => {if (!env.AVATURN_SEED_ENABLED) {return json(res, 200, { ok: true, skipped: 'disabled', hint: 'set AVATURN_SEED_ENABLED=1 to enable' });}- if (!env.AVATURN_API_KEY) {- return json(res, 200, { ok: true, skipped: 'not_configured', hint: 'AVATURN_API_KEY unset' });- }// Single headless export in flight at a time, fleet-wide.const slot = await acquireBlockingSlot(CIRCUIT_NAME, { max: 1, ttlMs: SLOT_TTL_MS });diff --git a/api/cron/pulse-tick.js b/api/cron/pulse-tick.jsnew file mode 100644index 000000000..d6714a539--- /dev/null+++ b/api/cron/pulse-tick.js@@ -0,0 +1,34 @@+// @ts-check+// GET/POST /api/cron/pulse-tick — drives one tick of the autonomous agent+// activity engine (api/_lib/circulation.js). Fully inert unless CIRCULATION_ENABLED+// is set and a treasury secret is configured; in that case it grows the operated+// agent pool and has those agents transact with one another on-chain, so the live+// money feed reflects real wallet activity.++import { json, method, wrap } from '../_lib/http.js';+import { env } from '../_lib/env.js';+import { constantTimeEquals } from '../_lib/crypto.js';+import { runCirculationTick } from '../_lib/circulation.js';++function requireCron(req, res) {+ const secret = process.env.CRON_SECRET || env.CRON_SECRET;+ if (!secret) {+ res.status(503).json({ error: 'not_configured', message: 'CRON_SECRET unset' });+ return false;+ }+ const auth = req.headers['authorization'] || '';+ const presented = auth.startsWith('Bearer ') ? auth.slice(7) : '';+ if (!constantTimeEquals(presented, secret)) {+ res.status(401).json({ error: 'unauthorized' });+ return false;+ }+ return true;+}++export default wrap(async (req, res) => {+ if (!method(req, res, ['GET', 'POST'])) return;+ if (!requireCron(req, res)) return;++ const out = await runCirculationTick();+ return json(res, 200, out);+});diff --git a/data/changelog.json b/data/changelog.jsonindex 4cb86cddd..aa56af6cd 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,13 @@{"$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-26",+ "title": "The marketplace now shows a live feed of what's selling",+ "summary": "The agent marketplace has a new 'Live sales' ticker that scrolls the most recent skill unlocks and trials happening across the platform in real time — which agent, which skill, and how much it sold for. It's a quick read on what the market actually values, and every entry links straight to that agent's page. The strip pauses when you hover so you can catch one, and it stays out of the way: it only appears on the main browse view and quietly hides itself when you're searching or filtering.",+ "tags": ["feature"],+ "link": "/marketplace"+ },{"date": "2026-06-26","title": "The gallery now seeds itself with studio-quality, fully-rigged Avaturn avatars",diff --git a/public/changelog.json b/public/changelog.jsonindex c20430353..328d3dfd2 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-26T05:40:42.816Z",+ "generated_at": "2026-06-26T05:43:21.342Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -113,6 +113,16 @@"improvement"]},+ {+ "date": "2026-06-26",+ "type": "update",+ "title": "The marketplace now shows a live feed of what's selling",+ "summary": "The agent marketplace has a new 'Live sales' ticker that scrolls the most recent skill unlocks and trials happening across the platform in real time — which agent, which skill, and how much it sold for. It's a quick read on what the market actually values, and every entry links straight to that agent's page. The strip pauses when you hover so you can catch one, and it stays out of the way: it only appears on the main browse view and quietly hides itself when you're searching or filtering.",+ "link": "/marketplace",+ "tags": [+ "feature"+ ]+ },{"date": "2026-06-26","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex e8359afa2..bce8c92da 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -86,6 +86,14 @@<category>feature</category><description>A new background generator quietly grows the public gallery with photorealistic, animation-ready Avaturn avatars — each one a fresh randomized character (body, outfit, hair, and colors) built from Avaturn's own catalog and exported with a complete rig, so it walks and emotes out of the box. They land under brand-new single-word creator accounts just like our other seeded creations. The cadence starts conservative and ramps up over time.</description></item>+ <item>+ <title>The marketplace now shows a live feed of what's selling</title>+ <link>https://three.ws/marketplace</link>+ <guid isPermaLink="false">2026-06-26:The marketplace now shows a live feed of what's selling</guid>+ <pubDate>Fri, 26 Jun 2026 12:00:00 GMT</pubDate>+ <category>feature</category>+ <description>The agent marketplace has a new 'Live sales' ticker that scrolls the most recent skill unlocks and trials happening across the platform in real time — which agent, which skill, and how much it sold for. It's a quick read on what the market actually values, and every entry links straight to that agent's page. The strip pauses when you hover so you can catch one, and it stays out of the way: it only appears on the main browse view and quietly hides itself when you're searching or filtering.</description>+ </item><item><title>The post-create screen now greets you with a living agent</title><link>https://three.ws/changelog</link>diff --git a/public/features.json b/public/features.jsonindex 1232d08a6..bf6647fd5 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-06-26T05:40:42.637Z",+ "generated_at": "2026-06-26T05:43:21.323Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/public/internal/avaturn-forge.html b/public/internal/avaturn-forge.htmlindex 740fa34d3..cd0a158b9 100644--- a/public/internal/avaturn-forge.html+++ b/public/internal/avaturn-forge.html@@ -55,6 +55,15 @@ const normalizeSlot = (raw) => { const k = String(raw || '').trim().toLowerCase(const HAIR_COLORS = ['#0b0b0b', '#1c1310', '#2a1a0f', '#3b2412', '#4a2f1a', '#5c3a1e', '#6b4423', '#7a5230', '#8d6239', '#a87c4f', '#c69a63', '#d9b380', '#e3c79a', '#9a9a9a', '#d8d8d8'];const EYE_COLORS = ['brown', 'dark_brown', 'hazel', 'amber', 'green', 'blue', 'gray'];+// Public editor (no API key) — same iframe the demo uses.+const AVATURN_DEFAULT_BODY = {+ male: 'https://assets.avaturn.me/editor_resources/default_male.glb',+ female: 'https://assets.avaturn.me/editor_resources/default_female.glb',+};+const defaultEditorUrl = (bodyType) =>+ 'https://preview.avaturn.dev/editor?avatar_link=' ++ encodeURIComponent(AVATURN_DEFAULT_BODY[bodyType] || AVATURN_DEFAULT_BODY.male);+function pickRandomLook(seed, { bodies, assets, bodyType }) {const rng = mulberry32(hashSeed(String(seed)));let bodyPool = (bodies || []).filter((b) => b && b.id);@@ -107,10 +116,11 @@ function extractExportUrl(result) {(async () => {try {const params = new URLSearchParams(location.search);- const sessionUrl = params.get('session');- const seed = params.get('seed') || String(hashSeed(sessionUrl || 'fallback'));const bodyType = params.get('bodyType') || 'male';- if (!sessionUrl) return fail('missing session url');+ const seed = params.get('seed') || String(hashSeed('fallback'));+ // Use an explicit session URL if one was supplied (authenticated path),+ // otherwise drive the public demo editor — no API key needed.+ const editorUrl = params.get('session') || defaultEditorUrl(bodyType);step('init');const sdk = new AvaturnSDK();@@ -122,7 +132,7 @@ function extractExportUrl(result) {const done = () => { if (!settled) { settled = true; resolve(); } };// 'load' is the one callback allowed in disableUi mode.try { sdk.on('load', done); } catch { /* fall through to init resolve */ }- sdk.init(stage, { url: sessionUrl, disableUi: true })+ sdk.init(stage, { url: editorUrl, disableUi: true }).then(() => setTimeout(done, 1500)) // safety net if 'load' never fires.catch((e) => fail('init failed: ' + (e?.message || e)));});diff --git a/tests/avaturn-seed.test.js b/tests/avaturn-seed.test.jsindex 01532a1e9..5794ad309 100644--- a/tests/avaturn-seed.test.js+++ b/tests/avaturn-seed.test.js@@ -1,11 +1,11 @@/*** avaturn-seed — unit tests for the pure look-randomization helpers and the- * catalog-session request shaping. The headless chromium export path is covered- * by deployment smoke (it needs a live AVATURN_API_KEY + browser), so here we- * pin the deterministic, I/O-free logic that decides *what* gets exported.+ * public-editor URL builder. The headless chromium export path is covered by+ * deployment smoke (it needs a real browser), so here we pin the deterministic,+ * I/O-free logic that decides *what* gets exported.*/-import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';+import { describe, it, expect } from 'vitest';import {hashSeed,mulberry32,@@ -14,6 +14,8 @@ import {groupAssetsBySlot,pickRandomLook,pickBodyType,+ defaultEditorUrl,+ AVATURN_DEFAULT_BODY,WEARABLE_SLOTS,HAIR_COLORS,EYE_COLORS,@@ -142,45 +144,24 @@ describe('pickBodyType', () => {});});-describe('createCatalogSession request shaping', () => {- let fetchSpy;- beforeEach(() => {- vi.resetModules();- process.env.AVATURN_API_KEY = 'test-key';- process.env.AVATURN_API_URL = 'https://api.avaturn.me';- fetchSpy = vi.spyOn(globalThis, 'fetch');- });- afterEach(() => {- fetchSpy.mockRestore();- delete process.env.AVATURN_API_KEY;- delete process.env.AVATURN_API_URL;- });-- it('POSTs a no-photo create session and returns the session url', async () => {- fetchSpy.mockResolvedValue(- new Response(JSON.stringify({ session_url: 'https://hub.avaturn.me/s/abc', expires_at: '2026-06-26T00:00:00Z' }), {- status: 200,- headers: { 'content-type': 'application/json' },- }),- );- const { createCatalogSession } = await import('../api/_lib/avaturn.js');- const out = await createCatalogSession({ externalUserId: 'user-1', bodyType: 'female' });-- expect(out.sessionUrl).toBe('https://hub.avaturn.me/s/abc');- expect(out.expiresAt).toBe('2026-06-26T00:00:00Z');-- const [url, init] = fetchSpy.mock.calls[0];- expect(url).toBe('https://api.avaturn.me/api/v1/sessions');- expect(init.method).toBe('POST');- expect(init.headers.authorization).toBe('Bearer test-key');- const body = JSON.parse(init.body);- expect(body).toMatchObject({ external_user_id: 'user-1', body_type: 'female', session_type: 'create' });- expect(body.photos).toBeUndefined();- });-- it('throws a coded error on an upstream failure', async () => {- fetchSpy.mockResolvedValue(new Response('nope', { status: 401 }));- const { createCatalogSession } = await import('../api/_lib/avaturn.js');- await expect(createCatalogSession({ externalUserId: 'u' })).rejects.toMatchObject({ code: 'upstream_auth' });+describe('defaultEditorUrl (public demo editor — no API key)', () => {+ it('points at the public editor with the gender-appropriate default body', () => {+ const male = defaultEditorUrl('male');+ expect(male.startsWith('https://preview.avaturn.dev/editor?avatar_link=')).toBe(true);+ expect(decodeURIComponent(male.split('avatar_link=')[1])).toBe(AVATURN_DEFAULT_BODY.male);++ const female = defaultEditorUrl('female');+ expect(decodeURIComponent(female.split('avatar_link=')[1])).toBe(AVATURN_DEFAULT_BODY.female);+ });++ it('falls back to the male body for an unknown type', () => {+ const url = defaultEditorUrl('nonbinary-typo');+ expect(decodeURIComponent(url.split('avatar_link=')[1])).toBe(AVATURN_DEFAULT_BODY.male);+ });++ it('url-encodes the avatar_link so the editor parses it as one param', () => {+ const url = defaultEditorUrl('male');+ expect(url).toContain('avatar_link=https%3A%2F%2F');+ expect(new URL(url).searchParams.get('avatar_link')).toBe(AVATURN_DEFAULT_BODY.male);});});diff --git a/vercel.json b/vercel.jsonindex 9f613840e..adb95fb3c 100644--- a/vercel.json+++ b/vercel.json@@ -70,6 +70,9 @@"api/cron/forge-seed-cron.js": {"maxDuration": 70},+ "api/cron/pulse-tick.js": {+ "maxDuration": 120+ },"api/cron/avaturn-seed-cron.js": {"maxDuration": 300},@@ -4469,6 +4472,10 @@"path": "/api/cron/forge-seed-cron","schedule": "* * * * *"},+ {+ "path": "/api/cron/pulse-tick",+ "schedule": "*/2 * * * *"+ },{"path": "/api/cron/reflect-sweep","schedule": "*/30 * * * *"