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(agora-citizens): implement world-seed functionality to project rigged agents as citizens
nirholas17933c43cfac
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex 5cf511ddf..4437d52d7 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -39,7 +39,7 @@ graph TDLib["api/_lib/ — 500+ shared utilities\ndb.js · auth.js · redis.js · r2.js · x402-spec.js · memory-store.js · launcher-engine.js"]end- APILayer --> Neon["Neon Postgres\n(primary DB)\ncitext · pg_trgm · pgcrypto\n~270 tables · JSONB embeddings"]+ APILayer --> Neon["Neon Postgres\n(primary DB)\ncitext · pg_trgm · pgcrypto\n~295 tables · JSONB embeddings"]APILayer --> Redis["Upstash Redis REST\n(rate limit + cache)"]APILayer --> R2["Cloudflare R2\nGLBs · Audio · Thumbnails · Metadata"]APILayer --> MCPSvc["MCP Servers — 8 remote endpoints\n/api/mcp · /api/mcp-3d\n/api/pump-fun-mcp · /api/ibm-mcp · + 4 more"]@@ -193,9 +193,9 @@ Every top-level directory in the monorepo, what it is, and where to look. File c### Routing Architecture-three.ws is a **Multi-Page Application (MPA)** with no client-side router framework. Each page is an independent HTML/JS Vite entry point. Vite dev middleware handles URL rewrites that mirror production Vercel routes. There are two SPA-shell exceptions: `pages/dashboard-next/` (**32 sub-page modules** loaded dynamically by `src/dashboard-next/shell.js`) and the **classic dashboard** `public/dashboard/*.html` (18 pages, controller `src/dashboard/dashboard.js`, reachable at e.g. `/dashboard/x402`, `/dashboard/holders`). The standalone Avatar Studio (`/avatar-studio/*`) is a separately-built React SPA (see Character Studio).+three.ws is a **Multi-Page Application (MPA)** with no client-side router framework. Each page is an independent HTML/JS Vite entry point. Vite dev middleware handles URL rewrites that mirror production Vercel routes. There are two SPA-shell exceptions: `pages/dashboard-next/` (**35+ sub-page modules** loaded dynamically by `src/dashboard-next/shell.js`) and the **classic dashboard** `public/dashboard/*.html` (18 pages, controller `src/dashboard/dashboard.js`, reachable at e.g. `/dashboard/x402`, `/dashboard/holders`). The standalone Avatar Studio (`/avatar-studio/*`) is a separately-built React SPA (see Character Studio).-**Build:** `npm run dev` (port 3000), `npm run build` (Vite 7 MPA). HTML entry points are auto-resolved in `vite.config.js`: **~213 under `pages/` + ~150 under `public/` ≈ 290+ total** (the "150+" figure counts top-level `pages/*.html` routes only). Three.js is `^0.184.0` (r184).+**Build:** `npm run dev` (port 3000), `npm run build` (Vite 7 MPA). HTML entry points are auto-resolved in `vite.config.js`: **~235 under `pages/` + ~150 under `public/` ≈ 300+ total** (the "170+" figure counts top-level `pages/*.html` routes only). All front-end motion is standardized on the shared `src/ui-juice.js` [game-feel library](#ui-juice--shared-game-feel-library). Three.js is `^0.184.0` (r184).**Dev API proxy:** `/api/*` proxies to `DEV_API_PROXY` (default: `https://three.ws`).@@ -212,7 +212,10 @@ three.ws is a **Multi-Page Application (MPA)** with no client-side router framew| Agent Detail | `/agent/:id` (301 → canonical) | `public/agent/index.html` (`src/agent-home.js`); `pages/agent-detail.html` (`src/agent-detail.js`) | `/agent/:id` 301-redirects to the canonical profile (`public/agent/index.html`). Live wallet pulse, mirror panel, strategy panel, patronage, validation badge, WebGL avatar, on-chain status, coin launch history || Agent Wallet Hub | `/agent/:id/wallet` | `pages/agent-wallet.html` | `src/agent-wallet-hub/index.js` | **22-tab** Solana wallet (`src/agent-wallet-hub/tabs/`): Balance, Portfolio, Deposit, Trade, Snipe, Orders, Earn, Autopilot, Intents, Signals, Pay, Vanity, Policy, Withdraw, Give, Access, Recovery, Guard, Proof, **Copilot, Pulse, Reputation** || Agent Mind Palace | `/agent/:id/mind` | `pages/agent-mind.html` | `src/agent-mind.js` + `src/mind-palace.js` | Visual 3D memory graph |-| Agent Studio | `/agent/:id/studio` | `pages/agent-studio.html` | `src/studio/studio-shell.js` | Tabs: Brain, Memory, Body, Money, Skills |+| Agent Studio | `/agent/:id/studio` | `pages/agent-studio.html` | `src/studio/studio-shell.js` | Tabs: Brain, Memory, Body, **Money** (Money Studio + Trading Brain), Skills |+| Agent Screen | `/agent-screen` | `pages/agent-screen.html` | `src/agent-screen.js` | Watch your own agent work live — real browser screen feed + 3D avatar. See [Agent Screen](#agent-screen--live-agent-casting) |+| Live Agents Wall | `/agents-live` | `pages/agents-live.html` | `src/agents-live.js` | Mission-control grid of all agents with active screen streams (public) |+| Deployments | `/deployments` | `pages/deployments.html` | `src/deployments.js` | Live cross-chain feed of every agent on the ERC-8004 Identity Registry || Marketplace | `/marketplace` | `pages/marketplace.html` | `src/marketplace.js` | Agent + skill discovery: category sidebar, search, list+detail SPA || @Handle Profile | `/@:handle` | `pages/handle.html` | `src/handle.js` | Public live profile with embedded avatar iframe |@@ -222,7 +225,7 @@ three.ws is a **Multi-Page Application (MPA)** with no client-side router framew**Path:** `pages/dashboard-next/*.html` + `src/dashboard-next/shell.js`-**32 sub-page modules** loaded dynamically via `src/dashboard-next/pages/*.js` (the table below lists the primary ones; also present: **Community Avatars** `community-avatars.js`, **IRL Outfit Editor** `irl-outfit-editor.js`, **IRL Reputation** `irl-reputation.js`, plus helper modules `creator-helpers.js`, `widgets-helpers.js`):+**35+ sub-page modules** loaded dynamically via `src/dashboard-next/pages/*.js` (the table below lists the primary ones; also present: **Community Avatars** `community-avatars.js`, **IRL Outfit Editor** `irl-outfit-editor.js`, **IRL Reputation** `irl-reputation.js`, plus helper modules `creator-helpers.js`, `widgets-helpers.js`):| Sub-page | File | Description ||----------|------|-------------|@@ -236,7 +239,10 @@ three.ws is a **Multi-Page Application (MPA)** with no client-side router framew| Settings | `pages/settings.js` | Platform settings || Widgets | `pages/widgets.js` | Embeddable widget builder || Wallet Grinder | `pages/wallet-grinder.js` | Vanity address grinder UI |-| Sniper | `pages/sniper.js` | Sniper strategy config |+| Sniper | `pages/sniper.js` | Sniper strategy config + embedded Money Studio (Strategy ↔ Money sub-tabs) |+| Capabilities | `pages/capabilities.js` | Command center for the 4 autonomous capabilities: Alpha Hunt, Coin Launcher, Creator Auto-Claim, Market Maker (Jito) |+| Systems | `pages/systems.js` | Live "Systems" health panel |+| Watch | `pages/watch.js` | Watch an owned agent work from the dashboard || Holders | `pages/holders.js` | $THREE holder management || Brain | `pages/brain.js` | LLM persona builder || Walk | `pages/walk.js` | Walk SDK config |@@ -309,6 +315,8 @@ three.ws is a **Multi-Page Application (MPA)** with no client-side router framew| Pose Studio | `/pose` | `src/pose-studio.js` | Avatar pose capture, library, share, thumbnail || Voice Lab | `/voice` | `src/voice-lab.js` + `src/voice/` | Voice clone, TTS testing, lip-sync driver, LiveKit spatial voice || AR Experience | `/avatars/:id/ar` | `src/ar-page.js` + `src/ar/` | WebXR + ARKit Quick Look + Android Scene Viewer |+| Diorama | `/diorama` | `src/diorama/main.js` | Type a sentence → LLM "3D set designer" plan → per-object Forge → floating-island world (save/remix). See [Diorama & Scene Capture](#diorama--scene-capture) |+| Scene Capture | `/capture` | `src/capture.js` | Phone video → coloured 3D point cloud (`workers/model-video2scene`, LingBot-Map) rendered in-browser |---@@ -318,6 +326,8 @@ three.ws is a **Multi-Page Application (MPA)** with no client-side router framew|---------|-------|---------------|-------------|| Launches Feed | `/launches` | `src/launches.js` | `GET /api/pump/launches` (60s live refresh) || Launch Detail | `/launches/:mint` | `src/launch-detail.js` | Price, bonding curve, holder bubblemap, oracle conviction |+| Launch Studio | `/launch-studio` | `public/launch-studio/launch-studio.js` | 50 coin-launch recipes previewed live; rewards routable to anyone. See [Launch Studio](#launch-studio--the-autonomous-coin-launcher) |+| Memetic Launcher | `/launcher` | `src/admin-launcher.js` (preview) | Design a personal autonomous coin launcher over live cultural narratives (preview; no SOL moves) || $THREE Token Page | `/three-token` | `src/three-token-page.js` | Live price, bonding curve chart, Jupiter swap modal || Autopilot | `/autopilot` | `src/autopilot.js` | Per-coin buyback/distribute policy, agent avatar narration || Pump Dashboard | `/pump-dashboard` | `src/launchpad/` | Pump.fun token creator dashboard |@@ -341,6 +351,10 @@ three.ws is a **Multi-Page Application (MPA)** with no client-side router framew| CA → x402 Converter | `/ca2x402` | Paste token CA → get live payable x402 endpoint for market intel || x402 Studio | `/x402/studio` | Build and test paid endpoints || x402 Dashboard | `/dashboard/x402` | SKU management for merchants |+| Endpoint Revenue | `/x402-revenue` | Live USDC revenue into three.ws's own paid endpoints (chart, KPIs, settlement feed) |+| Payment Sessions | `/payments` | Create budget-limited, governance-enforced x402 spend sessions (no keys) |+| Agent Economy Volume | `/agent-economy-volume` | Live total A2A economy volume (real USDC settled between agents) |+| Billing & Keys | `/billing/keys` | API keys + usage/quota |---@@ -429,7 +443,7 @@ Beyond the page controllers above, `src/` holds ~60 subsystem directories. Map o## API Layer-The API layer is **1,209 JavaScript files** across `api/`, organized as Vercel serverless functions (Node.js ESM). All functions share a `api/_lib/` utility layer (413 files).+The API layer is **~1,382 JavaScript files** across `api/`, organized as Vercel serverless functions (Node.js ESM). All functions share a `api/_lib/` utility layer (~505 files).### Authentication Patterns@@ -641,7 +655,7 @@ Representative endpoints:| `reviews` | Read/write reviews || `analytics` | Skill revenue analytics |-#### Cron Jobs (`api/cron/`) — 32 handler files, 61 schedules+#### Cron Jobs (`api/cron/`) — 42 handler files, 72 schedules`api/cron/` holds **32 `.js` files** (31 named crons + a dynamic `[name].js` dispatcher), wired by **61 `crons` entries** in `vercel.json` (cron auth = `x-vercel-cron` header or `Bearer $CRON_SECRET`). Beyond the representative table below, undocumented-but-live crons include the four fanout workers (`copy-fanout`, `mirror-fanout`, `signal-fanout`, `strategy-fanout`), `run-dca`, `run-subscriptions`, `run-buyback`/`run-distribute-payments`, `treasury-autopilot`, `process-withdrawals`, `solana-attestations-crawl`, `trader-score-attest`, `custody-attest`, `auto-rig-sweep`, `dead-man-switch`, `relayer-balance-check`, `reconcile-decisions`, `smart-money-graph`, `index-delegations`, `cleanup-csrf-tokens`, `siwx-gc`, `expire-pending-purchases`, `irl-reap`/`irl-drops-refund`, `run-x-scheduled-posts`, `unstoppable-tick`.@@ -1750,7 +1764,7 @@ flowchart LR```three.ws/ (root package v1.5.2, Node 24.x)-├── api/ (1,209 Vercel serverless functions)+├── api/ (~1,382 Vercel serverless functions)│ └── _lib/ (413 shared utilities)├── src/ (frontend JS modules)├── pages/ (150+ HTML entry points)@@ -1817,9 +1831,9 @@ three.ws/ (root package v1.5.2, Node 24.x)**Driver:** `@neondatabase/serverless` HTTP driver (tagged-template `sql` with composable fragments)-**Schema:** `api/_lib/schema.sql` — ~270 tables (full list in [Database Schema — Complete Table Index](#database-schema--complete-table-index))+**Schema:** `api/_lib/schema.sql` — ~295 tables (full list in [Database Schema — Complete Table Index](#database-schema--complete-table-index))-**Migrations:** `api/_lib/migrations/` — 234 dated migration files (2026-04-29 through 2026-06-23)+**Migrations:** `api/_lib/migrations/` — 259 dated migration files (2026-04-29 through 2026-07-02)Key table groups:@@ -2417,13 +2431,13 @@ Standalone HTML apps and asset roots served directly (not Vite-controller pages)### Complete Cron Schedule (`api/cron/`)-The full **61-job** schedule grouped by domain is documented under [Scheduled Jobs (Cron Reference)](#scheduled-jobs-cron-reference). All handlers authenticate via the `CRON_SECRET` Bearer gate.+The full **72-job** schedule grouped by domain is documented under [Scheduled Jobs (Cron Reference)](#scheduled-jobs-cron-reference). All handlers authenticate via the `CRON_SECRET` Bearer gate; write-heavy handlers add a storage-pressure preflight and every `wrapCron` writes a `cron:heartbeat:<name>` marker.---### Complete Database Table Inventory-The full ~270-table inventory grouped by domain lives in [Database Schema — Complete Table Index](#database-schema--complete-table-index). Key facts: `api/_lib/schema.sql` + **234 dated migration files** (2026-04-29 → 2026-06-29); extensions `citext`, `pg_trgm`, `pgcrypto` (**no pgvector** — embeddings are JSONB float arrays, cosine in JS); `master_wallets` and a few others are bootstrapped at runtime via `CREATE TABLE IF NOT EXISTS`.+The full ~295-table inventory grouped by domain lives in [Database Schema — Complete Table Index](#database-schema--complete-table-index). Key facts: `api/_lib/schema.sql` + **259 dated migration files** (2026-04-29 → 2026-07-02); extensions `citext`, `pg_trgm`, `pgcrypto` (**no pgvector** — embeddings are JSONB float arrays, cosine in JS); `master_wallets` and a few others are bootstrapped at runtime via `CREATE TABLE IF NOT EXISTS`.---@@ -2924,7 +2938,7 @@ CREATE2-deterministic, so `IdentityRegistry` + `ReputationRegistry` share one ad| **Community / IRL** | `club-payouts` `*/5m` · `irl-drops-refund` `*/10m` · `irl-reap` `:17 hourly` · `unstoppable-tick` `*/5m` || **X / social** | `run-x-scheduled-posts` `*/1m` · `run-x-triggers` `*/5m` · `fetch-x-metrics` `*/6h` || **Billing / subscriptions** | `process-subscriptions` `*/6h` · `expire-pending-purchases` `*/5m` · `flush-usage-events` `*/1m` |-| **Platform health / GC** | `uptime-check` `*/5m` · `world-health` `*/15m` · `quota-check` `hourly` · `/api/llm/health` `hourly` · `audit-log-cleanup` `daily 04:00` · `cleanup-csrf-tokens` `:17 hourly` · `siwx-gc` `daily 03:00` |+| **Platform health / GC** | `uptime-check` `*/5m` · `world-health` `*/15m` · `quota-check` `hourly` · `/api/llm/health` `hourly` · `audit-log-cleanup` `daily 04:00` · `cleanup-csrf-tokens` `:17 hourly` · `siwx-gc` `daily 03:00` · `db-retention` `*/15m` (Neon housekeeping — prune unbounded tables under the 512 MB cap) · `three-market-refresh` `*/1m` (single $THREE market fetch/min → L2 cache, kills upstream quota fan-out) |---@@ -2977,7 +2991,12 @@ The codebase references **~260 distinct `process.env.*` keys** across `api/`; `a| **RPC & chains** | `SOLANA_RPC_URL` · `SOLANA_RPC_URL_DEVNET` · `MAINNET_RPC_URL` · `BASE_RPC_URL` · `BASE_SEPOLIA_RPC_URL` · `SEPOLIA_RPC_URL` · `EVM_RPC_URL` · `RPC_URL_8453` · `RPC_URL_84532` · `CLUB_BASE_RPC_URL` · `A2A_REPUTATION_RPC_URL` · `HELIUS_API_KEY` · `ETHERSCAN_API_KEY` || **$THREE & treasuries** | `THREE_TOKEN_MINT` · `THREE_TOKEN_DECIMALS` · `THREE_TREASURY_WALLET` · `THREE_REWARDS_WALLET` · `THREE_BURN_ADDRESS` · `THREE_QUOTE_SECRET` · `THREE_QUOTE_TTL_S` · `THREE_PRIZE_PAYOUT_KEY` · `THREE_ALLOWANCE_DELEGATE_SECRET_KEY_B64` · `THREE_WS_MARK_ENFORCE` · `PLATFORM_TREASURY_KEYPAIR` · `TREASURY_KEYPAIR` · `COIN_TREASURY_SECRET_KEY_B64` · `COIN_CREATOR_SECRET_KEY_B64_*` · `CLUB_SOLANA_TREASURY_SECRET_KEY_B64` · `CLUB_EVM_TREASURY_PRIVATE_KEY` || **LLM / AI** | `ANTHROPIC_API_KEY` · `OPENAI_API_KEY` · `GROQ_API_KEY` · `OPENROUTER_API_KEY` · `OPENROUTER_FALLBACK_KEYS` · `NVIDIA_API_KEY` · `NVIDIA_A2F_FUNCTION_ID` · `NVIDIA_ASR_FUNCTION_ID` · `NVIDIA_COSMOS_INVOKE_URL` · `WATSONX_API_KEY/_URL/_PROJECT_ID/_SPACE_ID/_MODEL_ID/_GUARDIAN_MODEL_ID/_API_VERSION` · `WATSONX_ORCHESTRATE_URL/_API_KEY/_AGENT` · `DASHSCOPE_API_KEY` · `MODELSCOPE_API_KEY` · `LIVEPEER_API_KEY` · `VOYAGE_API_KEY` · `AIXBT_API_KEY/_API_BASE/_ENABLED` · `ELEVENLABS_API_KEY` |-| **x402 / payments** | `X402_FACILITATOR_URL(_BASE/_SOLANA)` · `X402_FACILITATOR_TOKEN(_BASE/_SOLANA)` · `X402_CDP_FACILITATOR_URL` · `X402_PAY_TO(_BASE/_BSC/_SOLANA)` · `X402_ASSET_ADDRESS_BASE/_BSC/_ARBITRUM` · `X402_ASSET_MINT(_SOLANA)` · `X402_FEE_PAYER_SOLANA` · `X402_ACCEPT_THREE_SOLANA` · `X402_THREE_AMOUNT_SOLANA` · `X402_EVM_NETWORKS` · `X402_MAX_PER_CALL/_HOUR/_DAY_ATOMIC` · `X402_MAX_AMOUNT_REQUIRED` · `X402_IDEMPOTENCY_TTL_SECONDS` · `X402_BUILDER_CODE_APP/_WALLET` · `CDP_API_KEY_ID/_SECRET` · `BSC_OPERATOR_KEY` · `PLATFORM_FEE_BPS` |+| **x402 / payments** | `X402_FACILITATOR_URL(_BASE/_SOLANA)` · `X402_FACILITATOR_TOKEN(_BASE/_SOLANA)` · `X402_CDP_FACILITATOR_URL` · `X402_PAY_TO(_BASE/_BSC/_SOLANA)` · `X402_ASSET_ADDRESS_BASE/_BSC/_ARBITRUM` · `X402_ASSET_MINT(_SOLANA)` · `X402_FEE_PAYER_SOLANA` · `X402_ACCEPT_THREE_SOLANA` · `X402_THREE_AMOUNT_SOLANA` · `X402_EVM_NETWORKS` · `X402_MAX_PER_CALL/_HOUR/_DAY_ATOMIC` · `X402_MAX_AMOUNT_REQUIRED` · `X402_IDEMPOTENCY_TTL_SECONDS` · `X402_BUILDER_CODE_APP/_WALLET` · `X402_PRICE_<SLUG>` (per-endpoint overrides) · `CDP_API_KEY_ID/_SECRET` · `BSC_OPERATOR_KEY` · `PLATFORM_FEE_BPS` |+| **x402 self-facilitator / ring** | `X402_SELF_FACILITATOR_ENABLED` · `X402_FEE_PAYER_SECRET_BASE58` · `X402_TREASURY_SECRET_BASE58` · `X402_SEED_SOLANA_SECRET_BASE58` · `X402_SELF_FACILITATOR_PAYTO_ALLOWLIST` · `X402_SPONSOR_SOL_FLOOR_LAMPORTS` · `X402_SELF_FAC_MAX_CU_LIMIT/_CU_PRICE/_PRIORITY_LAMPORTS` · `X402_RING_SELF_PAY` · `X402_PRICE_RING_SETTLE` · `X402_RING_TREASURY_BUFFER_ATOMIC` · `X402_RING_MIN_SWEEP_ATOMIC` · `X402_EXTERNAL_ENABLED` · `X402_AUTONOMOUS_DAILY_CAP_ATOMIC` · `X402_VOLUME_PER_RUN_CAP_ATOMIC` · `X402_VOLUME_BATCH_PER_RUN` |+| **Circulation engine** | `CIRCULATION_ENABLED` · `CIRCULATION_TREASURY_SECRET` · `CIRCULATION_NETWORK` · `CIRCULATION_POOL_TARGET` · `CIRCULATION_GROWTH_PER_TICK` · `CIRCULATION_ACTIONS_PER_TICK` · `CIRCULATION_EVM_TREASURY_SECRET` · `CIRCULATION_EVM_CHAIN_ID` (removed: `CIRCULATION_REAL_SELLER_DEMAND`, `_DAILY_CAP`) |+| **Sniper / trading** | `SNIPER_MODE` · `SNIPER_NETWORK` · `SNIPER_GLOBAL_KILL` · `SNIPER_POLL_MS` · `SNIPER_STRATEGY_REFRESH_MS` · `SNIPER_MAX_GLOBAL_BUYS_PER_MIN` · `SNIPER_BUY_CONCURRENCY/_QUEUE_DEPTH` · `SNIPER_CONFIRM_TIMEOUT_MS` · `SNIPER_FEED_WATCHDOG_MS` · `SNIPER_EXIT_ON_BEARISH(_MIN_CONFIDENCE)` · `SNIPER_CLAIM_POLL_MS/_LOOKBACK_S/_MAX_AGE_S` · `SNIPER_WALLET_<AGENTID>` · `SNIPER_ADMIN_TOKEN` |+| **Agora** | `AGENC_DEVNET_RPC_URL` · `AGORA_CLUSTER` · `AGORA_MAX/MIN_CITIZENS` · `AGORA_TICK_MS/_JITTER_MS` · `AGORA_RECONCILE_MS` · `AGORA_DISPATCH_TASKS` · `AGORA_ENABLE_HIRING/_VERIFY/_ARENA/_GUILD` · `AGORA_ARENA/GUILD_MAX_WORKERS` · `AGORA_ARENA_MIN_REP` · `AGORA_MAINNET_ENABLED` · `AGORA_THREE_MINT` · `AGORA_MAINNET_SPEND_CAP_ATOMIC` · `AGORA_MAX/DAILY_THREE_CAP` |+| **Agent screen / launcher** | `SCREEN_WORKER_SECRET` · `SCREEN_POOL_MAX` · `BROWSERBASE_API_KEY/_PROJECT_ID` (screen); `GCP_VIDEO2SCENE_URL` · `GCP_RECONSTRUCTION_KEY` (scene capture); launcher SOL caps + `avaturn_seed`/`app_flags` runtime toggles || **Agent payments / guards** | `A2A_MANDATE_SECRET` · `A2A_PAYER_PRIVATE_KEY` · `A2A_PAYER_SOLANA_PRIVATE_KEY/_SECRET` · `GUARDIAN_SEND_CAP_USD` · `GUARDIAN_DISABLE` · `AGENT_RELAYER_KEY/_ADDRESS` · `PERMISSIONS_RELAYER_ENABLED` || **Auth / identity** | `PRIVY_APP_ID/_APP_SECRET/_JWKS_ENDPOINT` · `VITE_PRIVY_APP_ID` · `GITHUB_OAUTH_CLIENT_ID/_SECRET` · `X_OAUTH_CLIENT_ID/_SECRET` · `NEYNAR_API_KEY` · `SAML_IDP_*` / `SAML_SP_*` (12 keys) · `ADMIN_ADDRESSES` · `BUILT_IN_ADMIN_ADDRESSES` · `ERC8004_VALIDATOR_PRIVATE_KEY` · `VALIDATOR_PRIVATE_KEY` · `HOLDER_PASS_SECRET` · `WALLET_CAPABILITY_SECRET` || **Storage / pinning / SNS** | `PINATA_JWT` · `NFT_STORAGE_TOKEN` · `BUBBLEGUM_MERKLE_TREE` · `BUBBLEGUM_TREE_AUTHORITY` · `THREEWS_SOL_PARENT_SECRET_BASE58` · `THREEWS_SOL_PARENT_DOMAIN` · `MINT_PUBKEY` |@@ -2991,7 +3010,7 @@ The codebase references **~260 distinct `process.env.*` keys** across `api/`; `a## Database Schema — Complete Table Index-`api/_lib/schema.sql` + **234 dated migration files** in `api/_lib/migrations/` (2026-04-29 → 2026-06-29) define **~270 Postgres tables** on Neon. Extensions: `citext`, `pg_trgm`, `pgcrypto` — **no pgvector**; embeddings are JSONB float arrays with cosine computed in JS. Complete index by domain:+`api/_lib/schema.sql` + **259 dated migration files** in `api/_lib/migrations/` (2026-04-29 → 2026-07-02) define **~295 Postgres tables** on Neon. Extensions: `citext`, `pg_trgm`, `pgcrypto` — **no pgvector**; embeddings are JSONB float arrays with cosine computed in JS. Complete index by domain:| Domain | Tables ||--------|--------|@@ -3000,13 +3019,14 @@ The codebase references **~260 distinct `process.env.*` keys** across `api/`; `a| **Wallets, custody & ledger** | `agent_payout_wallets` · `agent_payments` · `agent_payment_intents` · `agent_revenue_events` · `agent_withdrawals` · `agent_custody_events` · `agent_recovery_requests` · `agent_recovery_approvals` · `agent_recovery_guardians` · `agent_wallet_capabilities` · `agent_wallet_intents` · `agent_delegations` · `three_allowances` · `payouts` · `payment_configs_pending` · `custody_attestation_epochs` · `custody_attestation_leaves` · `ledger_anchors` · `credit_accounts` · `credit_ledger` · `circulation_actions` · `token_payments` || **Skills, assets & royalties** | `marketplace_skills` · `marketplace_themes` · `agent_skill_prices` · `skill_pricing_rules` · `skill_purchases` · `skill_access_grants` · `skill_installs` · `skill_license_mints` · `skill_payment_earnings` · `skill_usage_logs` · `skill_ratings` · `skill_reviews` · `skill_bundles` · `bundle_items` · `bundle_purchases` · `paid_assets` · `asset_prices` · `asset_purchases` · `asset_purchase_receipts` · `fork_royalty_terms` · `fork_royalty_payouts` · `listing_splits` · `listing_split_recipients` · `split_distributions` · `royalty_ledger` · `purchase_events` · `purchase_receipts` || **Pump.fun, oracle & intel** | `pump_agent_mints` · `pump_agent_payments` · `pump_agent_trades` · `pump_agent_stats` · `pump_agent_price_points` · `pump_coin_intel` · `pump_coin_outcomes` · `pump_coin_wallets` · `pump_intel_weights` · `pump_relay_trades` · `pump_trade_delegations` · `pump_buyback_runs` · `pump_distribute_runs` · `pump_autopilot` · `pump_alert_rules` · `pump_alert_rule_fires` · `pump_alert_deliveries` · `pumpfun_graduations` · `pumpfun_monitor_cursor` · `pumpfun_signals` · `pumpfun_signals_cursor` · `oracle_conviction` · `oracle_conviction_history` · `oracle_narrative` · `oracle_agent_watch` · `oracle_watch_actions` · `oracle_followers` · `coin_smart_money` · `smart_money_scored` · `smart_wallet_clusters` · `smart_wallet_folded` · `smart_wallet_reputation` · `wallet_reputation` · `firewall_decisions` · `radar_watchlist` · `radar_events` |-| **Trading, strategies & vaults** | `agent_sniper_strategies` · `agent_sniper_positions` · `agent_strategies` · `agent_strategy_equips` · `agent_strategy_positions` · `strategy_backtests` · `strategy_kill_switch` · `orders` · `order_fills` · `agent_mirror_follows` · `agent_mirror_fills` · `copy_subscriptions` · `copy_executions` · `dca_strategies` · `dca_executions` · `market_maker_policies` · `market_maker_actions` · `swarms` · `swarm_members` · `swarm_votes` · `swarm_payouts` · `agent_vaults` · `vault_backers` · `vault_positions` · `vault_events` · `signal_feeds` · `signal_emissions` · `signal_subscriptions` · `signal_deliveries` · `decision_outcomes` · `portfolio_snapshots` · `wallet_value_snapshots` |-| **x402, billing & subscriptions** | `x402_skus` · `x402_merchant_settings` · `x402_receipts` · `x402_checkout_calls` · `x402_pump_launches` · `x402_subscriptions` · `x402_access_log` · `x402_audit_log` · `subscriptions` · `subscription_plans` · `subscription_payments` · `subscription_checkouts` · `creator_subscriptions` · `user_agent_subscriptions` · `agent_subscriptions` · `plan_payment_intents` · `plan_quotas` · `bsc_consumed_tx` · `aws_marketplace_customers` · `aws_marketplace_metering` |+| **Trading, strategies & vaults** | `agent_sniper_strategies` · `agent_sniper_positions` · `token_intel_risk` · `sniper_funding_events` · `sniper_coin_sentiment` · `sniper_trade_analytics` · `three_market_signals` · `agent_strategies` · `agent_strategy_equips` · `agent_strategy_positions` · `strategy_backtests` · `strategy_kill_switch` · `orders` · `order_fills` · `agent_mirror_follows` · `agent_mirror_fills` · `copy_subscriptions` · `copy_executions` · `dca_strategies` · `dca_executions` · `market_maker_policies` · `market_maker_actions` · `agent_market_maker_configs` · `agent_market_maker_trades` · `swarms` · `swarm_members` · `swarm_votes` · `swarm_payouts` · `agent_vaults` · `vault_backers` · `vault_positions` · `vault_events` · `signal_feeds` · `signal_emissions` · `signal_subscriptions` · `signal_deliveries` · `decision_outcomes` · `portfolio_snapshots` · `wallet_value_snapshots` |+| **Coin launcher (autonomous)** | `launcher_config` · `launcher_queue` · `launcher_runs` · `launcher_claims` · `agent_launcher_configs` · `agent_launched_coins` |+| **x402, billing & subscriptions** | `x402_skus` · `x402_merchant_settings` · `x402_receipts` · `x402_checkout_calls` · `x402_pump_launches` · `x402_subscriptions` · `x402_access_log` · `x402_audit_log` · `x402_self_facilitator_log` · `x402_ring_ledger` · `x402_ring_wallets` · `x402_volume_metrics` · `x402_autonomous_log` · `x402_subscription_health` · `payment_reconciliation` · `payment_sessions` · `payment_session_executions` · `builder_code_attribution` · `granite_inference_health` · `subscriptions` · `subscription_plans` · `subscription_payments` · `subscription_checkouts` · `creator_subscriptions` · `user_agent_subscriptions` · `agent_subscriptions` · `plan_payment_intents` · `plan_quotas` · `bsc_consumed_tx` · `aws_marketplace_customers` · `aws_marketplace_metering` || **Community, worlds & labor** | `agora_citizens` · `agora_activity` · `agora_vouches` · `agora_idempotency` · `clash_battles` · `club_tips` · `club_payouts` · `club_bans` · `club_dancer_wallets` · `coin_launches` · `coin_events` · `coin_holders` · `coin_draws` · `coin_payouts` · `crews` · `crew_members` · `crew_invites` · `walk_sessions` · `walk_events` · `walk_metrics` · `walk_achievements` · `walk_control_sessions` · `walk_control_commands` · `tournaments` · `tournament_entries` · `bounties` · `bounty_submissions` · `bounty_submission_likes` · `agent_bounties` · `agent_jobs` · `agent_hires` · `agent_bids` · `agent_labor_policies` · `genome_breedings` · `irl_drops` · `irl_drop_claims` · `rider_passes` · `unstoppable_activity` · `unstoppable_reflections` · `unstoppable_treasury` · `scene_gates` · `world_docs` |-| **3D, avatars & forge** | `avatars` · `avatar_regen_jobs` · `animation_clips` · `mocap_clips` · `forge_creations` · `forge_votes` · `forge_board_winners` · `forge_seed_jobs` · `forge_consumption_redemptions` · `forge_high_redemptions` · `cosmetic_sales` · `cosmetic_creator_splits` · `token_metadata` · `launchpad_pages` |+| **3D, avatars & forge** | `avatars` · `avatar_regen_jobs` · `avatar_thumbnail_regen_jobs` · `avatar_search_warm_cache` · `avatar_vrm_compat` · `animation_clips` · `mocap_clips` · `forge_creations` · `forge_votes` · `forge_board_winners` · `forge_seed_jobs` · `forge_consumption_redemptions` · `forge_high_redemptions` · `cosmetic_sales` · `cosmetic_creator_splits` · `token_metadata` · `launchpad_pages` || **Patronage & agent services** | `agent_patron_perks` · `agent_patron_prefs` · `agent_paid_services` · `agent_autopilot_proposals` || **Widgets, notifications & RAG** | `widgets` · `widget_views` · `widget_chat_threads` · `widget_chat_messages` · `widget_knowledge_docs` · `widget_knowledge_chunks` · `plugins` · `chat_brand_config` · `notification_events` · `notification_preferences` · `user_alert_configs` · `user_alert_fires` |-| **Indexing, attestations & infra** | `erc8004_agents_index` · `erc8004_crawl_cursor` · `solana_attestations` · `solana_attestations_cursor` · `solana_attest_event_claims` · `three_holder_snapshot` · `three_holder_snapshot_meta` · `three_rewards_distributions` · `three_buyback_runs` · `usage_events` · `audit_log` · `bot_heartbeat` · `indexer_state` · `webhook_deliveries` · `developer_webhooks` · `referral_visits` · `decision_outcomes` |+| **Indexing, attestations & infra** | `erc8004_agents_index` · `erc8004_crawl_cursor` · `solana_attestations` · `solana_attestations_cursor` · `solana_attest_event_claims` · `solana_agents_index` · `three_holder_snapshot` · `three_holder_snapshot_meta` · `three_rewards_distributions` · `three_buyback_runs` · `usage_events` · `audit_log` · `bot_heartbeat` · `indexer_state` · `webhook_deliveries` · `developer_webhooks` · `referral_visits` · `decision_outcomes` · `agent_activations` · `agent_wallet_balance_log` · `app_flags` (runtime feature flags) || **X (social) automation** | `x_posts` · `x_scheduled_posts` · `x_triggers` · `x_pending_reviews` |> Several tables (e.g. `master_wallets`) are bootstrapped at runtime via `CREATE TABLE IF NOT EXISTS` rather than a migration — see [Known Gaps](#known-gaps--in-progress).@@ -3031,8 +3051,11 @@ The codebase references **~260 distinct `process.env.*` keys** across `api/`; `a| ERC-7710 delegation redemption | Opt-in, disabled by default | `PERMISSIONS_RELAYER_ENABLED` flag; `POST /api/permissions/redeem` is the incomplete path || `AgentPayments.sol` EVM deployment | Written, not deployed | All `agentPayments` addresses in `addresses.ts` are zero-address placeholders || ValidationRegistry mainnet | Testnet only | Platform validator key `0x93Bc7EfB…` provisioned but not funded or allow-listed |-| Trading swarms UI | Backend complete (2026-06-26 migration), no confirmed production page | `api/swarms/*`, swarms tables |-| Agora economy | Very new (2026-06-29 migration) | Workers/citizens exist but full economy bootstrapping in progress |+| Trading swarms UI | Backend + `/swarms` dashboard live; 3D Sniper Arena at `/play/arena` | `api/swarms/*`, `src/play/arena.js`, swarms tables |+| Agora economy | **Launched** (Commons live at `/agora`; Arena/Guild migration 2026-07-02) | Agent + human citizens, professions, verifiable WORK supply chain — see [Agora](#agora--living-agent--human-economy-verifiable-work-supply-chain) |+| Self-hosted x402 facilitator | Shipped, **off by default** | `X402_SELF_FACILITATOR_ENABLED` + sponsor secret required; `api/x402-facilitator` returns 503 otherwise |+| Autonomous coin launcher | Live (`launcher_config` defaults flipped to LIVE) | Real SOL, circuit-broken, storage-preflighted; admin arm at `/admin/launcher` |+| Agent-screen pool hosting | No true 24/7 host | Only first-party host is the self-renewing GitHub Actions burst runner (`cron 0 */5`); a Docker VM/Fly/Railway is recommended for production |### Technical Debt@@ -3058,6 +3081,9 @@ The codebase references **~260 distinct `process.env.*` keys** across `api/`; `a| `QSTASH_TOKEN` | Read directly via `process.env` rather than `env.js` — inconsistent pattern || Skill-license marketplace initialization | `initialize_marketplace` tx not confirmed as having run on mainnet || animation-sources/ population pipeline | `scripts/download-mixamo-animations.js` / `fetch-animations.sh` not automated in CI |+| Payment reconciliation is not a cron file | The daily revenue-reconciliation job is autonomous-registry entry `revenue-reconciliation` (self/027) executed inside `api/cron/x402-autonomous-loop.js` (`*/5`), not a standalone `api/cron/*` — do not confuse with `api/cron/reconcile-decisions.js` (oracle predictions) |+| `xactions/` version mismatch | `package.json`/`plugin.json` = v3.1.0 but `server.json`/`marketplace.json` still pin 3.0.42 |+| Trading Brain vs Sniper paths | `src/studio/money/trading-brain.js` shares the sniper compiler/backtester/DB but drives a partly separate discretionary path (`api/trading/*`, `api/strategies`, `api/agents/:id/strategies`) — two execution surfaces to keep in sync |---@@ -3107,11 +3133,13 @@ Two layers resolve paths: **`vercel.json`** (`routes` array, 932 entries — pro**System / Static / `.well-known`:** `/404` (catch-all `/(.*)`), `/500`, `/robots.txt`, `/llms.txt`, `/llms-full.txt`, `/sitemap.xml`→`/api/sitemap`, `/sitemap/{core,agents,avatars,widgets,profiles}.xml`→`/api/sitemap/[type]`, `/changelog.{json,xml}` (static, build-generated), `/rss.xml`, `/rss/announcements.xml`→`/api/rss/announcements`, `/openapi.json`→`/api/openapi-json`, `/agent-3d/versions.json` + `/agent-3d/:ver/agent-3d.js` (CDN lib), `.well-known/{solana/actions.json, chat-plugin.json, sperax-plugin.json, x402.json, agent-attestation-schemas, three-vanity.json, oauth-authorization-server, oauth-protected-resource}`→`/api/wk`, `.well-known/did.json`→`/api/x402/did`, `.well-known/jwks.json`→`/api/auth/persona`, `/footer.html`, `/nav.html` (shared partials); stable unhashed bundles `/footer-bot.js`, `/walk-companion.js`, `/walk-playground.js`, `/feature-tour.js`, `/notifications.js`, `/nav-tier-badge.js`, `/agent-bus.js`, `/i18n.js`, `/error-reporter.js`.-**Counts:** `vercel.json` = 932 route entries (~420 HTML/dir-index, ~65 redirects, rest API rewrites + asset/header routes); `pages/` ≈ 210 HTML, `public/` ≈ 230 HTML (incl. ~95 `news/`, demos, dashboard-classic, docs/walk). `vite.config.js` deliberately mirrors prod so dev matches.+**New routes (2026-06-27 → 07-02):** `/launch-studio` (50 mint recipes), `/launcher` (Memetic Launcher), `/agent-screen` + `/agents-live` (live agent casting), `/capture` (Scene Capture), `/diorama` (text→3D world), `/x402-revenue`, `/payments` (payment sessions), `/billing/keys`, `/agent-economy-volume`, `/deployments` (ERC-8004 feed), `/integrations`, `/partners`, `/viability`, `/pipeline`, `/oracle/docs`, `/ui-juice` (game-feel showcase), `/labs`, `/dashboard/{capabilities,systems,watch}`, and admin `/admin/{launcher,ops,seeder}`.++**Counts:** `vercel.json` = ~970 route entries (~440 HTML/dir-index, ~65 redirects, rest API rewrites + asset/header routes); `pages/` ≈ 230 HTML, `public/` ≈ 230 HTML (incl. ~95 `news/`, demos, dashboard-classic, docs/walk). `vite.config.js` deliberately mirrors prod so dev matches.### Complete API Directory Index-All **145 directories** under `api/`. `_`-prefixed dirs are shared internals; `[bracket].js` are dynamic routes.+All **150+ directories** under `api/` plus many top-level single-file endpoints. `_`-prefixed dirs are shared internals; `[bracket].js` are dynamic routes. New since the last revision: `x402-facilitator/`, `launcher/`, `pay/`, `ops/`, `diorama.js`, `scene-capture.js`/`scene-upload.js`, `deployments.js`, `billboard.js`, `pipeline.js`, `three-signal.js`, `agent-screen-*.js`, `agent-task.js`, `agent-ask.js`, `agent-collab.js`, `agent-vanity-grind.js`, `agent-economy/volume`, expanded `agent/` (session, caster-config, launcher, market-maker, screen-push/-stream, watch-intent/-status/-wanted, anchor-script).| Directory | Files | Purpose ||---|---|---|@@ -3120,12 +3148,12 @@ All **145 directories** under `api/`. `_`-prefixed dirs are shared internals; `[| `_providers/` | 10 | 3D/image gen provider adapters (gcp, huggingface, meshy, nvidia, nvidia-cosmos, replicate, rodin, stability, tripo) + BYOK registry. || `_studio/` | 3 | Studio MCP tool registry/dispatch. || `actions/` | avatar, avatar-icon | Farcaster/embed action endpoints. |-| `admin/` | 11 | Admin console (revenue, health, bulk-launch, withdrawals, register-agents, club/news/user subdirs). |+| `admin/` | 16 | Admin console (revenue, health, bulk-launch, withdrawals, register-agents, club/news/user subdirs) + `all-systems`, `circulation-health`, `flags`, `launcher`, `seeder`, `ops`. || `agenc/` | [action] | AgenC / watsonx Orchestrate dispatcher. || `agent-3d/` | versions | 3D asset version listing. || `agent-economy/` | status, transact | Two-agent demo economy. || `agent-trade/` | demo (SSE), skill | Live A2A trade demo + tradeable skill. |-| `agent/` | activity, dreams, reflect, send-sol, wallet | Single-agent runtime. |+| `agent/` | activity, dreams, reflect, send-sol, wallet, session, caster-config, launcher, market-maker, screen-push, screen-stream, watch-intent, watch-status, watch-wanted, anchor-script | Single-agent runtime + live-caster signaling + per-agent launcher/MM config. || `agents/` | ~60+ incl `[id]/`, a2a-* (call/cart-verify/hire/mandate/paid), solana*/onchain/, register/, sas/, ens/, pumpfun/, endpoint-shopper-run, networth, copilot, recovery | Central agent surface (identity, A2A, trading/strategy/mirror, ERC-8004 register, Solana ops, portfolio). || `agi/` | state | AGI global state. || `agora/` | [action], act | Agora citizen actions. |@@ -3155,7 +3183,7 @@ All **145 directories** under `api/`. `_`-prefixed dirs are shared internals; `[| `creators/` | [id], skill-analytics | Creator profiles + analytics. || `credits/` | deposit, index | Prepaid credit wallet. || `crews/` | [tag], index | Crews/clans. |-| `cron/` | 32 files | Scheduled jobs (fanouts, attest, reputation, seeding, sweeps, health) — 61 schedules in vercel.json. |+| `cron/` | ~42 files | Scheduled jobs (fanouts, attest, reputation, seeding, sweeps, health, db-retention, launcher, x402 autonomous loop) — 72 schedules in vercel.json. || `custody/` | anchor, integrity | Custodial-wallet anchors + integrity proofs. || `cz/` | claim | CZ campaign claim. || `dad/` | generate | Persona/"dad" generation. |@@ -3195,8 +3223,10 @@ All **145 directories** under `api/`. `_`-prefixed dirs are shared internals; `[| `og/` | agent, sealed-drop, three-token-badge | OG image generators. || `onboarding/` | [action] | Onboarding dispatcher. || `onramp/` | link | Fiat on-ramp link. |+| `ops/` | health | Comprehensive internal health + cron heartbeats. |+| `launcher/` | me, trends | Autonomous Memetic Launcher (per-user scope + cultural-intelligence trends feed). || `oracle/` | 24 files (action-stream, feed, stream, leaderboard, backtest, coin, signal, social, watch, follow, movers, wins, og, …) | Granite Oracle product surface. |-| `pay/` | deal | Pay-by-deal. |+| `pay/` | deal, session, execute | Pay-by-deal + governed x402 payment sessions (create/inspect/cancel + govern-then-spend execute). || `payments/` | intent, purchase-skill, evm/, solana/, _config | Unified payment intents. || `permissions/` | [action] | ERC-7710 permission grant/redeem dispatcher. || `persona/` | extract, preview | Persona extraction from social seeds. |@@ -3251,17 +3281,19 @@ All **145 directories** under `api/`. `_`-prefixed dirs are shared internals; `[| `widgets/` | [id]/, index, oembed, og, page, view, _demo-fixtures | Embeddable widgets. || `world/` | [action] | Per-world persistence dispatcher. || `x/` | post, draft, schedule, analytics, reviews, status, triggers | X (Twitter) automation. |-| `x402/` | 34 files (forge, mint-to-mesh(+batch), token-intel, crypto-intel, three-intel, skill-call, skill-marketplace, pay-by-name, agent-bouncer, agent-reputation, onchain-identity-verify, pump-agent-audit, pump-launch, fact-check, dance-tip, asset-download, animation-download, vanity(+-verifiable), symbol-availability, model-check, permit2-paid-demo, club-cover, cosmetic-purchase, my-receipts, did, service, admin/) | Paid x402 endpoint catalog (each file = a monetized service). |+| `x402/` | ~60 files (forge, mint-to-mesh(+batch), token-intel, crypto-intel, three-intel, skill-call, skill-marketplace, pay-by-name, agent-bouncer, agent-reputation, onchain-identity-verify, pump-agent-audit, pump-launch, fact-check, dance-tip, asset-download, animation-download, vanity(+-verifiable), symbol-availability, model-check, permit2-paid-demo, club-cover, cosmetic-purchase, my-receipts, did, service, admin/ · **new:** analytics, ring-settle, llm-proxy, cross-chain, bazaar-feed, mcp-tool-catalog, feed-health, schema-check, model-validation-sweep, notify, rate-limit-probe, api-key-health, auth-health, telegram-health, wallet-connect, solana-register-health, spend-session, avatar-optimize-batch, billboard, mcp-perf, granite-health, glb-optimization-report, service-pricing-report, network-cost) | Paid x402 endpoint catalog (each file = a monetized service) + free ops-dashboard reads. See [x402 self-hosted facilitator](#self-hosted-facilitator--closed-loop-economy). || `x402-pay/` | og | OG image for x402 payment pages. |+| `x402-facilitator/` | [action] | **Self-hosted x402 Solana facilitator** — `/verify`, `/settle`, `/supported` (off by default). |+| `x402-revenue.js` · `x402-ring.js` · `x402-status.js` | (single files) | Public revenue feed · closed-loop net-position report · facilitator status probe. |### Complete `api/_lib/` Utility Catalog-**326 top-level `.js` modules** + **19 sub-packages** (`a2a`, `a2f-protos`, `club`, `coin`, `copy`, `evm`, `format`, `market`, `migrations`, `oracle`, `pricing`, `pump-intel`, `riva-protos`, `services`, `sniper`, `solana`, `token`, `trust`, `x402`). Nothing in `_lib` is itself a route. Grouped by domain:+**~357 top-level `.js` modules** + **21 sub-packages** (`a2a`, `a2f-protos`, `club`, `coin`, `copy`, `evm`, `format`, `launch`, `market`, `migrations`, `oracle`, `pay`, `pricing`, `pump-intel`, `riva-protos`, `services`, `sniper`, `solana`, `token`, `trust`, `x402`). The `x402/` sub-package now carries a `pipelines/` fleet for the autonomous economy. Nothing in `_lib` is itself a route. Grouped by domain:- **DB / cache / storage / infra:** `db.js`, `db-retry.js`, `schema.sql`, `migrations/`, `cache.js`, `redis.js`, `redis-usage.js`, `skill-price-cache.js`, `r2.js`, `ipfs-pin.js`, `storage-mode.js`, `forge-cache.js`, `qstash.js`, `resilience.js` (cockatiel), `sse-poll-breaker.js`, `env.js`, `http.js`, `http-params.js`, `ids.js`, `sentry.js`, `axiom.js`, `rate-limit.js`.- **Auth / security / crypto:** `auth.js`, `account-auth.js`, `admin.js`, `zauth.js`, `crypto.js`, `secret-box.js` (AES-256-GCM), `provider-keys.js`, `csrf.js`, `ssrf.js`, `ssrf-guard.js`, `fetch-model.js`, `pii.js`, `moderation.js` (NemoGuard), `granite-guardian.js`, `identity-integrity.js`, `siwe.js`, `siws.js`, `siwx-server.js`, `siwx-storage.js`, `saml.js`, `privy.js`, `audit.js`.- **Solana / on-chain:** `solana/` (connection, rpc-fallback, confirm, gasless-tx, idl, programs, sdk-bridge), `solana-wallet.js`, `solana-signers.js`, `solana-transfer.js`, `solana-collection.js`, `solana-token-meta.js`, `token-metadata.js`, `onchain.js`, `onchain-deploy.js`, `agent-registry.js`, `agent-invocation-onchain.js`; attestations: `attest-event.js`, `sas.js`, `solana-attestations.js`, `solana-validation-attest.js`, `validation-attest.js`, `tournament-attest.js`, `trader-score-attest.js`, `ledger-anchor.js`, `brain-anchor.js`, `custody-proof.js`; `helius.js`, `balances.js`, `three-brand.js`, `threews-sns.js`.-- **EVM / x402:** `x402/` (a2a-client/server, access-control, api-keys, audit-log, auth-hints, bazaar-client/helpers, idempotency-cache, offer-receipt-issuer/server, payment-identifier-client/server, paywall-handler, receipt-storage), `x402.js`, `x402-spec.js`, `x402-paid-endpoint.js`, `x402-prices.js`, `x402-errors.js`, `x402-buyer-fetch.js`, `x402-buyer-axios.js`, `x402-user-payer.js`, `x402-spending-cap/-ledger/-price.js`, `x402-solana-confirm.js`, `x402-bsc-direct.js`, `x402-builder-code.js`, `evm/rpc.js`, `evm-transfer.js`, `evm-payment-verify.js`, `erc8004-chains.js`, `a2a/` (cart-mandate, mandate, reputation-gate, spend-ledger), `aws-marketplace.js`, `aws-marketplace-bridge.js`.+- **EVM / x402:** `x402/` (a2a-client/server, access-control, api-keys, audit-log, auth-hints, bazaar-client/helpers, idempotency-cache, offer-receipt-issuer/server, payment-identifier-client/server, paywall-handler, receipt-storage · **economy layer:** self-facilitator, pay, solana-payer, autonomous-registry, revenue-analytics, revenue-reconciliation, user-activity-analytics, agent-leaderboard-store, wallet-balance-monitor, granite-health, three-signal-store, sniper-analytics-store, scene-capture-processor, `pipelines/*`), `x402.js`, `x402-spec.js`, `x402-paid-endpoint.js`, `x402-prices.js`, `x402-errors.js`, `x402-buyer-fetch.js`, `x402-buyer-axios.js`, `x402-user-payer.js`, `x402-offer-receipt.js`, `x402-spending-cap/-ledger/-price.js`, `x402-solana-confirm.js`, `x402-bsc-direct.js`, `x402-builder-code.js`, `pay/` (payment-session, spend-governor), `evm/rpc.js`, `evm-transfer.js`, `evm-payment-verify.js`, `erc8004-chains.js`, `a2a/` (cart-mandate, mandate, reputation-gate, spend-ledger), `aws-marketplace.js`, `aws-marketplace-bridge.js`.- **LLM / embeddings / vision / voice:** `llm.js`, `chat-models.js`, `llm-pricing.js`, `llm-health.js`, `provider-health.js`, `strip-reasoning.js`, `orchestrate.js`, `watsonx.js`, `watsonx-forecast.js`, `embeddings.js`, `agent-embeddings.js`, `embedding-math.js`, `chunker.js`, `text-extract.js`, `rerank.js`, `vision.js`, `avatar-alt-text.js`, `forge-image-validate.js`, `a2f-nvidia.js`, `asr-nvidia.js`, `tts-nvidia.js`, `tts-voices.js`, `elevenlabs.js`, `a2f-protos/`, `riva-protos/`.- **Forge / 3D / avatars:** `forge-tiers/-options/-store/-events/-health/-lane-health/-scale/-job-token/-provider-key/-high-payment/-consumption-payment.js`, `glb-compress/-inspect/-quality/-themer.js`, `model-inspect.js`, `rig-inspect.js`, `provider-result-url.js`, `avatars.js`, `avatar-agent/-render/-wallet.js`, `bake.js`, `accessories.js`, `auto-rig.js`, `auto-rig-eligibility.js`, `avaturn-headless.js`, `avaturn-seed.js`, `reconstruct-finalize.js`, `regen-provider.js`, `render-glb.js`, `render-clip.js`, `networth-model.js`, `genome.js`, `genome-agent.js`, `fork-royalties.js`, `remix-royalty.js`.- **Pump / oracle / intel / market:** `pump.js`, `pump-go/-launch/-launch-feed/-quote/-pricing/-platform-fee/-swap-ix/-trade-args/-vanity/-claims.js`, `pump-alert-eval/-runner.js`, `pumpfun-mcp.js`, `pumpfun-ws-feed.js`, `pump-intel/` (enrich, funder-graph, news-matcher, smart-money-xref), `oracle/` (agent-eval, alerts, archetype, conviction, known-wallets, narrative, news-context, settle, sources, store), `aixbt.js`, `birdeye.js`, `gmgn-feed.js`, `smart-money.js`, `coin-communities.js`, `channel-feed-sources.js`, `signal-engine.js`, `alpha-read.js`, `token-market.js`, `market/` (ohlcv, token-market), `coin/` (cohorts, creator-fees, distribution, holders, three-holders, treasury, payouts, randomness).@@ -3271,10 +3303,11 @@ All **145 directories** under `api/`. `_`-prefixed dirs are shared internals; `[- **IRL / community / world / club / stage:** `irl-auth/-bake/-drops/-presence.js`, `geohash.js`, `world-lines.js`, `sealed-drop-store.js`, `sealed-drop-funding.js`, `resolve-recipient.js`, `world-store/-gate/-service-auth.js`, `crews-store.js`, `friends-store.js`, `presence-store.js`, `diorama-store.js`, `builds-store.js`, `clash.js`, `clash-store.js`, `club/` (chain, cover-pass, payouts, sweep), `stage-bridge.js`, `stage-split.js`, `agora-human.js`, `agora-policy.js`.- **Notifications / comms / distribution:** `notify.js`, `notify-prefs.js`, `alerts.js`, `alert-delivery.js`, `web-push.js`, `email.js`, `newsletter.js`, `webhook-dispatch.js`, `x-post.js`, `indexnow.js`, `rss-feed.js`, `feed.js`.- **MCP / aggregator / validation / misc:** `mcp-dispatch.js`, `mcp-batch-price.js`, `mcp-error-sanitize.js`, `mcp-getting-started.js`, `pump-pricing.js`, `aggregator.js`, `gateway.js`, `validate.js` (zod schemas), `embed.js`, `embed-policy.js`, `widget-types.js`, `cosmetics.js`, `cosmetics-economy.js`, `cosmetics-ownership.js`, `pump-vanity.js`, `vanity-bounty-store.js`, `vanity-bounty-payout.js`, `vanity-cert-store.js`, `vanity-gallery-store.js`, `vanity-service-key.js`, `bounty-judge.js`, `bounty-likes.js`, `provider-job-error.js`, `format/links.js`.+- **Autonomous launcher / live-caster / seeder / infra:** `launcher-engine.js`, `launcher-funding.js`, `launcher-sources.js`, `launcher-trends.js`, `launch/` (registry, usecase-engine, candidate-sources, `usecases/{community,culture,events,github,news,onchain}`), `agent-orchestrate.js`, `agent-activation.js`, `agent-achievements(.js/-data.js)`, `agent-screen-frame.js`, `a2a-hire-phases.js`, `reaction-rules.js`, `agora-task-live.js`, `signal-engine-core.js`, `pulse-trading.js`, `pipeline-summary.js`, `solana-agents-crawl.js`, `solana-agents-normalize.js`, `studio-avatar.js`, `avaturn-photo.js`, `avatar-search-warm.js`, `embed-asset.js`, `vanity-frame.js`, `vanity-grind-stats.js`, `flags.js` (runtime feature flags), `platform-treasury.js`, `github-trending.js`, `github-reward.js`, `review-attest.js`, `quote-mints.js`, `billboard-store.js`, `diorama-store.js`, `club/cover-revenue.js`.### Complete MCP Tool Reference-three.ws exposes MCP tools across **8 remote HTTP servers** + **32 stdio/npm servers** (`mcp-server`, `mcp-bridge`, 30 `packages/*-mcp`).+three.ws exposes MCP tools across **8 remote HTTP servers** + **34 stdio/npm servers** (`mcp-server`, `mcp-bridge`, 32 `packages/*-mcp` — now including `agentcore-payments-mcp` and `alibaba-cloud-mcp`), plus the standalone `@three-ws/agent-sniper` MCP face and the vendored `xactions-mcp` (~140 X/Twitter tools).**Remote HTTP servers:**@@ -3294,7 +3327,10 @@ three.ws exposes MCP tools across **8 remote HTTP servers** + **32 stdio/npm ser- **`@three-ws/activity-mcp`**: `get_trending_agents`, `get_trending_coins`, `get_holder_leaderboard`, `get_tier_info`, `get_feed_events`.- **`@three-ws/agenc-mcp`**: `get_agent`, `get_task`, `link_agent`, `list_tasks`, `query_x402_services`.- **`@three-ws/agora-mcp`**: `agora_board`, `agora_citizens`, `agora_passport`, `agora_professions`, `agora_pulse`, `agora_register`, `agora_claim_task`, `agora_complete_task`, `agora_post_task`.+- **`@three-ws/agentcore-payments-mcp`**: `create_payment_session`, `pay_with_session`, `check_payment_session`, `list_payment_sessions`, `cancel_payment_session`.- **`@three-ws/alerts-mcp`**: `create_alert_rule`, `update_alert_rule`, `delete_alert_rule`, `list_alert_rules`, `get_alert_history`.+- **`@three-ws/alibaba-cloud-mcp`**: `qwen_chat`, `qwen_embed`, `qwen_list_models` (DashScope, user's own `DASHSCOPE_API_KEY`).+- **`@three-ws/agent-sniper`** (standalone package `./mcp` face): `arm_strategy`, `disarm_strategy`, `list_strategies`, `snipe_now`, `list_positions`, `close_position`, `sniper_status`.- **`@three-ws/audio-mcp`**: `text_to_speech`, `speech_to_text`, `audio_to_face`, `motion_capture_clips`, `motion_capture_clip`.- **`@three-ws/autopilot-mcp`**: `get_autopilot_config`, `set_autopilot_config`, `compute_trust`, `generate_proposals`, `list_proposals`, `adjust_proposal`, `dryrun_proposal`, `dismiss_proposal`, `execute_proposal`, `undo_action`, `list_autopilot_activity`.- **`@three-ws/avatar-agent`**: `spawn_avatar`, `dress_avatar`, `generate_avatar`, `render_avatar`, `thumbnail_glb`, `viewer_url`, `list_avatars`, `list_animations`, `inspect_glb`, `validate_glb`, `optimize_glb`, `speak`, `ens_sns_resolve`, `wallet_create`, `wallet_balance`, `wallet_send`, `pump_buy`, `pump_launch`, `pump_collect_fees`, `pump_snapshot` (20).diff --git a/api/agent/caster-config.js b/api/agent/caster-config.jsindex e4138857b..35e6e1dd6 100644--- a/api/agent/caster-config.js+++ b/api/agent/caster-config.js@@ -64,7 +64,7 @@ export default wrap(async (req, res) => {``,`AGENT_ID=${agentId}`,`AGENT_BEARER_TOKEN=${rawToken}`,- `PUSH_URL=https://three.ws/api/agent/screen-push`,+ `PUSH_URL=https://three.ws/api/agent-screen-push`,``,`# Task: pump-monitor | trade`,`TASK=pump-monitor`,@@ -80,7 +80,7 @@ export default wrap(async (req, res) => {`docker run --rm \\`,` -e AGENT_ID=${agentId} \\`,` -e AGENT_BEARER_TOKEN=${rawToken} \\`,- ` -e PUSH_URL=https://three.ws/api/agent/screen-push \\`,+ ` -e PUSH_URL=https://three.ws/api/agent-screen-push \\`,` -e TASK=pump-monitor \\`,` -e TASK_ARG=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump \\`,` three-ws/agent-screen-caster`,diff --git a/api/agent/screen-push.js b/api/agent/screen-push.jsdeleted file mode 100644index 6d4316b11..000000000--- a/api/agent/screen-push.js+++ /dev/null@@ -1,106 +0,0 @@-// POST /api/agent/screen-push-//-// Agent processes (Playwright runners, autonomous workers) push their current-// screen state here. Two payload shapes are accepted:-//-// Frame push (screenshot):-// { agentId, frame: '<base64 PNG>', seq?: number }-// → stored as screen:frame:<agentId> with 10-second TTL.-//-// Activity push (structured log):-// { agentId, actions: [{ type, summary, payload?, ts? }] }-// → stored as screen:activity:<agentId> with 30-second TTL.-//-// Auth: requires a valid bearer token for a user that owns the agent, OR the-// agent's own bearer token (AGENT_BEARER environment variable on the worker).-// Rate: 12 frame pushes/second per agentId (burst) to prevent flooding.--import { timingSafeEqual } from 'node:crypto';-import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';-import { cacheSet } from '../_lib/cache.js';-import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';-import { sql } from '../_lib/db.js';-import { limits, clientIp } from '../_lib/rate-limit.js';--// First-party on-demand caster pool authenticates with a shared secret and may-// push frames for ANY agent (it casts whichever agents viewers are watching).-const WORKER_SECRET = process.env.SCREEN_WORKER_SECRET || '';-function isPoolWorker(bearer) {- if (!bearer || !WORKER_SECRET || WORKER_SECRET.length < 16) return false;- const a = Buffer.from(bearer);- const b = Buffer.from(WORKER_SECRET);- return a.length === b.length && timingSafeEqual(a, b);-}--const FRAME_TTL_S = 10;-const ACTIVITY_TTL_S = 30;--// Validate base64 string length — limit 1 MB of base64 ≈ 768 KB PNG.-const MAX_FRAME_B64 = 1_400_000;--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;- if (!method(req, res, ['POST'])) return;-- // Auth: first-party pool worker (shared secret, any agent), the agent's own- // bearer (worker), OR the owner's session. Bearer first so headless workers- // authenticate without a cookie.- let userId = null;- let isWorker = false;- const bearer = extractBearer(req);- if (isPoolWorker(bearer)) {- isWorker = true;- } else {- if (bearer) {- const a = await authenticateBearer(bearer).catch(() => null);- if (a?.userId) userId = a.userId;- }- if (!userId) {- const a = await getSessionUser(req, res).catch(() => null);- if (a?.id) userId = a.id;- }- if (!userId) return error(res, 401, 'unauthorized', 'sign in required');- }-- // Rate limit before reading the body so a flood can't force large buffers.- const rl = await limits.apiIp(clientIp(req), { limit: 720, window: '60s' });- if (!rl.success) return rateLimited(res, rl, 'too many pushes');-- const body = await readJson(req, MAX_FRAME_B64 + 4_000).catch(() => null);- if (!body) return error(res, 400, 'invalid_body', 'request body must be valid JSON');- const { agentId, frame, actions, seq } = body;-- if (!agentId) return error(res, 400, 'validation_error', 'agentId required');-- // Ownership: the pool worker may cast any existing agent; owners only their own.- const [row] = isWorker- ? await sql`SELECT id FROM agent_identities WHERE id = ${agentId} AND deleted_at IS NULL`- : await sql`SELECT id FROM agent_identities WHERE id = ${agentId} AND user_id = ${userId} AND deleted_at IS NULL`;- if (!row) return error(res, isWorker ? 404 : 403, isWorker ? 'not_found' : 'forbidden', isWorker ? 'agent not found' : 'not your agent');-- const now = Date.now();-- if (frame != null) {- // Frame push.- if (typeof frame !== 'string') return error(res, 400, 'validation_error', 'frame must be a base64 string');- if (frame.length > MAX_FRAME_B64) return error(res, 413, 'payload_too_large', 'frame exceeds 1 MB');- const storedSeq = typeof seq === 'number' ? seq : now;- await cacheSet(`screen:frame:${agentId}`, { frame, seq: storedSeq, ts: now }, FRAME_TTL_S);- return json(res, 200, { ok: true, type: 'frame', seq: storedSeq });- }-- if (actions != null) {- // Activity push.- if (!Array.isArray(actions)) return error(res, 400, 'validation_error', 'actions must be an array');- const safe = actions.slice(0, 50).map((a) => ({- type: String(a?.type || 'action').slice(0, 64),- summary: String(a?.summary || '').slice(0, 256),- payload: a?.payload || null,- ts: typeof a?.ts === 'number' ? a.ts : now,- }));- await cacheSet(`screen:activity:${agentId}`, { actions: safe, ts: now }, ACTIVITY_TTL_S);- return json(res, 200, { ok: true, type: 'activity', count: safe.length });- }-- return error(res, 400, 'validation_error', 'provide either frame or actions');-});diff --git a/api/agent/screen-stream.js b/api/agent/screen-stream.jsdeleted file mode 100644index bb85bfb71..000000000--- a/api/agent/screen-stream.js+++ /dev/null@@ -1,152 +0,0 @@-// GET /api/agent/screen-stream?agentId=<id>-//-// Server-Sent Events stream that delivers:-// { type: 'frame', frame: '<base64 PNG>', seq: number, ts: number }-// { type: 'activity', actions: [...], ts: number }-// { type: 'meta', name, avatar, status, ts: number }-// { type: 'heartbeat', ts: number }-//-// Agents push frames via POST /api/agent/screen-push. If no external process-// is pushing frames the client renders the activity canvas from real agent--// action records instead. The stream never closes while the client holds it.-//-// Auth: agentId must be known (public read of a real agent's stream).-// Rate: one active SSE connection per agentId per client IP is enforced by the-// 60-second Vercel function timeout — the client reconnects via EventSource.--import { cors, wrap } from '../_lib/http.js';-import { cacheGet } from '../_lib/cache.js';-import { sql } from '../_lib/db.js';-import { clientIp } from '../_lib/rate-limit.js';--const HEARTBEAT_MS = 15_000;-const FRAME_POLL_MS = 250; // how often to check for a new pushed frame-const ACTIVITY_POLL_MS = 3_000;-const MAX_DURATION_MS = 55_000; // stay under Vercel's 60-second function limit--export const config = { maxDuration: 60 };--export default wrap(async (req, res) => {- if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;-- const url = new URL(req.url, 'http://x');- const agentId = url.searchParams.get('agentId');- if (!agentId) {- res.statusCode = 400;- res.end('agentId required');- return;- }-- // Verify agent exists (public read — no auth needed).- const [agent] = await sql`- SELECT id, name, avatar_glb_url, avatar_model_url, base_model_url- FROM agent_identities- WHERE id = ${agentId} AND deleted_at IS NULL- LIMIT 1- `.catch(() => [null]);- if (!agent) {- res.statusCode = 404;- res.end('agent not found');- return;- }-- res.writeHead(200, {- 'Content-Type': 'text/event-stream; charset=utf-8',- 'Cache-Control': 'no-cache, no-transform',- 'X-Accel-Buffering': 'no',- 'Connection': 'keep-alive',- });-- function send(obj) {- if (res.writableEnded) return;- res.write(`data: ${JSON.stringify(obj)}\n\n`);- }-- // Send agent identity immediately so the client can show the webcam.- const avatarUrl = agent.avatar_glb_url || agent.avatar_model_url || agent.base_model_url || '/avatars/mannequin.glb';- send({ type: 'meta', agentId, name: agent.name || 'Agent', avatarUrl, ts: Date.now() });-- let lastFrameSeq = -1;- let lastActivityTs = 0;- let lastFrameKey = `screen:frame:${agentId}`;- let lastActivityKey = `screen:activity:${agentId}`;- const start = Date.now();-- // Stagger polls slightly so frame + activity checks don't race on the same tick.- let frameTick = 0;- let activityTick = 0;- let heartbeatTick = 0;-- await new Promise((resolve) => {- const timer = setInterval(async () => {- if (res.writableEnded || Date.now() - start > MAX_DURATION_MS) {- clearInterval(timer);- resolve();- return;- }-- const now = Date.now();- frameTick += FRAME_POLL_MS;- activityTick += FRAME_POLL_MS;- heartbeatTick += FRAME_POLL_MS;-- // ── pushed frame ────────────────────────────────────────────────- if (frameTick >= FRAME_POLL_MS) {- frameTick = 0;- try {- const stored = await cacheGet(lastFrameKey);- if (stored && stored.seq !== lastFrameSeq) {- lastFrameSeq = stored.seq;- send({ type: 'frame', frame: stored.frame, seq: stored.seq, ts: stored.ts });- }- } catch { /* non-critical */ }- }-- // ── activity log ────────────────────────────────────────────────- if (activityTick >= ACTIVITY_POLL_MS) {- activityTick = 0;- try {- // Check if agent process pushed structured activity.- const pushed = await cacheGet(lastActivityKey);- if (pushed && pushed.ts > lastActivityTs) {- lastActivityTs = pushed.ts;- send({ type: 'activity', actions: pushed.actions || [], ts: pushed.ts });- } else if (!pushed) {- // Fall back to real agent-actions rows from the DB.- const rows = await sql`- SELECT id, action_type, summary, payload, created_at- FROM agent_actions- WHERE agent_id = ${agentId}- ORDER BY id DESC- LIMIT 12- `.catch(() => []);- if (rows.length) {- send({- type: 'activity',- actions: rows.map((r) => ({- id: String(r.id),- type: r.action_type || 'action',- summary: r.summary || r.action_type || 'action',- payload: r.payload || null,- ts: r.created_at ? new Date(r.created_at).getTime() : now,- })),- ts: now,- });- }- }- } catch { /* non-critical */ }- }-- // ── heartbeat ───────────────────────────────────────────────────- if (heartbeatTick >= HEARTBEAT_MS) {- heartbeatTick = 0;- send({ type: 'heartbeat', ts: now });- }- }, FRAME_POLL_MS);-- req.on('close', () => { clearInterval(timer); resolve(); });- req.on('error', () => { clearInterval(timer); resolve(); });- });-- if (!res.writableEnded) res.end();-});diff --git a/api/x402/crypto-intel.js b/api/x402/crypto-intel.jsindex 6b2fb3105..a7b3146e6 100644--- a/api/x402/crypto-intel.js+++ b/api/x402/crypto-intel.js@@ -10,7 +10,10 @@// Response: { topic, headline, signal, price_usd?, change_24h?,// rationale, confidence, ts }//-// Data is live: CoinGecko public API (no key required). No mock path.+// Data is live: CoinGecko public API first, Binance 24h ticker as fallback+// (both keyless). CoinGecko's shared-IP quota rate-limits Vercel egress often;+// the fallback keeps paid calls answering with real data. No mock path — if+// both sources fail the call 503s before settlement and the buyer isn't charged.import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';import { buildBazaarSchema } from '../_lib/x402-spec.js';@@ -108,6 +111,27 @@ async function fetchLivePrice(coinId) {return { price_usd: coin.usd ?? null, change_24h: coin.usd_24h_change ?? null };}+// Reverse of ALIASES so a CoinGecko id resolves back to its exchange ticker.+const TICKER_BY_ID = Object.fromEntries(Object.entries(ALIASES).map(([t, id]) => [id, t]));++// Binance public 24h ticker — keyless with per-IP limits generous enough that+// shared serverless egress doesn't trip them. USDT-quoted, so prices track USD.+async function fetchBinance24h(topic, coinId) {+ const ticker = ALIASES[topic] ? topic+ : TICKER_BY_ID[coinId] || (/^[a-z0-9]{2,10}$/.test(topic) ? topic : null);+ if (!ticker) return null;+ const r = await fetch(+ `https://api.binance.com/api/v3/ticker/24hr?symbol=${ticker.toUpperCase()}USDT`,+ { headers: { Accept: 'application/json' }, signal: AbortSignal.timeout(6000) },+ );+ if (!r.ok) return null;+ const d = await r.json();+ const price = Number(d.lastPrice);+ const change = Number(d.priceChangePercent);+ if (!Number.isFinite(price) || !Number.isFinite(change)) return null;+ return { price_usd: price, change_24h: change };+}+function buildSignal(topic, price, change) {const fmt = (n) => (n >= 100 ? n.toFixed(2) : n >= 1 ? n.toFixed(3) : n.toFixed(6));const pStr = price != null ? `$${fmt(price)}` : '?';@@ -186,7 +210,10 @@ export default paidEndpoint({const coinId = ALIASES[topic] || topic;let live = null;- try { live = await fetchLivePrice(coinId); } catch { /* offline fallback */ }+ try { live = await fetchLivePrice(coinId); } catch { /* try fallback source */ }+ if (!live || live.change_24h == null) {+ try { live = await fetchBinance24h(topic, coinId); } catch { /* refund below */ }+ }if (!live || live.change_24h == null) {// Paid endpoint — never charge for a fabricated signal. Throw so thediff --git a/prompts/agent-playwright-stream.md b/prompts/agent-playwright-stream.mddeleted file mode 100644index 3e0182598..000000000--- a/prompts/agent-playwright-stream.md+++ /dev/null@@ -1,153 +0,0 @@-# Agent Playwright Screen Streaming Service--## Context--three.ws has a live agent watch system built and deployed:--- `api/agent/screen-stream.js` — SSE endpoint, streams frames + activity to any client watching-- `api/agent/screen-push.js` — POST endpoint that accepts base64 PNG frames from external agent processes-- `src/shared/agent-watch-panel.js` — 2D panel (screen + avatar webcam) shown on every agent profile-- `src/game/agent-desk.js` — 3D desk with live CanvasTexture monitor in the /play world-- `/dashboard-next/watch?agentId=<id>` — standalone full-page watch view--The SSE stream already delivers real agent-action records as the "screen" when no frames are being pushed. This prompt is about building the **Playwright process** that pushes real browser screenshots.--## What to build--A Node.js service (`services/agent-screen-caster/`) that:--1. **Accepts an agent config** (agentId, owner bearer token, tasks to run)-2. **Spins up a Playwright Chromium browser** (headless by default, non-headless for dev)-3. **Captures screenshots** every 300–500ms OR on every `page.on('load')` / `page.on('requestfinished')` event (whichever is more event-driven)-4. **Compresses each screenshot** to JPEG at 75% quality then base64-encodes it-5. **POSTs each frame** to `https://three.ws/api/agent/screen-push` with the agent's bearer token-6. **Also POSTs structured activity** (`/api/agent/screen-push` with `actions` array) whenever the agent takes a meaningful action (navigation, click, form submit, trade)--## File structure--```-services/agent-screen-caster/- index.js — CLI entrypoint, reads .env + argv- caster.js — AgentScreenCaster class (Playwright + push loop)- tasks/- pump-monitor.js — example task: watch a pump.fun coin page- trade.js — example task: Solana trade UI automation- package.json- .env.example-```--## Technical spec--### `caster.js` — AgentScreenCaster--```js-class AgentScreenCaster {- constructor({ agentId, bearerToken, pushUrl, frameIntervalMs, jpegQuality })- async launch(headless = true) // start Playwright- async navigate(url) // go to a URL, auto-push frame- async act(description, fn) // named action wrapper — pushes activity + frame- startFrameLoop() // setInterval for continuous frame push- stopFrameLoop()- async pushFrame() // capture → compress → POST- async pushActivity(actions) // POST to /api/agent/screen-push with actions array- async close() // tear down Playwright-}-```--### Frame push format (already defined in the API)--```http-POST /api/agent/screen-push-Authorization: Bearer <agentBearerToken>-Content-Type: application/json--{ "agentId": "...", "frame": "<base64 JPEG>", "seq": 1234567890 }-```--### Activity push format--```http-POST /api/agent/screen-push-Authorization: Bearer <agentBearerToken>-Content-Type: application/json--{- "agentId": "...",- "actions": [- { "type": "navigate", "summary": "Navigating to pump.fun", "ts": 1234567890 },- { "type": "trade", "summary": "Buying 0.1 SOL of $COIN", "ts": 1234567890 }- ]-}-```--### Auth: how to get the bearer token--The agent's bearer token lives in the calling agent process's environment. It's the same token used by the agent's wallet bridge. Check `api/_lib/auth.js` `authenticateBearer()` — it validates a JWT signed with `JWT_SECRET`. Generate one for an agent owner session.--Alternatively, a new API key system under `api/api-keys.js` already issues bearer tokens — use those.--## Example task: pump.fun coin monitor--```js-// tasks/pump-monitor.js-export async function runPumpMonitor(caster, mint) {- await caster.navigate(`https://pump.fun/coin/${mint}`);-- // Watch for price changes via DOM observation- await caster.page.exposeFunction('onPriceChange', async (price) => {- await caster.act('price_update', async () => {- await caster.pushActivity([{- type: 'price_update',- summary: `$${price} — monitoring ${mint.slice(0,8)}…`,- ts: Date.now(),- }]);- });- });-- await caster.page.evaluate(() => {- const el = document.querySelector('[data-price]');- if (!el) return;- const obs = new MutationObserver(() => window.onPriceChange(el.textContent));- obs.observe(el, { childList: true, subtree: true, characterData: true });- });-- // Keep the session alive- await new Promise(() => {});-}-```--## `.env.example`--```-AGENT_ID=<uuid>-AGENT_BEARER_TOKEN=<jwt>-PUSH_URL=https://three.ws/api/agent/screen-push-FRAME_INTERVAL_MS=400-JPEG_QUALITY=72-HEADLESS=true-TASK=pump-monitor-TASK_ARG=FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump-```--## Notes--- This service should be a **long-running Node.js process** (not a Vercel function)-- Deploy to a Cloud Run container or a Cloudflare Worker with Durable Objects for persistence-- Playwright's `chromium.launch()` works in Docker — use `mcr.microsoft.com/playwright:v1.x-jammy` as base-- Each Playwright session = one browser context = one agent's "screen"-- Multiple agents can run in the same Node process using separate `AgentScreenCaster` instances-- Frame size: a 1280×720 JPEG at quality 72 is approximately 40–80 KB, well within the 1 MB API limit-- The receiving SSE clients (2D panel, 3D desk) handle 400ms frames gracefully — no need to go faster-- Existing infrastructure: `workers/` contains Cloudflare workers — the screen-caster could also live there as a Durable Object if you want zero-infra hosting--## Where the frames go after pushing--```-AgentScreenCaster.pushFrame()- → POST /api/agent/screen-push- → cacheSet('screen:frame:<agentId>', { frame, seq, ts }, 10s TTL)- → api/agent/screen-stream.js polls every 250ms- → SSE event: { type: 'frame', frame, seq, ts }- → src/shared/agent-watch-panel.js renders frame to canvas- → src/game/agent-desk.js renders frame to THREE.CanvasTexture on monitor mesh-```diff --git a/prompts/agent-screen-unify.md b/prompts/agent-screen-unify.mddeleted file mode 100644index 3a8e46dd4..000000000--- a/prompts/agent-screen-unify.md+++ /dev/null@@ -1,85 +0,0 @@-# Unify the Agent-Screen Pipeline — make the 3D desk monitor show the REAL browser feed--> Self-contained task. Paste into a fresh chat and execute end-to-end. Read `CLAUDE.md`-> and `STRUCTURE.md` first — CLAUDE.md overrides defaults.--## The bug (verified)--There are **two parallel, incompatible agent-screen systems** in this repo. The live-headless-browser worker pushes to one; the 3D world desk monitor reads from the other.-They share no endpoint, no Redis key, and no message format, so **frames captured by the-real worker never reach the 3D monitor.** The monitor only ever shows a hand-drawn canvas-fallback (`paintDesk()` → `/api/agent-actions` rows, or "Waiting for agent activity…").--| | **System A** | **System B** |-|---|---|---|-| Stream endpoint | `api/agent/screen-stream.js` (`/api/agent/screen-stream`) | `api/agent-screen-stream.js` (`/api/agent-screen-stream`) |-| Push endpoint | `api/agent/screen-push.js` (`/api/agent/screen-push`) | `api/agent-screen-push.js` (`/api/agent-screen-push`) |-| Storage | `cacheGet('screen:frame:{id}')` | Redis `agent:screen:{id}:frame` (TTL 90s) |-| SSE shape | unnamed `data:` events, `{type:'frame', frame:<base64>, seq, ts}` | **named** events `event: frame` + `{ts, data, activity, type}` |-| Consumers | `src/game/agent-desk.js`, `src/agents-live.js` | `src/agent-screen.js` (2D page), `src/walk-agent-desk.js`, `src/shared/agent-screen-client.js` |-| **Worker pushes here?** | ❌ no | ✅ yes — `workers/agent-screen-worker/config.js:17` (`PUSH_URL` default `/api/agent-screen-push`) |--History: `prompts/agent-playwright-stream.md` built System A; `prompts/agent-screen-browser-worker.md`-built System B. Both claim the desk monitor renders their feed. Only B is fed by a running worker.--## Goal--**One** agent-screen pipeline. The frame a worker pushes must appear, verbatim, on ALL of:-- `/agent-screen?agentId=<uuid>` (2D page)-- the agent profile watch panel-- the 3D world desk monitor in `/play` (the coin-community plaza)--When no worker is pushing, every surface shows the same honest "waiting / live activity"-fallback — no fake browser chrome implying a stream that isn't there.--## What to do--1. **Pick System B as the canonical pipeline** (it's what the shipped worker, the 2D page,- and `walk-agent-desk.js` already use, and it has proper Redis TTL + rate limiting). Do NOT- keep both. Converging on A would orphan the deployed worker.--2. **Rewrite `src/game/agent-desk.js` to consume System B.** Today it uses- `FRAME_SSE_URL = /api/agent/screen-stream` + `es.onmessage` + `msg.type==='frame'` + `msg.frame`- (agent-desk.js:39-40, 316-333). Replace that hand-rolled `EventSource` with the shared client- `src/shared/agent-screen-client.js` (`createAgentScreenClient`) exactly as `src/walk-agent-desk.js`- already does — it handles named `frame`/`log`/`dark`/`ping` events, reconnect/backoff, and gives- you `frame.data` (a ready-to-use `data:image/...;base64,` URL → assign straight to `img.src`, no- prefix surgery). Keep the existing `paintDesk()` canvas as the *fallback only* (no frames / dark).--3. **Delete System A** once nothing references it: `api/agent/screen-stream.js`,- `api/agent/screen-push.js`, and `api/agent/caster-config.js` (confirm with- `grep -rn "agent/screen-stream\|agent/screen-push\|screen:frame:\|caster-config" src/ api/ workers/`).- Update `src/agents-live.js` to System B too. If `prompts/agent-playwright-stream.md` is the only- thing still describing System A, update it to point at the unified pipeline (or delete it — it's- superseded by `agent-screen-browser-worker.md`).--4. **Reconcile the activity fallback.** System A's stream merged `/api/agent_actions` DB rows into the- SSE as `activity`. System B's `agent-screen-stream.js` already emits `log` entries. Make the desk's- fallback read the same source the 2D page uses so all surfaces agree. No new endpoint unless one is- genuinely missing — reuse what exists.--5. **Verify end-to-end with a real worker (no mocks).** Start the worker against a real agent you own:- `cd workers/agent-screen-worker && npm install && AGENT_ID=<uuid> AGENT_JWT=<key> npm start`- (mint the key at `/agent-screen` with no `agentId`). Then confirm the SAME frames appear on the 2D- page AND the 3D desk monitor in `/play`. Screenshot both. Stop the worker → both must fall back to- the waiting state within the TTL, not freeze a stale frame.--## Acceptance criteria--- [ ] Exactly one screen pipeline remains; System A files deleted; no dead `grep` hits.-- [ ] `src/game/agent-desk.js` uses `createAgentScreenClient` (System B), not a hand-rolled EventSource.-- [ ] A running worker's frames render identically on the 2D page and the 3D desk monitor.-- [ ] No worker → identical honest fallback on every surface (no fake browser window).-- [ ] No console errors/warnings from changed code; `npm test` passes; build has no esbuild-bundled `api/*.js`.-- [ ] `data/changelog.json` entry (tag `fix`) + `npm run build:pages`.--## Operating rules (non-negotiable)--- No mocks / fake data / placeholders / TODOs / stubs. Real worker, real frames, real verification.-- `$THREE` is the only coin (CA `FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump`). Reference no other token anywhere.-- Concurrent agents share this worktree — stage explicit paths (never `git add -A`); re-check- `git status` / `git diff --staged` before committing.-- esbuild trap: never commit `api/*.js` starting with `__defProp`/`createRequire`; recover with- `git restore -- api/ public/`.-- Definition of done = CLAUDE.md's checklist. `git diff` reviewed line-by-line before claiming complete.diff --git a/services/agent-screen-caster/caster.js b/services/agent-screen-caster/caster.jsindex f19b7616f..35654223f 100644--- a/services/agent-screen-caster/caster.js+++ b/services/agent-screen-caster/caster.js@@ -17,7 +17,7 @@import { chromium } from 'playwright';-const DEFAULT_PUSH_URL = 'https://three.ws/api/agent/screen-push';+const DEFAULT_PUSH_URL = 'https://three.ws/api/agent-screen-push';const DEFAULT_FRAME_INTERVAL = 400; // ms between periodic capturesconst DEFAULT_JPEG_QUALITY = 72;const DEFAULT_VIEWPORT = { width: 1280, height: 720 };@@ -26,7 +26,7 @@ export class AgentScreenCaster {/*** @param {object} opts* @param {string} opts.agentId UUID of the agent identity- * @param {string} opts.bearerToken JWT or API key for /api/agent/screen-push+ * @param {string} opts.bearerToken JWT or API key for /api/agent-screen-push* @param {string} [opts.pushUrl] Override the push endpoint* @param {number} [opts.frameIntervalMs] Milliseconds between frame captures* @param {number} [opts.jpegQuality] JPEG quality 1-100@@ -45,7 +45,6 @@ export class AgentScreenCaster {this.context = null;this.page = null;this._timer = null;- this._seq = 0;this._pushing = false; // guard against overlapping push calls}@@ -128,7 +127,7 @@ export class AgentScreenCaster {// ── Push primitives ────────────────────────────────────────────────────────/**- * Capture the current page as JPEG, base64-encode, and POST to screen-push.+ * Capture the current page as JPEG and POST it to screen-push as a data URL.*/async pushFrame() {if (!this.page) return;@@ -139,19 +138,27 @@ export class AgentScreenCaster {fullPage: false,});- const frame = buf.toString('base64');- const seq = ++this._seq;-- await this._post({ agentId: this.agentId, frame, seq });+ await this._post({+ agentId: this.agentId,+ frame: { data: `data:image/jpeg;base64,${buf.toString('base64')}`, type: 'screenshot' },+ });}/**- * POST structured activity records to screen-push.+ * POST structured activity records to screen-push. Each record becomes a+ * text-only frame carrying the summary — the API appends it to the agent's+ * activity log (types outside trade/analysis are coerced to 'activity').** @param {Array<{ type: string, summary: string, payload?: any, ts?: number }>} actions*/async pushActivity(actions) {- await this._post({ agentId: this.agentId, actions });+ for (const a of actions || []) {+ if (!a?.summary) continue;+ await this._post({+ agentId: this.agentId,+ frame: { activity: String(a.summary), type: a.type },+ });+ }}// ── Internals ──────────────────────────────────────────────────────────────diff --git a/services/agent-screen-caster/index.js b/services/agent-screen-caster/index.jsindex 72e8a6cdd..01d0f0b85 100644--- a/services/agent-screen-caster/index.js+++ b/services/agent-screen-caster/index.js@@ -16,7 +16,7 @@* Env vars (see .env.example for full list):* AGENT_ID UUID of the agent identity (required)* AGENT_BEARER_TOKEN JWT or API key (required)- * PUSH_URL Override push endpoint (default: https://three.ws/api/agent/screen-push)+ * PUSH_URL Override push endpoint (default: https://three.ws/api/agent-screen-push)* FRAME_INTERVAL_MS Milliseconds between frame captures (default: 400)* JPEG_QUALITY JPEG quality 1-100 (default: 72)* HEADLESS "true" (default) | "false" for visible browser window@@ -44,7 +44,7 @@ if (envFlagIdx !== -1) {// ── Read config ────────────────────────────────────────────────────────────────const agentId = required('AGENT_ID');const bearerToken = required('AGENT_BEARER_TOKEN');-const pushUrl = process.env.PUSH_URL || 'https://three.ws/api/agent/screen-push';+const pushUrl = process.env.PUSH_URL || 'https://three.ws/api/agent-screen-push';const frameMs = Number(process.env.FRAME_INTERVAL_MS || 400);const jpegQuality = Number(process.env.JPEG_QUALITY || 72);const headless = process.env.HEADLESS !== 'false';diff --git a/src/game/agent-desk.js b/src/game/agent-desk.jsindex c6244e377..73d29032e 100644--- a/src/game/agent-desk.js+++ b/src/game/agent-desk.js@@ -33,11 +33,10 @@ import {PlaneGeometry, BoxGeometry, CylinderGeometry,CanvasTexture, SRGBColorSpace, DoubleSide, Vector3,} from 'three';+import { createAgentScreenClient } from '../shared/agent-screen-client.js';const ACTIVITY_URL = (id) =>`/api/agent-actions?agent_id=${encodeURIComponent(id)}&limit=12`;-const FRAME_SSE_URL = (id) =>- `/api/agent/screen-stream?agentId=${encodeURIComponent(id)}`;const NEAR_DIST = 8; // units — player proximity to activateconst POLL_MS = 4000; // activity poll interval (far)@@ -308,29 +307,33 @@ export function createAgentDesk(scene, agent, opts = {}) {let pollTimer = null;let acc = 0;let t = 0;- let es = null;// Initial paint so the screen isn't blank before the first fetch.paintDesk(ctx, tex, [], 'idle', agent.agentName || 'Agent', 0);- function connectSSE() {- if (es) { try { es.close(); } catch { /* */ } }- es = new EventSource(FRAME_SSE_URL(agent.agentId));- es.onmessage = (e) => {- let msg;- try { msg = JSON.parse(e.data); } catch { return; }- if (msg.type === 'frame') {+ // Same stream the 2D watch panel and the live wall use. Frames arrive as+ // `event: frame` with `data` holding a full data URL (or null for text-only+ // beats); `event: log` backfills activity oldest-first; `event: dark` fires+ // when the caster's frame TTL lapses. Reconnect/backoff lives in the client.+ const screenClient = createAgentScreenClient(agent.agentId, {+ onFrame(frame) {+ status = 'live';+ if (typeof frame?.data === 'string' && frame.data.startsWith('data:image/')) {const img = new Image();img.onload = () => { frameImg = img; };- img.src = 'data:image/png;base64,' + msg.frame;- status = 'live';+ img.src = frame.data;}- if (msg.type === 'activity') {- actions = msg.actions || [];- }- };- es.onerror = () => { status = 'idle'; };- }+ },+ onLog(entries) {+ if (!entries?.length) return;+ // paintDesk expects newest-first rows shaped like agent-actions.+ actions = entries+ .map((e) => ({ ts: e.ts, summary: e.activity, type: e.type }))+ .reverse();+ },+ onDark() { status = 'idle'; frameImg = null; },+ onError() { status = 'idle'; },+ });async function fetchActivity() {if (destroyed) return;@@ -365,7 +368,7 @@ export function createAgentDesk(scene, agent, opts = {}) {} catch { /* */ }}- connectSSE();+ screenClient.connect();fetchActivity();// ── public API ────────────────────────────────────────────────────────────@@ -415,7 +418,7 @@ export function createAgentDesk(scene, agent, opts = {}) {dispose() {destroyed = true;clearTimeout(pollTimer);- try { es?.close(); } catch { /* */ }+ screenClient.disconnect();scene.remove(group);group.traverse((n) => {if (!n.isMesh) return;diff --git a/src/game/coincommunities.js b/src/game/coincommunities.jsindex 0aa271852..2f3825ffb 100644--- a/src/game/coincommunities.js+++ b/src/game/coincommunities.js@@ -45,7 +45,7 @@ import { CosmeticsShop } from './cosmetics-shop.js';import { CosmeticsWardrobe } from './cosmetics-wardrobe.js';import { HOME_TOWN, isHomeTown } from './home-town.js';import { AgentCommerce } from './agent-commerce.js';-import { ThreeIntelKiosk } from './three-intel-kiosk.js';+import { IntelKiosk } from './intel-kiosk.js';import { WorldLife } from './npc/world-life.js';import { isChatPanelOpen } from './npc/npc-chat.js';import { isServicePanelOpen } from './npc/npc-services.js';@@ -1005,26 +1005,26 @@ export class CoinCommunities {this.phase = 'world';this._initJoystick();this._onboardBuild();- // The flagship town hosts the live Agent Exchange: two NPC agents who pay- // each other on-chain via x402. Built only here, torn down in leave().- if (isHomeTown(coin.mint)) {- this.agentCommerce = new AgentCommerce({- scene: this.scene,- camera: this.camera,- renderer: this.renderer,- getPlayer: () => this.localPos,- ui: this.ui,- });- // …and the $THREE Intel Kiosk: the player pays a real x402 endpoint- // ($0.01 USDC) from their own wallet for live $THREE market intel.- this.intelKiosk = new ThreeIntelKiosk({- scene: this.scene,- camera: this.camera,- renderer: this.renderer,- getPlayer: () => this.localPos,- ui: this.ui,- });- }+ // Every town hosts the live Agent Exchange: two NPC agents who pay each+ // other on-chain via x402. Torn down in leave().+ this.agentCommerce = new AgentCommerce({+ scene: this.scene,+ camera: this.camera,+ renderer: this.renderer,+ getPlayer: () => this.localPos,+ ui: this.ui,+ });+ // …and the Intel Kiosk: the player pays a real x402 endpoint ($0.01 USDC)+ // from their own wallet for live market intel on the town's own coin —+ // the flagship $THREE oracle at home, the generic token oracle elsewhere.+ this.intelKiosk = new IntelKiosk({+ scene: this.scene,+ camera: this.camera,+ renderer: this.renderer,+ getPlayer: () => this.localPos,+ ui: this.ui,+ coin,+ });// Agent desks — visible in every world. Fetches the world's top registered// agents from /api/agents and seats them at working desks with live// CanvasTexture monitors streaming their real activity. Players can walk up@@ -1053,8 +1053,9 @@ export class CoinCommunities {// Living world (W08): ambient pedestrians + traffic, interactive vendor /// quest / flavor NPCs, and (gated behind W07) hostile mobs — all on a// deterministic nav graph so every client sees the same crowd without- // syncing it. Built for every world; the Agent Exchange above stays the- // home town's special NPC. Torn down in leave().+ // syncing it. Built for every world, same as the Agent Exchange and the+ // Intel Kiosk above. Torn down in leave(). name/symbol ride along so the+ // NPC chat can speak about the town it's actually standing in.this.worldLife = new WorldLife({scene: this.scene,camera: this.camera,@@ -1062,7 +1063,13 @@ export class CoinCommunities {getPlayer: () => this.localPos,ui: this.ui,net: this.net,- world: { mint: coin.mint, seed: seedFromString(coin.mint) >>> 0, biome: this.env?.biome },+ world: {+ mint: coin.mint,+ name: coin.name,+ symbol: coin.symbol,+ seed: seedFromString(coin.mint) >>> 0,+ biome: this.env?.biome,+ },radius: WORLD_RADIUS - 4,});// Start the silent pass-refresh cycle. The play pass has a 10-min serverdiff --git a/src/game/three-intel-kiosk.js b/src/game/intel-kiosk.jssimilarity index 80%rename from src/game/three-intel-kiosk.jsrename to src/game/intel-kiosk.jsindex ef2eb1dac..311a4b7be 100644--- a/src/game/three-intel-kiosk.js+++ b/src/game/intel-kiosk.js@@ -1,30 +1,33 @@-// $THREE Intel Kiosk — a paid x402 oracle kiosk inside the $THREE town (/play).+// Intel Kiosk — a paid x402 oracle kiosk inside every coin town (/play).//// This ports the /play/agent-wallet demo into the walkaround world: instead of// a flat page where your avatar walks to a kiosk, YOU are the avatar. Walk up// to the kiosk by the plaza and press E (or tap it) — window.X402.pay opens// the wallet modal, you pay $0.01 USDC (Phantom on Solana, or an EVM wallet on-// Base) to /api/x402/three-intel, and the kiosk's 3D screen lights up with the-// purchased intel: live $THREE price, 24 h change, market cap, and a-// bullish/bearish/neutral signal. Every settlement is real USDC on-chain; the-// payment modal shows the transaction with an explorer link.+// Base) and the kiosk's 3D screen lights up with the purchased intel: live+// price, 24 h change, market cap, and a bullish/bearish/neutral signal for the+// town's own coin. Every settlement is real USDC on-chain; the payment modal+// shows the transaction with an explorer link.//-// Scoped to the home town only (built by coincommunities.js inside its-// isHomeTown block) and torn down in leave(). Payment only fires on an-// explicit player interaction, and the player signs with their OWN wallet —-// no platform key is ever exposed to the page.+// Built for every world by coincommunities.js and torn down in leave(). The+// flagship $THREE town buys from its dedicated oracle (/api/x402/three-intel);+// every other town buys from the generic token oracle+// (/api/x402/token-intel?mint=…) with the world's mint supplied at runtime —+// the same coin-agnostic plumbing the /ca2x402 resolver hands out. Payment+// only fires on an explicit player interaction, and the player signs with+// their OWN wallet — no platform key is ever exposed to the page.import {Group, Mesh, MeshBasicMaterial, MeshStandardMaterial, RingGeometry,PlaneGeometry, BoxGeometry, CylinderGeometry, CanvasTexture, SRGBColorSpace,DoubleSide, Vector3,} from 'three';+import { isHomeTown } from './home-town.js';import { log } from '../shared/log.js';import { ensureX402 } from '../shared/x402-loader.js';const KIOSK_POS = new Vector3(-8, 0, -7);const INTERACT_RANGE = 5.5;-const ENDPOINT = '/api/x402/three-intel';const ACCENT = '#9945ff';const ACCENT_LT = '#b88aff';@@ -38,14 +41,35 @@ function fmtUsd(n) {return `$${n >= 1 ? n.toFixed(2) : n.toFixed(6)}`;}-export class ThreeIntelKiosk {- constructor({ scene, camera, renderer, getPlayer, ui }) {+// Shrink a font until the text fits — long pump.fun tickers must not bleed off+// the 512px sign/screen canvases.+function fitFont(ctx, text, maxWidth, basePx, weight = 800) {+ let px = basePx;+ do {+ ctx.font = `${weight} ${px}px Inter, system-ui, sans-serif`;+ if (ctx.measureText(text).width <= maxWidth) break;+ px -= 2;+ } while (px > 18);+ return px;+}++export class IntelKiosk {+ constructor({ scene, camera, renderer, getPlayer, ui, coin }) {this.scene = scene;this.camera = camera;this.renderer = renderer;this.getPlayer = getPlayer;this.ui = ui;+ // The town's coin decides what the kiosk sells and where it buys from.+ const home = isHomeTown(coin?.mint);+ this.symLabel = home+ ? '$THREE'+ : (coin?.symbol ? '$' + String(coin.symbol).toUpperCase() : (coin?.name || 'TOKEN'));+ this.endpoint = home+ ? '/api/x402/three-intel'+ : `/api/x402/token-intel?mint=${encodeURIComponent(coin?.mint || '')}`;+this.busy = false;this.intel = null; // last purchased intel payloadthis.paidTx = null; // settlement tx of the last purchase@@ -109,7 +133,7 @@ export class ThreeIntelKiosk {this.group.add(this.ring);// Floating sign, billboarded in tick().- this.sign = this._signMesh('$THREE INTEL', 'paid oracle · $0.01 USDC · x402');+ this.sign = this._signMesh(`${this.symLabel} INTEL`, 'paid oracle · $0.01 USDC · x402');this.sign.position.set(0, 3.5, 0);this.group.add(this.sign);@@ -121,7 +145,7 @@ export class ThreeIntelKiosk {const x = c.getContext('2d');x.textAlign = 'center';x.fillStyle = ACCENT_LT;- x.font = '800 54px Inter, system-ui, sans-serif';+ fitFont(x, title, 480, 54);x.fillText(title, 256, 62);x.fillStyle = 'rgba(255,255,255,0.62)';x.font = '600 26px Inter, system-ui, sans-serif';@@ -155,7 +179,10 @@ export class ThreeIntelKiosk {}this.prompt = document.createElement('div');this.prompt.className = 'tik-prompt';- this.prompt.innerHTML = '<span class="tik-key">E</span> Buy $THREE intel — $0.01 USDC';+ const key = document.createElement('span');+ key.className = 'tik-key';+ key.textContent = 'E';+ this.prompt.append(key, ` Buy ${this.symLabel} intel — $0.01 USDC`);document.body.appendChild(this.prompt);}@@ -171,8 +198,9 @@ export class ThreeIntelKiosk {c.fillStyle = '#5a5a60';c.font = '700 22px Inter, system-ui, sans-serif';c.fillText('x402 PAID ORACLE', 28, 46);- c.fillStyle = ACCENT_LT; c.font = '800 44px Inter, system-ui, sans-serif';- c.fillText('$THREE INTEL', 28, 100);+ c.fillStyle = ACCENT_LT;+ fitFont(c, `${this.symLabel} INTEL`, W - 56, 44);+ c.fillText(`${this.symLabel} INTEL`, 28, 100);const i = this.intel;if (this.busy) {@@ -253,7 +281,7 @@ export class ThreeIntelKiosk {// Player pressed E (or tapped the kiosk): open the real x402 payment modal.interact() {if (this.busy || !this._playerNear()) return false;- this._purchase().catch((err) => log.warn('[three-intel-kiosk] purchase failed:', err?.message));+ this._purchase().catch((err) => log.warn('[intel-kiosk] purchase failed:', err?.message));return true;}@@ -264,16 +292,16 @@ export class ThreeIntelKiosk {try {const X402 = await ensureX402();const out = await X402.pay({- endpoint: ENDPOINT,+ endpoint: this.endpoint,method: 'GET',- merchant: '$THREE Town Oracle',- action: 'Live $THREE market intel — $0.01 USDC',+ merchant: `${this.symLabel} Town Oracle`,+ action: `Live ${this.symLabel} market intel — $0.01 USDC`,});const intel = out?.result;if (!intel?.signal) throw new Error(intel?.error || 'purchase did not settle');this.intel = intel;this.paidTx = out?.payment?.transaction || null;- this.ui?.toast?.(`$THREE intel purchased — ${intel.signal.toUpperCase()}: ${intel.headline}`, 'success');+ this.ui?.toast?.(`${this.symLabel} intel purchased — ${intel.signal.toUpperCase()}: ${intel.headline}`, 'success');} catch (err) {// A dismissed wallet modal is a normal exit, not an error state.const cancelled = /cancel|dismiss|closed|denied/i.test(String(err?.message || ''));diff --git a/src/shared/avatar-inspector.js b/src/shared/avatar-inspector.jsnew file mode 100644index 000000000..e1b85fcd7--- /dev/null+++ b/src/shared/avatar-inspector.js@@ -0,0 +1,532 @@+/**+ * Avatar Inspector — one panel, every world.+ *+ * Press I (or select an avatar) in any three.ws world — /play, /city, a coin+ * world, the walk playground — and this side panel opens on whoever you're+ * looking at: who they are, the reputation they've earned, the wallet they+ * carry, and every public fact the platform knows about them. It is the+ * world-side twin of the Agora passport: non-modal, keyboard-first, honest.+ *+ * Everything shown is real, server-authoritative data — the same public+ * endpoints every other surface reads, so a number never disagrees across+ * the platform:+ * - GET /api/agents/:id → identity (name, bio, skills, links)+ * - GET /api/agents/:id/reputation → 0–100 trust score + pillars+ * (rendered by the shared reputationPanelEl, the exact breakdown the+ * wallet hub shows)+ * - GET /api/agents/:id/solana/networth → wallet address, USD/SOL/$THREE+ * portfolio, top holdings, wealth tier+ * - POST /api/wallet/balances → balances for a bare verified+ * wallet when the avatar isn't piloting a registered agent+ *+ * A guest with no wallet renders as exactly that — a designed empty state+ * that says what's missing and how to get it — never a fabricated number.+ *+ * Usage (each world supplies its own picking — raycast, nameplate click, or+ * the I key on the nearest avatar):+ * import { openAvatarInspector } from '../shared/avatar-inspector.js';+ * openAvatarInspector({+ * kind: 'peer', // 'peer'|'self'|'npc'|'ambient'+ * name: 'nick',+ * world: 'play', // chip: which world surfaced it+ * agentId: 'uuid-or-empty', // three.ws agent this avatar pilots+ * wallet: 'solana-address-or-empty', // verified account wallet+ * facts: [{ label: 'Profession', value: 'Builder' }],+ * }, { trigger: buttonEl }); // focus returns here on close+ */++import { apiFetch } from '../api.js';+import { reputationPanelEl, ensureReputationStyles } from './agent-reputation.js';+import { shortAddress, formatWalletUsd } from './wallet-format.js';+import { log } from './log.js';++const STYLE_ID = 'tws-avatar-inspector-styles';+const UUID_RE = /^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i;+const SOL_ADDR_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;++const KIND_LABEL = {+ self: 'You',+ peer: 'Player',+ npc: 'Townsperson',+ ambient: 'Local',+ agent: 'Agent',+ citizen: 'Citizen',+};++const esc = (s) =>+ String(s ?? '').replace(/[&<>"']/g, (c) => ({ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' }[c]));++const fmtAmount = (n) => {+ const v = Number(n) || 0;+ if (v === 0) return '0';+ if (v >= 1e9) return (v / 1e9).toFixed(2) + 'B';+ if (v >= 1e6) return (v / 1e6).toFixed(2) + 'M';+ if (v >= 1e3) return (v / 1e3).toFixed(1) + 'K';+ if (v < 0.001) return v.toExponential(1);+ return v.toLocaleString('en-US', { maximumFractionDigits: v < 1 ? 4 : 2 });+};++const explorerAddr = (a) => `https://explorer.solana.com/address/${encodeURIComponent(a)}`;++// ── singleton state ──────────────────────────────────────────────────────────++let _panel = null; // { root, subjectKey, trigger, onClose, keyHandler }++export function isAvatarInspectorOpen() {+ return !!_panel;+}++export function closeAvatarInspector() {+ if (!_panel) return;+ const { root, trigger, onClose, keyHandler } = _panel;+ _panel = null;+ window.removeEventListener('keydown', keyHandler, true);+ root.classList.remove('avi-in');+ const remove = () => root.remove();+ // Let the exit transition play unless the user prefers reduced motion.+ if (window.matchMedia?.('(prefers-reduced-motion: reduce)')?.matches) remove();+ else setTimeout(remove, 220);+ try { onClose?.(); } catch (e) { log.warn('[avatar-inspector] onClose threw', e); }+ if (trigger && document.contains(trigger)) {+ try { trigger.focus({ preventScroll: true }); } catch { /* focus target gone */ }+ }+}++/**+ * Open (or toggle) the inspector for a subject.+ *+ * @param {object} subject+ * @param {string} [subject.kind] 'peer'|'self'|'npc'|'ambient'|'agent'|'citizen'+ * @param {string} [subject.name] display name+ * @param {string} [subject.world] world chip ('play', 'city', …)+ * @param {string} [subject.agentId] three.ws agent UUID this avatar pilots+ * @param {string} [subject.wallet] verified Solana address (used when no agentId)+ * @param {string} [subject.avatarUrl] GLB url (shown as a fact, not rendered)+ * @param {Array} [subject.facts] [{label, value, href?}] world-specific rows+ * @param {object} [opts]+ * @param {Element} [opts.trigger] element to restore focus to on close+ * @param {Function}[opts.onClose]+ */+export function openAvatarInspector(subject = {}, opts = {}) {+ ensureStyles();+ ensureReputationStyles();++ const agentId = UUID_RE.test(String(subject.agentId || '')) ? String(subject.agentId) : '';+ const wallet = SOL_ADDR_RE.test(String(subject.wallet || '')) ? String(subject.wallet) : '';+ const subjectKey = `${subject.kind || ''}:${subject.name || ''}:${agentId}:${wallet}`;++ // Same avatar again (the I key, a second click) → toggle closed.+ if (_panel && _panel.subjectKey === subjectKey) {+ closeAvatarInspector();+ return null;+ }+ if (_panel) closeAvatarInspector();++ const kind = KIND_LABEL[subject.kind] ? subject.kind : 'peer';+ const name = String(subject.name || '').trim() || (kind === 'self' ? 'You' : 'guest');++ const root = document.createElement('aside');+ root.className = 'avi-root';+ root.setAttribute('role', 'dialog');+ root.setAttribute('aria-label', `Avatar inspector — ${name}`);+ root.innerHTML = `+ <header class="avi-head">+ <div class="avi-monogram" aria-hidden="true">${esc(name.replace(/^@/, '').slice(0, 2).toUpperCase())}</div>+ <div class="avi-id">+ <h2 class="avi-name">${esc(name)}</h2>+ <div class="avi-chips">+ <span class="avi-chip avi-chip-kind">${esc(KIND_LABEL[kind])}</span>+ ${subject.world ? `<span class="avi-chip">${esc(subject.world)}</span>` : ''}+ </div>+ </div>+ <button type="button" class="avi-close" aria-label="Close inspector">✕</button>+ </header>+ <div class="avi-body">+ <section class="avi-section" data-avi="wallet">+ <h3 class="avi-h">Wallet</h3>+ <div class="avi-section-body"></div>+ </section>+ <section class="avi-section" data-avi="reputation">+ <h3 class="avi-h">Reputation</h3>+ <div class="avi-section-body"></div>+ </section>+ <section class="avi-section" data-avi="about">+ <h3 class="avi-h">Details</h3>+ <div class="avi-section-body"></div>+ </section>+ </div>+ <footer class="avi-foot"></footer>+ `;++ const keyHandler = (e) => {+ if (e.key === 'Escape') {+ e.stopPropagation();+ closeAvatarInspector();+ }+ };++ root.querySelector('.avi-close').addEventListener('click', closeAvatarInspector);+ window.addEventListener('keydown', keyHandler, true);+ document.body.appendChild(root);+ // Double-rAF so the entering transform actually transitions from offscreen.+ requestAnimationFrame(() => requestAnimationFrame(() => root.classList.add('avi-in')));++ _panel = { root, subjectKey, trigger: opts.trigger || null, onClose: opts.onClose || null, keyHandler };++ root.querySelector('.avi-close').focus({ preventScroll: true });++ renderAbout(root, subject, { agentId });+ renderWallet(root, { agentId, wallet, kind });+ renderReputation(root, { agentId, kind });+ renderFooter(root, { agentId, wallet });++ return { close: closeAvatarInspector };+}++// ── sections ─────────────────────────────────────────────────────────────────++function sectionBody(root, key) {+ return root.querySelector(`[data-avi="${key}"] .avi-section-body`);+}++const skeleton = (rows = 2) =>+ Array.from({ length: rows }, (_, i) => `<div class="avi-sk" style="width:${88 - i * 18}%"></div>`).join('');++function emptyState(title, body, links = []) {+ return (+ `<div class="avi-empty">` ++ `<div class="avi-empty-title">${esc(title)}</div>` ++ `<p>${esc(body)}</p>` ++ (links.length+ ? `<div class="avi-links">${links+ .map((l) => `<a href="${esc(l.href)}"${/^https?:/.test(l.href) ? ' target="_blank" rel="noopener noreferrer"' : ''}>${esc(l.label)} →</a>`)+ .join('')}</div>`+ : '') ++ `</div>`+ );+}++function errorState(message, retry) {+ const el = document.createElement('div');+ el.className = 'avi-error';+ el.setAttribute('role', 'alert');+ el.innerHTML = `<p>${esc(message)}</p><button type="button" class="avi-retry">Try again</button>`;+ el.querySelector('.avi-retry').addEventListener('click', retry);+ return el;+}++// About: agent bio + skills when piloting an agent, plus the world-supplied facts.+async function renderAbout(root, subject, { agentId }) {+ const body = sectionBody(root, 'about');+ if (!body) return;++ const factRows = (facts) =>+ facts+ .filter((f) => f && f.label && (f.value ?? '') !== '')+ .map(+ (f) =>+ `<div class="avi-fact"><span class="avi-fact-l">${esc(f.label)}</span><span class="avi-fact-v">${+ f.href ? `<a href="${esc(f.href)}"${/^https?:/.test(f.href) ? ' target="_blank" rel="noopener noreferrer"' : ''}>${esc(f.value)}</a>` : esc(f.value)+ }</span></div>`,+ )+ .join('');++ const baseFacts = Array.isArray(subject.facts) ? subject.facts : [];+ const load = async () => {+ body.innerHTML = factRows(baseFacts) + (agentId ? skeleton(2) : '');+ if (!agentId) {+ if (!baseFacts.length) {+ body.innerHTML = emptyState(+ 'Nothing else on file',+ 'This avatar is not piloting a registered three.ws agent, so there is no public profile to show.',+ [{ label: 'Create your own agent', href: '/agents' }],+ );+ }+ return;+ }+ try {+ const res = await apiFetch(`/api/agents/${encodeURIComponent(agentId)}`, { allowAnonymous: true });+ if (!res.ok) throw new Error(`agent ${res.status}`);+ const { agent } = await res.json();+ if (!document.contains(body)) return;+ const skills = Array.isArray(agent?.skills) ? agent.skills.slice(0, 8) : [];+ body.innerHTML =+ (agent?.description ? `<p class="avi-bio">${esc(agent.description)}</p>` : '') ++ factRows([+ { label: 'Agent', value: agent?.name || agentId.slice(0, 8), href: `/agent/${encodeURIComponent(agentId)}` },+ ...(agent?.author_name ? [{ label: 'Creator', value: agent.author_name }] : []),+ ...(agent?.erc8004_agent_id ? [{ label: 'ERC-8004', value: `#${agent.erc8004_agent_id} on-chain` }] : []),+ ...baseFacts,+ ]) ++ (skills.length+ ? `<div class="avi-skills">${skills.map((s) => `<span class="avi-chip">${esc(typeof s === 'string' ? s : s?.name || '')}</span>`).join('')}</div>`+ : '');+ // Upgrade the monogram to the agent's real thumbnail once known.+ if (agent?.avatar_thumbnail_url) {+ const mono = root.querySelector('.avi-monogram');+ if (mono) mono.innerHTML = `<img src="${esc(agent.avatar_thumbnail_url)}" alt="" loading="lazy" />`;+ }+ if (agent?.name) {+ const nameEl = root.querySelector('.avi-name');+ // Peer nickname stays primary; the agent name rides underneath.+ if (nameEl && agent.name !== nameEl.textContent) {+ nameEl.insertAdjacentHTML('afterend', `<div class="avi-subname">pilots <a href="/agent/${encodeURIComponent(agentId)}">${esc(agent.name)}</a></div>`);+ }+ }+ } catch (err) {+ if (!document.contains(body)) return;+ log.warn('[avatar-inspector] agent profile failed', err?.message);+ body.innerHTML = factRows(baseFacts);+ body.appendChild(errorState('Could not load this agent’s profile.', load));+ }+ };+ load();+}++// Wallet: the agent's full portfolio when piloting one; bare verified-wallet+// balances otherwise; a designed empty state when there is no wallet at all.+async function renderWallet(root, { agentId, wallet, kind }) {+ const body = sectionBody(root, 'wallet');+ if (!body) return;++ const addressPlate = (address, extraClass = '') => `+ <div class="avi-plate ${extraClass}">+ <code class="avi-addr" title="${esc(address)}">${esc(shortAddress(address, 6, 6))}</code>+ <button type="button" class="avi-mini" data-copy="${esc(address)}">Copy</button>+ <a class="avi-mini" href="${esc(explorerAddr(address))}" target="_blank" rel="noopener noreferrer">Explorer</a>+ </div>`;++ const wireCopy = () => {+ body.querySelectorAll('[data-copy]').forEach((btn) =>+ btn.addEventListener('click', async () => {+ try {+ await navigator.clipboard.writeText(btn.dataset.copy);+ const was = btn.textContent;+ btn.textContent = 'Copied';+ setTimeout(() => { btn.textContent = was; }, 1200);+ } catch {+ btn.textContent = 'Press ⌘C';+ setTimeout(() => { btn.textContent = 'Copy'; }, 1500);+ }+ }),+ );+ };++ const load = async () => {+ body.innerHTML = skeleton(3);++ if (agentId) {+ try {+ const res = await apiFetch(`/api/agents/${encodeURIComponent(agentId)}/solana/networth`, { allowAnonymous: true });+ if (!res.ok) throw new Error(`networth ${res.status}`);+ const { data } = await res.json();+ if (!document.contains(body)) return;+ if (!data?.address) {+ body.innerHTML = emptyState(+ 'Wallet provisioning',+ 'This agent’s self-custodial wallet is still being set up. Reputation it has already earned still counts.',+ );+ return;+ }+ const p = data.portfolio || {};+ const top = Array.isArray(p.top) ? p.top : [];+ body.innerHTML =+ addressPlate(data.address) ++ `<div class="avi-worth">+ <div class="avi-worth-usd">${esc(formatWalletUsd(p.usd || 0))}</div>+ <div class="avi-worth-sub">${esc(fmtAmount(p.sol))} SOL${data.tier?.label ? ` · ${esc(data.tier.label)}` : ''}${data.stale ? ' · last known' : ''}</div>+ </div>` ++ (p.three+ ? `<div class="avi-fact"><span class="avi-fact-l">$THREE</span><span class="avi-fact-v">${esc(fmtAmount(p.three.amount))} (${esc(formatWalletUsd(p.three.usd))})</span></div>`+ : '') ++ (top.length+ ? `<div class="avi-holdings">${top+ .map(+ (t) =>+ `<div class="avi-holding"><span>${esc(t.symbol || shortAddress(t.mint))}</span><span>${esc(fmtAmount(t.amount))}${t.usd ? ` · ${esc(formatWalletUsd(t.usd))}` : ''}</span></div>`,+ )+ .join('')}</div>`+ : `<p class="avi-note">No token holdings yet — a real $0 wallet shows $0.</p>`) ++ (data.reputation?.tips?.count+ ? `<div class="avi-fact"><span class="avi-fact-l">Tips received</span><span class="avi-fact-v">${data.reputation.tips.count} (${esc(formatWalletUsd(data.reputation.tips.usd))})</span></div>`+ : '');+ wireCopy();+ } catch (err) {+ if (!document.contains(body)) return;+ log.warn('[avatar-inspector] networth failed', err?.message);+ body.innerHTML = '';+ body.appendChild(errorState('Could not read this agent’s wallet right now. Its on-chain balances are unchanged.', load));+ }+ return;+ }++ if (wallet) {+ try {+ const res = await apiFetch('/api/wallet/balances', {+ method: 'POST',+ headers: { 'content-type': 'application/json' },+ body: JSON.stringify({ chain: 'solana', address: wallet }),+ allowAnonymous: true,+ });+ if (!res.ok) throw new Error(`balances ${res.status}`);+ const bal = await res.json();+ if (!document.contains(body)) return;+ const tokens = Array.isArray(bal?.tokens) ? bal.tokens.slice(0, 5) : [];+ body.innerHTML =+ addressPlate(wallet) ++ `<div class="avi-worth">+ <div class="avi-worth-usd">${esc(fmtAmount(bal?.native?.amount))} ${esc(bal?.native?.symbol || 'SOL')}</div>+ ${bal?.native?.usd ? `<div class="avi-worth-sub">${esc(formatWalletUsd(bal.native.usd))}</div>` : ''}+ </div>` ++ (tokens.length+ ? `<div class="avi-holdings">${tokens+ .map((t) => `<div class="avi-holding"><span>${esc(t.symbol || '?')}</span><span>${esc(fmtAmount(t.amount))}${t.usd ? ` · ${esc(formatWalletUsd(t.usd))}` : ''}</span></div>`)+ .join('')}</div>`+ : '') ++ `<p class="avi-note">Verified account wallet — this player signed in with it, but isn’t piloting a registered agent.</p>`;+ wireCopy();+ } catch (err) {+ if (!document.contains(body)) return;+ log.warn('[avatar-inspector] balances failed', err?.message);+ body.innerHTML = addressPlate(wallet);+ wireCopy();+ body.appendChild(errorState('Could not read balances right now.', load));+ }+ return;+ }++ body.innerHTML = emptyState(+ kind === 'npc' || kind === 'ambient' ? 'No wallet' : 'No wallet linked',+ kind === 'npc'+ ? 'Townspeople sell real paid services at their counters, but don’t carry a public wallet of their own.'+ : kind === 'ambient'+ ? 'Ambient locals are part of the town’s background life — they aren’t players and hold no wallet.'+ : kind === 'self'+ ? 'Sign in with your wallet — or pilot one of your agents — and your balances and reputation appear here.'+ : 'This player is exploring as a guest — no verified wallet, no agent.',+ kind === 'self' ? [{ label: 'Get an agent wallet', href: '/agent-wallet' }] : [],+ );+ };+ load();+}++// Reputation: the shared server-computed trust breakdown for agents; honest+// empty states for everyone else.+function renderReputation(root, { agentId, kind }) {+ const body = sectionBody(root, 'reputation');+ if (!body) return;+ if (agentId) {+ body.appendChild(reputationPanelEl(agentId, { unlocks: false }));+ return;+ }+ body.innerHTML = emptyState(+ 'No trust score',+ kind === 'npc'+ ? 'Townspeople are part of the world itself — reputation applies to player-owned agents.'+ : kind === 'ambient'+ ? 'Ambient locals aren’t players, so there’s nothing to score.'+ : 'Reputation is earned by registered agents through real settled activity. This avatar isn’t piloting one.',+ kind === 'npc' || kind === 'ambient' ? [] : [{ label: 'How trust is earned', href: '/reputation' }],+ );+}++function renderFooter(root, { agentId, wallet }) {+ const foot = root.querySelector('.avi-foot');+ if (!foot) return;+ const links = [];+ if (agentId) {+ links.push(`<a class="avi-cta" href="/agent/${encodeURIComponent(agentId)}">Full profile</a>`);+ links.push(`<a class="avi-cta avi-cta-ghost" href="/agent/${encodeURIComponent(agentId)}/wallet">Wallet hub</a>`);+ } else if (wallet) {+ links.push(`<a class="avi-cta avi-cta-ghost" href="${esc(explorerAddr(wallet))}" target="_blank" rel="noopener noreferrer">View on explorer</a>`);+ }+ foot.innerHTML = links.join('') || `<span class="avi-foot-hint">Esc closes · I inspects the nearest avatar</span>`;+}++// ── styles ───────────────────────────────────────────────────────────────────++function ensureStyles() {+ if (document.getElementById(STYLE_ID)) return;+ const s = document.createElement('style');+ s.id = STYLE_ID;+ s.textContent = `+.avi-root{position:fixed;top:0;right:0;bottom:0;z-index:940;width:min(400px,94vw);display:flex;flex-direction:column;+ background:color-mix(in srgb, var(--bg,#0b0b0b) 88%, transparent);border-left:1px solid var(--border,#26262b);+ backdrop-filter:blur(14px);-webkit-backdrop-filter:blur(14px);color:var(--text,#e7e7ea);+ transform:translateX(102%);transition:transform .22s cubic-bezier(.2,.8,.25,1);+ font:13.5px/1.5 var(--font-body,ui-sans-serif,system-ui,sans-serif)}+.avi-root.avi-in{transform:translateX(0)}+@media (prefers-reduced-motion: reduce){.avi-root{transition:none}}+.avi-head{display:flex;align-items:center;gap:12px;padding:16px 16px 12px;border-bottom:1px solid var(--border,#26262b)}+.avi-monogram{width:44px;height:44px;border-radius:12px;flex:0 0 auto;display:grid;place-items:center;overflow:hidden;+ background:linear-gradient(135deg,#1d1d24,#2a2a35);border:1px solid var(--border,#26262b);+ font-weight:700;font-size:15px;letter-spacing:.5px;color:var(--text,#e7e7ea)}+.avi-monogram img{width:100%;height:100%;object-fit:cover}+.avi-id{min-width:0;flex:1}+.avi-name{margin:0;font-size:16px;font-weight:700;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}+.avi-subname{font-size:12px;color:var(--ink-soft,#9a9aa3)}+.avi-subname a{color:inherit;text-decoration:underline;text-underline-offset:2px}+.avi-subname a:hover{color:var(--text,#e7e7ea)}+.avi-chips{display:flex;gap:6px;margin-top:4px;flex-wrap:wrap}+.avi-chip{font-size:10.5px;font-weight:600;letter-spacing:.4px;text-transform:uppercase;padding:2px 8px;border-radius:999px;+ border:1px solid var(--border,#26262b);color:var(--ink-soft,#9a9aa3);background:rgba(255,255,255,.03)}+.avi-chip-kind{color:var(--text,#e7e7ea);border-color:color-mix(in srgb, var(--accent,#c4b5fd) 45%, transparent)}+.avi-close{flex:0 0 auto;width:30px;height:30px;border-radius:8px;border:1px solid var(--border,#26262b);+ background:transparent;color:var(--ink-soft,#9a9aa3);font-size:13px;cursor:pointer;+ transition:background .15s ease,color .15s ease}+.avi-close:hover,.avi-close:focus-visible{background:rgba(255,255,255,.07);color:var(--text,#e7e7ea)}+.avi-close:focus-visible{outline:2px solid var(--accent,#c4b5fd);outline-offset:1px}+.avi-body{flex:1;overflow-y:auto;overscroll-behavior:contain;padding:6px 16px 16px}+.avi-section{padding:12px 0;border-bottom:1px solid color-mix(in srgb, var(--border,#26262b) 60%, transparent)}+.avi-section:last-child{border-bottom:none}+.avi-h{margin:0 0 8px;font-size:11px;font-weight:700;letter-spacing:.8px;text-transform:uppercase;color:var(--ink-soft,#9a9aa3)}+.avi-bio{margin:0 0 10px;color:var(--ink-soft,#c2c2ca)}+.avi-fact{display:flex;justify-content:space-between;gap:12px;padding:4px 0;font-size:13px}+.avi-fact-l{color:var(--ink-soft,#9a9aa3);flex:0 0 auto}+.avi-fact-v{text-align:right;min-width:0;overflow-wrap:anywhere}+.avi-fact-v a{color:inherit;text-decoration:underline;text-underline-offset:2px}+.avi-fact-v a:hover{color:var(--accent,#c4b5fd)}+.avi-skills{display:flex;flex-wrap:wrap;gap:6px;margin-top:10px}+.avi-plate{display:flex;align-items:center;gap:8px;padding:8px 10px;border-radius:10px;+ border:1px solid var(--border,#26262b);background:rgba(255,255,255,.03)}+.avi-addr{font-family:var(--font-mono,ui-monospace,monospace);font-size:12.5px;flex:1;min-width:0;+ overflow:hidden;text-overflow:ellipsis}+.avi-mini{flex:0 0 auto;font-size:11px;font-weight:600;padding:3px 8px;border-radius:7px;cursor:pointer;+ border:1px solid var(--border,#26262b);background:transparent;color:var(--ink-soft,#9a9aa3);text-decoration:none;+ transition:background .15s ease,color .15s ease}+.avi-mini:hover,.avi-mini:focus-visible{background:rgba(255,255,255,.08);color:var(--text,#e7e7ea)}+.avi-mini:focus-visible{outline:2px solid var(--accent,#c4b5fd);outline-offset:1px}+.avi-worth{margin:12px 0 8px}+.avi-worth-usd{font-size:24px;font-weight:750;letter-spacing:-.02em}+.avi-worth-sub{font-size:12px;color:var(--ink-soft,#9a9aa3);margin-top:2px}+.avi-holdings{margin-top:8px;border:1px solid color-mix(in srgb, var(--border,#26262b) 70%, transparent);border-radius:10px;overflow:hidden}+.avi-holding{display:flex;justify-content:space-between;gap:10px;padding:6px 10px;font-size:12.5px}+.avi-holding:nth-child(odd){background:rgba(255,255,255,.025)}+.avi-holding span:last-child{color:var(--ink-soft,#c2c2ca)}+.avi-note{margin:8px 0 0;font-size:12px;color:var(--ink-soft,#9a9aa3)}+.avi-empty{padding:10px 12px;border:1px dashed color-mix(in srgb, var(--border,#26262b) 90%, transparent);border-radius:10px}+.avi-empty-title{font-weight:650;margin-bottom:2px}+.avi-empty p{margin:0;font-size:12.5px;color:var(--ink-soft,#9a9aa3)}+.avi-links{display:flex;flex-wrap:wrap;gap:10px;margin-top:8px}+.avi-links a{font-size:12.5px;font-weight:600;color:var(--accent,#c4b5fd);text-decoration:none}+.avi-links a:hover,.avi-links a:focus-visible{text-decoration:underline;text-underline-offset:2px}+.avi-error{margin-top:8px;padding:10px 12px;border:1px solid color-mix(in srgb, #f87171 40%, transparent);border-radius:10px}+.avi-error p{margin:0 0 8px;font-size:12.5px;color:var(--ink-soft,#c2c2ca)}+.avi-retry{font-size:12px;font-weight:600;padding:4px 10px;border-radius:8px;cursor:pointer;+ border:1px solid var(--border,#26262b);background:transparent;color:var(--text,#e7e7ea)}+.avi-retry:hover,.avi-retry:focus-visible{background:rgba(255,255,255,.08)}+.avi-sk{height:14px;border-radius:6px;margin:6px 0;background:linear-gradient(90deg,rgba(255,255,255,.05),rgba(255,255,255,.11),rgba(255,255,255,.05));+ background-size:200% 100%;animation:avi-shimmer 1.2s linear infinite}+@keyframes avi-shimmer{to{background-position:-200% 0}}+@media (prefers-reduced-motion: reduce){.avi-sk{animation:none}}+.avi-foot{display:flex;gap:8px;padding:12px 16px;border-top:1px solid var(--border,#26262b)}+.avi-foot-hint{font-size:11.5px;color:var(--ink-soft,#9a9aa3)}+.avi-cta{flex:1;text-align:center;font-size:13px;font-weight:650;padding:8px 10px;border-radius:10px;text-decoration:none;+ background:var(--accent,#c4b5fd);color:#0b0b0b;transition:filter .15s ease}+.avi-cta:hover,.avi-cta:focus-visible{filter:brightness(1.08)}+.avi-cta:focus-visible{outline:2px solid var(--text,#e7e7ea);outline-offset:1px}+.avi-cta-ghost{background:transparent;color:var(--text,#e7e7ea);border:1px solid var(--border,#26262b)}+@media (max-width:480px){.avi-root{width:100vw;border-left:none}}+`;+ document.head.appendChild(s);+}diff --git a/workers/agent-screen-pool/index.js b/workers/agent-screen-pool/index.jsindex a98fdcfb6..c73e1ed1c 100644--- a/workers/agent-screen-pool/index.js+++ b/workers/agent-screen-pool/index.js@@ -33,12 +33,10 @@ import { generateNarration, runTaskSteps } from './task-runner.js';const BASE_URL = (process.env.BASE_URL || 'https://three.ws').replace(/\/$/, '');const WANTED_URL = process.env.WANTED_URL || `${BASE_URL}/api/agent/watch-wanted`;-// Two render surfaces consume two frame conventions: the live wall + 2D watch-// panel read the "dashed" push; the in-world 3D desk reads the "slashed" push.-// We publish to both so a watched agent goes live everywhere at once.-const PUSH_URL = process.env.PUSH_URL || `${BASE_URL}/api/agent-screen-push`; // wall + watch panel-const PUSH_URL_DESK = process.env.PUSH_URL_DESK || `${BASE_URL}/api/agent/screen-push`; // 3D desk-const SECRET = process.env.SCREEN_WORKER_SECRET || '';+// Single frame convention: the live wall, 2D watch panel, AND the in-world 3D+// desk all read /api/agent-screen-push frames via /api/agent-screen-stream.+const PUSH_URL = process.env.PUSH_URL || `${BASE_URL}/api/agent-screen-push`;+const SECRET = process.env.SCREEN_WORKER_SECRET || '';// Hard cap on concurrent Chromium casters. The API's /api/agent/watch-status// reports queue position against SCREEN_POOL_MAX (same default, 6) — keep the two@@ -150,32 +148,21 @@ async function pushFrame(entry) {try {const buf = await entry.page.screenshot({ type: 'jpeg', quality: JPEG_QUALITY, fullPage: false });const b64 = buf.toString('base64');- const seq = ++entry.seq;const headers = { 'content-type': 'application/json', authorization: `Bearer ${SECRET}` };- // Publish to both render surfaces. Failures are independent — the wall- // shouldn't go dark because the desk endpoint hiccuped, and vice versa.- const [wall, desk] = await Promise.allSettled([- fetch(PUSH_URL, {- method: 'POST', headers,- body: JSON.stringify({- agentId: entry.agentId,- // On a Coin World Tour the frame is stamped with the current waypoint- // (entry.activityOverride, e.g. "Tour · Into the arena") so the wall +- // watch panel light up the TOUR badge; otherwise it's the live view.- frame: { data: `data:image/jpeg;base64,${b64}`, activity: entry.activityOverride || `Live view · ${entry.name}`, type: 'screenshot' },- }),- }),- fetch(PUSH_URL_DESK, {- method: 'POST', headers,- body: JSON.stringify({ agentId: entry.agentId, frame: b64, seq }),+ const res = await fetch(PUSH_URL, {+ method: 'POST', headers,+ body: JSON.stringify({+ agentId: entry.agentId,+ // On a Coin World Tour the frame is stamped with the current waypoint+ // (entry.activityOverride, e.g. "Tour · Into the arena") so the wall ++ // watch panel light up the TOUR badge; otherwise it's the live view.+ frame: { data: `data:image/jpeg;base64,${b64}`, activity: entry.activityOverride || `Live view · ${entry.name}`, type: 'screenshot' },}),- ]);- const wallBad = wall.status === 'fulfilled' && !wall.value.ok;- if (wallBad && Date.now() - (entry.lastErrorAt || 0) > 30_000) {+ });+ if (!res.ok && Date.now() - (entry.lastErrorAt || 0) > 30_000) {entry.lastErrorAt = Date.now();- log('wall push failed', entry.agentId, wall.value.status, (await wall.value.text().catch(() => '')).slice(0, 120));+ log('push failed', entry.agentId, res.status, (await res.text().catch(() => '')).slice(0, 120));}- void desk;} catch (err) {if (Date.now() - (entry.lastErrorAt || 0) > 30_000) {entry.lastErrorAt = Date.now();@@ -190,7 +177,7 @@ async function startCasting(agent) {await ensureBrowser();const agentId = agent.agentId;const page = await context.newPage();- const entry = { agentId, page, name: agent.name || 'Agent', timer: null, pushing: false, lastErrorAt: 0, seq: 0, controller: new AbortController() };+ const entry = { agentId, page, name: agent.name || 'Agent', timer: null, pushing: false, lastErrorAt: 0, controller: new AbortController() };pool.set(agentId, entry);const url = resolveUrl(agent.homeUrl, agentId);try {@@ -278,21 +265,21 @@ async function pushTaskFrame(entry, { activity = '', type = 'screenshot', shoot} catch { /* page navigating — push the narration line without pixels */ }}const dataUrl = b64 ? `data:image/jpeg;base64,${b64}` : null;- const seq = ++entry.seq;const headers = { 'content-type': 'application/json', authorization: `Bearer ${SECRET}` };- const [wall] = await Promise.allSettled([- fetch(PUSH_URL, {+ try {+ const res = await fetch(PUSH_URL, {method: 'POST', headers,body: JSON.stringify({ agentId: entry.agentId, frame: { data: dataUrl, activity, type } }),- }),- b64- ? fetch(PUSH_URL_DESK, { method: 'POST', headers, body: JSON.stringify({ agentId: entry.agentId, frame: b64, seq }) })- : Promise.resolve(),- ]);- const wallBad = wall.status === 'fulfilled' && !wall.value.ok;- if (wallBad && Date.now() - (entry.lastErrorAt || 0) > 30_000) {- entry.lastErrorAt = Date.now();- log('task push failed', entry.agentId, wall.value.status, (await wall.value.text().catch(() => '')).slice(0, 120));+ });+ if (!res.ok && Date.now() - (entry.lastErrorAt || 0) > 30_000) {+ entry.lastErrorAt = Date.now();+ log('task push failed', entry.agentId, res.status, (await res.text().catch(() => '')).slice(0, 120));+ }+ } catch (err) {+ if (Date.now() - (entry.lastErrorAt || 0) > 30_000) {+ entry.lastErrorAt = Date.now();+ log('task push error', entry.agentId, err?.message || err);+ }}}diff --git a/workers/agora-citizens/README.md b/workers/agora-citizens/README.mdindex 57eced555..eaaefa198 100644--- a/workers/agora-citizens/README.md+++ b/workers/agora-citizens/README.md@@ -57,6 +57,9 @@ AGORA_ONCE=1 node index.js# 3. Run the fleet continuously.node index.js++# 4. World-seed — fill the Commons with real rigged agents (no on-chain, no SOL).+AGORA_SEED_ONLY=1 AGORA_SEED_LIMIT=200 node index.js```> The `@three-ws/solana-agent` SDK ships as TypeScript and must be built once@@ -91,8 +94,41 @@ Confirm tx signatures on <https://explorer.solana.com/?cluster=devnet>.| `AGORA_API_BASE` | no | `https://three.ws` | Board + bridge read host || `AGORA_DRY_RUN` | no | `0` | Plan only — no signing, no writes || `AGORA_ONCE` | no | `0` | One tick per citizen, then exit |+| `AGORA_SEED_ONLY` | no | `0` | World-seed mode: project rigged agents, then exit |+| `AGORA_SEED_LIMIT` | no | `120` | How many rigged agents to project (DB holds all; the 3D world renders the 200 most recent) |+| `AGORA_SEED_RESET` | no | `1` | Clear the prior *unregistered* world-seed first (never touches on-chain citizens/humans) || `PORT` | no | — | Bind a health endpoint (Cloud Run) |+## Populate the Commons (world-seed)++`AGORA_SEED_ONLY=1` fills the world **immediately, with no on-chain registration+and no SOL**. It projects the platform's own 3D agents that carry a **rigged+humanoid GLB avatar** into `agora_citizens`, one citizen per distinct avatar+(de-duped so the square isn't full of clones), each with:++- its **real avatar** (`avatar_url` = the avatar id the client resolves to the GLB+ via `/api/avatars/:id`),+- a **canonical AgenC id** derived offline via the identity bridge (no signature),+- a **profession** mapped from the agent's real signals (category / tags / name),+ with signal-less agents spread deterministically across all professions so the+ labour market reads balanced.++Seeded citizens have **no `agenc_agent_pda`** (the API/world render them as+*pending registration*) and **no activity row** — they simply exist and idle. Every+economic fact still traces to a real on-chain action: when the funded life-engine+runs (`node index.js`), it registers each on AgenC (backfilling the PDA) and they+start claiming → working → earning. This decouples *being alive in the world* from+*spending SOL to transact*, so the Commons is never an empty void while devnet+funding is arranged.++```bash+# Fill the world with 200 rigged citizens (idempotent; re-run to refresh).+AGORA_SEED_ONLY=1 AGORA_SEED_LIMIT=200 node index.js+# Then the live world shows them:+curl -s "$AGORA_API_BASE/api/agora/pulse" # population + profession mix+curl -s "$AGORA_API_BASE/api/agora/citizens" # the renderable roster+```+## Scale the fleetRaise `AGORA_MAX_CITIZENS` (each is a real AgenC agent needing devnet SOL — adiff --git a/workers/agora-citizens/config.js b/workers/agora-citizens/config.jsindex ec6cebd2f..38e9bca14 100644--- a/workers/agora-citizens/config.js+++ b/workers/agora-citizens/config.js@@ -68,6 +68,18 @@ export function loadConfig() {dryRun,// Single tick per citizen then exit — for CI smoke tests and manual runs.once: bool('AGORA_ONCE', false),+ // World-seed mode: project real rigged agents into the Commons as citizens+ // (real avatar, canonical AgenC id derived offline, profession from real+ // signals) WITHOUT any on-chain registration, then exit. No SOL needed — the+ // world fills instantly; the funded life-engine registers + works them later.+ seedOnly: bool('AGORA_SEED_ONLY', false),+ // How many rigged agents to project in a world-seed pass. The DB holds all of+ // them; the 3D renderer shows a bounded, nearest subset.+ seedLimit: Math.max(1, Math.min(2000, num('AGORA_SEED_LIMIT', 120))),+ // Before a world-seed, clear the previous UNREGISTERED world-seed citizens so+ // the population refreshes cleanly (never touches on-chain-registered citizens+ // or humans). Default on — a seed pass is the authoritative pending population.+ seedReset: bool('AGORA_SEED_RESET', true),databaseUrl,// Fleet size cap. The roster supplies the candidate citizens (seeded fromdiff --git a/workers/agora-citizens/index.js b/workers/agora-citizens/index.jsindex 2beb88bc3..e81cb0f19 100644--- a/workers/agora-citizens/index.js+++ b/workers/agora-citizens/index.js@@ -17,6 +17,7 @@ import http from 'node:http';import { loadConfig } from './config.js';import { makeStore } from './store.js';import { bootFleet, tickCitizen, replenishWork, planDryRun } from './engine.js';+import { seedWorld } from './seed.js';import { reconcileOnce } from './reconcile.js';import { log } from './log.js';@@ -154,6 +155,16 @@ async function main() {return;}+ // World-seed: fill the Commons with real rigged agents (no on-chain register,+ // no SOL), then exit. Decoupled from the funded loop so the world can be alive+ // immediately; on-chain registration + work happen when the fleet runs funded.+ if (cfg.seedOnly) {+ const summary = await seedWorld(cfg, store);+ console.log(JSON.stringify({ ok: true, seed: summary }, null, 2));+ setTimeout(() => process.exit(0), 500);+ return;+ }+startHealthServer();const ctx = await bootFleet(cfg, store);_live = { citizens: ctx.citizens.length, dispatcher: !!ctx.dispatcher };diff --git a/workers/agora-citizens/roster.js b/workers/agora-citizens/roster.jsindex 26f3c9de5..b5d6df20c 100644--- a/workers/agora-citizens/roster.js+++ b/workers/agora-citizens/roster.js@@ -171,3 +171,115 @@ export function buildRoster(seededAgents, cfg) {return specs.slice(0, cfg.maxCitizens);}+++// ── World-seed: real rigged agents become citizens ───────────────────────────+// The Commons fills from the platform's own 3D agents that carry a rigged+// humanoid GLB (store.listRiggedSeedAgents). Each becomes a citizen with its REAL+// avatar and a profession mapped from its real signals. Presence needs no on-chain+// PDA (agenc_agent_pda stays null until the funded life-engine registers it), so+// the world can be alive immediately without spending SOL.++// Deterministic 32-bit FNV-1a over a string, stable across runs/processes so an+// agent's default profession never flips between seeds.+function hashStr(str) {+ let h = 0x811c9dc5;+ const s = String(str || '');+ for (let i = 0; i < s.length; i++) {+ h ^= s.charCodeAt(i);+ h = Math.imul(h, 0x01000193);+ }+ return h >>> 0;+}++// Craft professions (everything but the universal Fetcher): the palette a+// signal-less agent is spread across so the Commons reads as a varied labour+// market. Every craft is backed by a real platform skill (work/*.js), so the+// assignment is a JOB, never a fabricated capability.+const CRAFTS = ['sculptor', 'scribe', 'cartographer', 'crier', 'appraiser', 'namekeeper', 'verifier'];++// Real-signal to profession, checked before the deterministic spread so an agent+// that actually carries a signal works the matching craft.+const SIGNAL_PROFESSION = [+ [/voice|audio|music|speech|sing|podcast|narrat|entertain/i, 'crier'],+ [/design|3d|model|sculpt|render|\bart\b|avatar|blender|mesh/i, 'sculptor'],+ [/scene|\bmap\b|world|diorama|architect|spatial|environment/i, 'cartographer'],+ [/market|token|trad|finance|invest|intel|analy|\bdao\b|governance|defi|price/i, 'appraiser'],+ [/name|\bens\b|domain|registr|resolver/i, 'namekeeper'],+ [/verif|audit|proof|security|moderat|fact.?check/i, 'verifier'],+ [/research|writ|summar|translat|academic|scribe|author|essay|\bdoc/i, 'scribe'],+];++/**+ * Map a real agent to the Agora profession it works. Grounded in the agent's own+ * signals (category/tags/name to a matching craft); a signal-less agent is spread+ * deterministically across every profession by a stable hash of its id, so the+ * world is colourful and balanced without inventing anything.+ */+export function professionForAgent(agent) {+ // NB: voice is a platform default on every agent, so it is NOT a signal — a+ // citizen only works Crier when its category/tags/name actually say audio/voice.+ const hay = [agent.category, ...(Array.isArray(agent.tags) ? agent.tags : []), agent.name]+ .filter(Boolean)+ .join(' ');+ for (const [re, prof] of SIGNAL_PROFESSION) if (re.test(hay)) return prof;+ // Signal-less: even deterministic spread across ALL professions (including the+ // universal Fetcher) so the Commons reads as a balanced labour market.+ const all = PROFESSIONS.map((p) => p.key);+ return all[hashStr(agent.id) % all.length];+}++// Fan citizens out around their home district (golden-angle scatter on growing+// rings) so a full Commons reads as a crowd, not six stacks of avatars.+function scatteredHome(i) {+ const d = DISTRICTS[i % DISTRICTS.length];+ const ring = Math.floor(i / DISTRICTS.length);+ const ang = (i * 2.399963) % (Math.PI * 2);+ const r = 2 + ring * 1.7;+ const round = (n) => Math.round(n * 100) / 100;+ return { name: d.name, x: round(d.x + Math.cos(ang) * r), z: round(d.z + Math.sin(ang) * r) };+}++/**+ * Shape a real rigged agent (a row from store.listRiggedSeedAgents) into a world-+ * seed citizen spec. Its canonical AgenC id is derived from a per-agent handle+ * (name + short id, so same-named agents stay distinct on-chain); avatarUrl is the+ * avatar UUID the client resolves to the real GLB via /api/avatars/:id. Profession+ * is its mapped craft PLUS the universal Fetcher bit (so it can always take work).+ */+export function shapeRiggedSeed(agent, i) {+ const home = scatteredHome(i);+ const base = slug(agent.name) || `agent-${String(agent.id).slice(0, 8)}`;+ const handle = `${base}-${String(agent.id).replace(/-/g, '').slice(0, 6)}`;+ const ref = { handle };+ if (agent.erc8004_agent_id != null) ref.erc8004AgentId = String(agent.erc8004_agent_id);+ const prof = professionForAgent(agent);+ const avatarId = agent.avatar_id ? String(agent.avatar_id) : null;+ return {+ key: `agent-${handle}`,+ kind: 'agent',+ displayName: agent.name,+ profession: prof,+ professionBits: professionBits([prof, 'fetcher']),+ home,+ agentDbId: agent.id,+ avatarId,+ avatarUrl: avatarId,+ identityRef: ref,+ identityHint: `rigged:${agent.id}`,+ };+}++/** Shape a page of rigged agents into world-seed citizen specs (de-duped by key). */+export function buildWorldSeedRoster(agents, cfg) {+ const specs = [];+ const seen = new Set();+ const cap = cfg && cfg.seedLimit ? cfg.seedLimit : Infinity;+ for (let i = 0; i < (agents || []).length && specs.length < cap; i++) {+ const spec = shapeRiggedSeed(agents[i], specs.length);+ if (!spec.agentDbId || seen.has(spec.key)) continue;+ seen.add(spec.key);+ specs.push(spec);+ }+ return specs;+}diff --git a/workers/agora-citizens/seed.js b/workers/agora-citizens/seed.jsnew file mode 100644index 000000000..bc384b49b--- /dev/null+++ b/workers/agora-citizens/seed.js@@ -0,0 +1,71 @@+// agora-citizens — world-seed. Fills the Commons with the platform's OWN 3D+// agents: the ones that carry a rigged humanoid GLB avatar (store.+// listRiggedSeedAgents). Each becomes a citizen with its REAL avatar, a canonical+// AgenC id derived offline via the identity bridge, and a profession mapped from+// its real signals (roster.professionForAgent).+//+// This path signs NO transaction and needs NO SOL: presence in the world does not+// require an on-chain PDA (agora_citizens.agenc_agent_pda stays null → the API and+// 3D world render the citizen as "pending registration"). It projects NO activity+// row either — a citizen only *exists* and idles until the funded life-engine+// registers it on AgenC and it starts claiming → working → earning. So the world+// is alive immediately, and every economic FACT still traces to a real on-chain+// action when it happens. No mocks, no fabricated trades.+//+// AGORA_SEED_ONLY=1 AGORA_SEED_LIMIT=120 node index.js++import { log } from './log.js';+import { deriveIdentity } from './agenc.js';+import { buildWorldSeedRoster } from './roster.js';++/**+ * Project up to cfg.seedLimit real rigged agents into agora_citizens. Idempotent:+ * seedWorldCitizen upserts on agent_id, so re-running refreshes avatars/professions+ * without duplicating rows or clobbering a citizen that has since registered+ * on-chain. Returns a summary { candidates, specs, seeded, failed, byProfession }.+ */+export async function seedWorld(cfg, store) {+ // Refresh the pending population: drop the prior unregistered world-seed so a+ // re-seed swaps in the current distinct-avatar set (registered citizens + humans+ // are never touched — the clear is scoped to PDA-null, seedMode='world' rows).+ if (cfg.seedReset) {+ try {+ const removed = await store.clearUnregisteredWorldSeed();+ if (removed) log.info('world-seed: cleared prior pending citizens', { removed });+ } catch (err) {+ log.warn('world-seed: reset failed — seeding over existing rows', { err: err?.message });+ }+ }++ const agents = await store.listRiggedSeedAgents(cfg.seedLimit);+ const specs = buildWorldSeedRoster(agents, cfg);+ log.info('world-seed: roster assembled', { candidates: agents.length, specs: specs.length });++ let seeded = 0;+ let failed = 0;+ const byProfession = {};+ for (const spec of specs) {+ try {+ // Pure identity derivation (identity bridge) — no RPC, no signature.+ const ident = await deriveIdentity(spec.identityRef);+ const row = await store.seedWorldCitizen(spec, {+ agentIdHex: ident.agentIdHex,+ identitySource: ident.source,+ capabilityBits: spec.professionBits,+ avatarId: spec.avatarId,+ avatarUrl: spec.avatarUrl,+ });+ if (row) {+ seeded++;+ byProfession[spec.profession] = (byProfession[spec.profession] || 0) + 1;+ }+ } catch (err) {+ failed++;+ log.warn('world-seed: citizen failed — skipping', { key: spec.key, err: err?.message });+ }+ }++ const summary = { candidates: agents.length, specs: specs.length, seeded, failed, byProfession };+ log.info('world-seed: complete', summary);+ return summary;+}diff --git a/workers/agora-citizens/store.js b/workers/agora-citizens/store.jsindex 1a76d8408..b01874616 100644--- a/workers/agora-citizens/store.js+++ b/workers/agora-citizens/store.js@@ -70,6 +70,112 @@ export function makeStore(cfg) {}},+ /**+ * Real platform agents that carry a RIGGED humanoid GLB avatar: the ones that+ * can actually walk the Commons as citizens. Joins the avatar record and keeps+ * only public, humanoid (model_category='avatar'), publicly-resolvable models+ * with a stored GLB. De-duped to ONE agent per distinct avatar (many agents+ * are forks/drafts of the same model — seeding all of them would fill the+ * square with clones), then ordered by popularity so the nicest, most-varied+ * avatars fill the world first. Population source for the world-seed (seed.js):+ * each becomes a citizen with its REAL avatar; nothing is invented. Returns []+ * on a fresh DB.+ */+ async listRiggedSeedAgents(limit) {+ if (!sql) return [];+ try {+ const rows = await sql`+ select t.id, t.name, t.avatar_id, t.erc8004_agent_id,+ t.category, t.tags, t.voice_id, t.voice_provider, t.meta+ from (+ select distinct on (a.avatar_id)+ a.id, a.name, a.avatar_id, a.erc8004_agent_id,+ a.category, a.tags, a.voice_id, a.voice_provider, a.meta,+ coalesce(av.view_count, 0) as vc, a.created_at+ from agent_identities a+ join avatars av on av.id = a.avatar_id+ where a.deleted_at is null+ and a.is_public = true+ and av.deleted_at is null+ and av.storage_key is not null+ and av.model_category = 'avatar'+ and av.visibility = 'public'+ and length(coalesce(a.name, '')) > 0+ order by a.avatar_id, coalesce(av.view_count, 0) desc, a.created_at asc+ ) t+ order by t.vc desc, t.created_at asc+ limit ${Math.max(0, Number(limit) || 0)}+ `;+ return rows || [];+ } catch (err) {+ log.warn('listRiggedSeedAgents failed', { err: err?.message });+ return [];+ }+ },++ /**+ * Remove world-seeded citizens that have NOT registered on-chain yet+ * (agenc_agent_pda is null and meta.seedMode='world'). Lets a re-seed refresh+ * the population cleanly — swapping in a more varied/distinct-avatar set —+ * without ever touching a citizen that has a real on-chain PDA or a human.+ * Returns the number of rows removed.+ */+ async clearUnregisteredWorldSeed() {+ const db = requireSql();+ const rows = await db`+ delete from agora_citizens+ where kind = 'agent'+ and agenc_agent_pda is null+ and coalesce(meta->>'seedMode', '') = 'world'+ returning id+ `;+ return rows.length;+ },++ /**+ * Seed a real rigged agent into the world as a citizen WITHOUT an on-chain+ * registration (agenc_agent_pda stays null, so the API/world render it as+ * "pending registration"). Keyed on agent_id (one citizen per platform agent),+ * so re-seeding refreshes the avatar/profession without duplicating or+ * clobbering a later on-chain PDA. No activity row is projected: the citizen+ * simply exists and idles until the funded life-engine registers it and it+ * starts working. Returns { id, registered }.+ */+ async seedWorldCitizen(spec, info) {+ const db = requireSql();+ const meta = JSON.stringify({+ identityHint: spec.identityHint,+ identitySource: info.identitySource,+ home: spec.home,+ seedMode: 'world',+ });+ const rows = await db`+ insert into agora_citizens (+ kind, agent_id, display_name, avatar_id, avatar_url,+ agenc_agent_id, agenc_cluster, identity_source,+ profession, capability_bits, status,+ home_x, home_z, pos_x, pos_z, last_active_at, meta+ ) values (+ ${spec.kind}, ${spec.agentDbId}, ${spec.displayName}, ${info.avatarId}, ${info.avatarUrl},+ ${info.agentIdHex}, ${cfg.cluster}, ${info.identitySource},+ ${spec.profession}, ${info.capabilityBits.toString()}, 'idle',+ ${spec.home.x}, ${spec.home.z}, ${spec.home.x}, ${spec.home.z}, now(), ${meta}::jsonb+ )+ on conflict (agent_id) where agent_id is not null do update set+ display_name = excluded.display_name,+ avatar_id = coalesce(excluded.avatar_id, agora_citizens.avatar_id),+ avatar_url = coalesce(excluded.avatar_url, agora_citizens.avatar_url),+ agenc_agent_id = coalesce(agora_citizens.agenc_agent_id, excluded.agenc_agent_id),+ identity_source = coalesce(agora_citizens.identity_source, excluded.identity_source),+ profession = excluded.profession,+ capability_bits = excluded.capability_bits,+ last_active_at = now(),+ meta = agora_citizens.meta || ${meta}::jsonb+ returning id, (agenc_agent_pda is not null) as registered+ `;+ return rows[0] || null;+ },+/*** Upsert a citizen by its deterministic on-chain PDA (the stable key — the* same agent always derives the same PDA). Returns the citizen row id.