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: agent-memory pins, MCP tool refinements, and world-env
nirholasfa3675662e1d
diff --git a/api/_lib/migrations/20260603140000_agent_memory_pins.sql b/api/_lib/migrations/20260603140000_agent_memory_pins.sqlnew file mode 100644index 000000000..146d4f4ae--- /dev/null+++ b/api/_lib/migrations/20260603140000_agent_memory_pins.sql@@ -0,0 +1,16 @@+-- agent_memory_pins — records every IPFS CID an agent has pinned via+-- POST /api/agents/:id/memory/pin, so the read proxy+-- (GET /api/agents/:id/memory/:cid) can verify the requested CID actually+-- belongs to that agent instead of acting as a generic authenticated IPFS+-- fetch proxy for any CID.+create table if not exists agent_memory_pins (+ agent_id uuid not null references agent_identities(id) on delete cascade,+ cid text not null,+ filename text not null,+ bytes integer not null default 0,+ created_at timestamptz not null default now(),+ primary key (agent_id, cid)+);++create index if not exists agent_memory_pins_agent+ on agent_memory_pins(agent_id, created_at desc);diff --git a/api/_lib/rate-limit.js b/api/_lib/rate-limit.jsindex cdb52e636..31da7a7d2 100644--- a/api/_lib/rate-limit.js+++ b/api/_lib/rate-limit.js@@ -138,6 +138,11 @@ export const limits = {upload: (userId) => getLimiter('upload', { limit: 60, window: '1 h' }).limit(userId),avatarPatch: (userId) => getLimiter('avatar:patch', { limit: 20, window: '1 h' }).limit(userId),prefsWrite: (userId) => getLimiter('prefs:write', { limit: 30, window: '1 h' }).limit(userId),+ // Per-user budget for the paid Voyage embeddings endpoint (api/agents/:id/embed).+ // Keyed by userId (not IP) so the shared platform API key/quota can't be drained+ // by one account rotating IPs. recall() embeds one query at a time, so a generous+ // per-minute ceiling still leaves headroom for interactive memory search.+ embedUser: (userId) => getLimiter('embed:user', { limit: 120, window: '1 m' }).limit(userId),avatarRollback: (userId) =>getLimiter('avatar:rollback', { limit: 10, window: '1 h' }).limit(userId),chatUser: (userId) => getLimiter('chat:user', { limit: 40, window: '1 m' }).limit(userId),diff --git a/api/_lib/schema.sql b/api/_lib/schema.sqlindex 271850331..23d40ea13 100644--- a/api/_lib/schema.sql+++ b/api/_lib/schema.sql@@ -444,6 +444,21 @@ do $$ beginfor each row execute function set_updated_at();exception when duplicate_object then null; end $$;+-- ── agent_memory_pins — IPFS CIDs an agent has pinned ────────────────────────+-- Lets the read proxy (GET /api/agents/:id/memory/:cid) confirm the requested+-- CID belongs to this agent instead of proxying any caller-supplied CID.+create table if not exists agent_memory_pins (+ agent_id uuid not null references agent_identities(id) on delete cascade,+ cid text not null,+ filename text not null,+ bytes integer not null default 0,+ created_at timestamptz not null default now(),+ primary key (agent_id, cid)+);++create index if not exists agent_memory_pins_agent+ on agent_memory_pins(agent_id, created_at desc);+-- ── agent_actions — append-only signed history ───────────────────────────────create table if not exists agent_actions (id bigserial primary key,diff --git a/api/agents/_id/embed.js b/api/agents/_id/embed.jsindex 427da430a..d3d9d9d07 100644--- a/api/agents/_id/embed.js+++ b/api/agents/_id/embed.js@@ -2,22 +2,39 @@// Generates a text embedding via Voyage AI (voyage-3-lite, 1024-dim).// Used by AgentMemory.recall() for semantic similarity search.-import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';+import { getSessionUser, authenticateBearer, extractBearer, hasScope } from '../../_lib/auth.js';import { cors, json, method, readJson, error } from '../../_lib/http.js';-import { limits, clientIp } from '../../_lib/rate-limit.js';+import { limits } from '../../_lib/rate-limit.js';+import { sql } from '../../_lib/db.js';import { env } from '../../_lib/env.js';const VOYAGE_URL = 'https://api.voyageai.com/v1/embeddings';-export async function handleEmbed(req, res) {+export async function handleEmbed(req, res, id) {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;const session = await getSessionUser(req);const bearer = session ? null : await authenticateBearer(extractBearer(req));if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');+ // Match the sibling per-agent sub-resources (nfts.js / pumpfun.js): a bearer+ // token must carry an appropriate scope to drive the paid embeddings API.+ if (bearer && !hasScope(bearer.scope, 'mcp') && !hasScope(bearer.scope, 'profile')) {+ return error(res, 403, 'insufficient_scope', 'requires mcp or profile scope');+ }+ const userId = session?.id || bearer?.userId;++ // This route is namespaced per-agent and burns the shared platform Voyage key,+ // so it must enforce ownership of :id exactly like every other /api/agents/:id+ // sub-resource — never embed against an agent the caller doesn't own.+ const [agent] = await sql`+ select id from agent_identities+ where id = ${id} and user_id = ${userId} and deleted_at is null+ limit 1+ `;+ if (!agent) return error(res, 404, 'not_found', 'agent not found');- const rl = await limits.authIp(clientIp(req));+ const rl = await limits.embedUser(userId);if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');const body = await readJson(req);diff --git a/api/avatar/presign-glb.js b/api/avatar/presign-glb.jsindex a1e7f5870..450844059 100644--- a/api/avatar/presign-glb.js+++ b/api/avatar/presign-glb.js@@ -24,6 +24,7 @@import { cors, error, json, wrap } from '../_lib/http.js';import { getSessionUser } from '../_lib/auth.js';import { presignUpload, publicUrl } from '../_lib/r2.js';+import { limits, clientIp } from '../_lib/rate-limit.js';import { randomUUID } from 'crypto';// 16 MB — generous for a single-mesh avatar, tight enough to keep the scene's@@ -45,14 +46,31 @@ export default wrap(async (req, res) => {if (session) userId = session.id ?? session.userId ?? 'anon';} catch { /* anonymous player — allowed */ }+ // Anonymous /play uploaders share the `anon` namespace, so rate-limit them+ // per-IP to stop a single client minting unlimited presigned PUT URLs and+ // using the bucket as free hosting. Authenticated users get the upload bucket+ // keyed to their own id.+ const rl = userId === 'anon'+ ? await limits.publicIp(clientIp(req))+ : await limits.upload(userId);+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many upload requests');+const body = req.body || {};const contentType = (body.content_type || 'model/gltf-binary').toLowerCase().trim();if (!ALLOWED_TYPES.has(contentType)) {return error(res, 415, 'unsupported_media_type', `content_type must be model/gltf-binary, got: ${contentType}`);}+ // Require a declared size and enforce the cap up front. The presigned PUT+ // can't carry a content-length policy (R2 rejects the CORS preflight when+ // content-length is a signed header — see api/_lib/r2.js), so the declared+ // `bytes` is the binding pre-check; omitting it would otherwise sidestep the+ // 16 MB cap entirely.const bytes = Number(body.bytes);- if (Number.isFinite(bytes) && bytes > MAX_GLB_BYTES) {+ if (!Number.isFinite(bytes) || bytes <= 0) {+ return error(res, 400, 'invalid_request', 'bytes (declared file size) is required');+ }+ if (bytes > MAX_GLB_BYTES) {return error(res, 413, 'payload_too_large', `glb is ${bytes} bytes; max is ${MAX_GLB_BYTES}`);}diff --git a/api/avatar/video-generate.js b/api/avatar/video-generate.jsindex 59edde360..0589833bd 100644--- a/api/avatar/video-generate.js+++ b/api/avatar/video-generate.js@@ -24,6 +24,29 @@ import { cors, error, json, wrap } from '../_lib/http.js';import { sql } from '../_lib/db.js';import { publicUrl } from '../_lib/r2.js';import { getSessionUser } from '../_lib/auth.js';+import { env } from '../_lib/env.js';++// Mirror of trustedOrigin() in api/avatar/optimize.js: image_url/audio_url are+// forwarded to the LongCat worker, which fetches them server-side. Restrict them+// to https on a three.ws-controlled host (APP_ORIGIN / R2 public domain) so a+// caller can't drive the worker into an SSRF against internal/metadata hosts.+function trustedMediaUrl(url) {+ let u;+ try {+ u = new URL(url);+ } catch {+ return false;+ }+ if (u.protocol !== 'https:') return false;+ const allowed = new Set();+ try {+ if (env.APP_ORIGIN) allowed.add(new URL(env.APP_ORIGIN).host);+ } catch { /* ignore malformed env */ }+ try {+ if (env.S3_PUBLIC_DOMAIN) allowed.add(new URL(env.S3_PUBLIC_DOMAIN).host);+ } catch { /* ignore malformed env */ }+ return allowed.has(u.host);+}function workerUrl() {const u = process.env.LONGCAT_WORKER_URL;@@ -92,6 +115,17 @@ export default wrap(async (req, res) => {if (!imageUrl) return error(res, 400, 'invalid_request', 'image_url or avatar_id is required');+ // The worker fetches these URLs server-side, so they must be https on a+ // three.ws-controlled host. A server-resolved avatar render (publicUrl →+ // R2 domain) already satisfies this; an arbitrary caller-supplied URL must+ // pass the same allowlist or we'd hand the worker an SSRF primitive.+ if (!trustedMediaUrl(imageUrl)) {+ return error(res, 400, 'invalid_request', 'image_url must be an https three.ws-hosted URL');+ }+ if (!trustedMediaUrl(audioUrl)) {+ return error(res, 400, 'invalid_request', 'audio_url must be an https three.ws-hosted URL');+ }+let workerRes;try {workerRes = await fetch(`${workerUrl()}/generate`, {diff --git a/api/avatars/_actions.js b/api/avatars/_actions.jsindex cfd239ff8..28d9c3825 100644--- a/api/avatars/_actions.js+++ b/api/avatars/_actions.js@@ -686,10 +686,23 @@ const handleAutoTag = wrap(async (req, res) => {`;if (!rows[0]) return error(res, 404, 'not_found', 'avatar not found');+ // Never trust thumb_key blindly: it is used for a server-side vision fetch and+ // written into avatars.thumbnail_key (which decorate() exposes as a public+ // URL). Restrict it to keys the caller can legitimately own — either their own+ // u/<userId>/ namespace, or the canonical thumb/<avatarId>.png slot for THIS+ // avatar (the shape thumbnail.js writes). Anything else would let one user+ // point the fetch at, and publicly disclose, another user's private object.+ const thumbKey = body.thumb_key;+ const ownsKey =+ thumbKey.startsWith(`u/${userId}/`) || thumbKey === `thumb/${body.avatar_id}.png`;+ if (!ownsKey) {+ return error(res, 400, 'invalid_storage_key', 'thumb_key must live under your namespace');+ }+// Fetch the thumbnail from R2 for vision.const { publicUrl } = await import('../_lib/r2.js');const { env } = await import('../_lib/env.js');- const thumbUrl = publicUrl(body.thumb_key);+ const thumbUrl = publicUrl(thumbKey);// Image classification needs a vision-capable model. Per platform policy// the free providers come first (OpenRouter hosts open vision models);@@ -721,8 +734,8 @@ const handleAutoTag = wrap(async (req, res) => {const patch = {};if (!currentTags.length && newTags.length) patch.tags = newTags;if (!currentDesc && desc) patch.description = desc;- // Always write thumbnail_key if not set yet.- if (!rows[0].thumbnail_key) patch.thumbnail_key = body.thumb_key;+ // Always write thumbnail_key if not set yet — using the validated key only.+ if (!rows[0].thumbnail_key) patch.thumbnail_key = thumbKey;if (Object.keys(patch).length) {await sql`diff --git a/api/x402-checkout.js b/api/x402-checkout.jsindex 3f0750caf..b46c2bf64 100644--- a/api/x402-checkout.js+++ b/api/x402-checkout.js@@ -38,6 +38,7 @@ import {} from '@solana/spl-token';import { cors, json, method, readJson, wrap, error } from './_lib/http.js';import { parse } from './_lib/validate.js';+import { limits, clientIp } from './_lib/rate-limit.js';import {NETWORK_SOLANA_MAINNET,NETWORK_SOLANA_DEVNET,@@ -46,6 +47,32 @@ import {const SOLANA_RPC = process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com';const SOLANA_DEVNET_RPC = process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com';+// Short-lived caches so repeated prepare calls don't re-issue identical RPC+// round-trips. Mint decimals are effectively immutable; a blockhash is valid for+// ~60-90s on Solana, so a few seconds of reuse cuts redundant traffic without+// handing out a stale-enough blockhash for the buyer's signed tx to fail.+const MINT_DECIMALS_TTL_MS = 5 * 60 * 1000;+const BLOCKHASH_TTL_MS = 8 * 1000;+const mintDecimalsCache = new Map(); // `${rpc}:${mint}` -> { decimals, at }+const blockhashCache = new Map(); // rpc -> { blockhash, at }++async function getMintDecimals(conn, rpc, mint) {+ const key = `${rpc}:${mint.toBase58()}`;+ const hit = mintDecimalsCache.get(key);+ if (hit && Date.now() - hit.at < MINT_DECIMALS_TTL_MS) return hit.decimals;+ const info = await getMint(conn, mint);+ mintDecimalsCache.set(key, { decimals: info.decimals, at: Date.now() });+ return info.decimals;+}++async function getRecentBlockhash(conn, rpc) {+ const hit = blockhashCache.get(rpc);+ if (hit && Date.now() - hit.at < BLOCKHASH_TTL_MS) return hit.blockhash;+ const { blockhash } = await conn.getLatestBlockhash('confirmed');+ blockhashCache.set(rpc, { blockhash, at: Date.now() });+ return blockhash;+}+const acceptSchema = z.object({scheme: z.literal('exact'),network: z.string().min(1).max(80),@@ -108,6 +135,12 @@ function rpcFor(network) {}async function handlePrepare(req, res) {+ // Per-IP rate limit: prepare fans out to multiple Solana RPC round-trips, so+ // throttle anonymous callers to stop quota-drain / cost amplification against+ // the (potentially paid) upstream RPC.+ const rl = await limits.x402PayIp(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many prepare requests');+const body = parse(prepareSchema, await readJson(req));const { accept, buyer } = body;if (!isSolanaNetwork(accept.network)) {@@ -119,7 +152,8 @@ async function handlePrepare(req, res) {);}- const conn = new Connection(rpcFor(accept.network), 'confirmed');+ const rpc = rpcFor(accept.network);+ const conn = new Connection(rpc, 'confirmed');const mint = new PublicKey(accept.asset);const payTo = new PublicKey(accept.payTo);const feePayer = new PublicKey(accept.extra.feePayer);@@ -140,7 +174,7 @@ async function handlePrepare(req, res) {TOKEN_PROGRAM_ID,ASSOCIATED_TOKEN_PROGRAM_ID,);- const mintInfo = await getMint(conn, mint);+ const mintDecimals = await getMintDecimals(conn, rpc, mint);const ixs = [ComputeBudgetProgram.setComputeUnitLimit({ units: 60_000 }),@@ -166,13 +200,13 @@ async function handlePrepare(req, res) {receiverAta,buyerPubkey,amount,- mintInfo.decimals,+ mintDecimals,[],TOKEN_PROGRAM_ID,),);- const { blockhash } = await conn.getLatestBlockhash('confirmed');+ const blockhash = await getRecentBlockhash(conn, rpc);const message = new TransactionMessage({payerKey: feePayer,recentBlockhash: blockhash,diff --git a/mcp-server/package.json b/mcp-server/package.jsonindex 00db6f7d6..611275036 100644--- a/mcp-server/package.json+++ b/mcp-server/package.json@@ -70,6 +70,7 @@"colyseus": "0.17.10","ethers": "^6.16.0","short-uuid": "6.0.3",- "zod": "^3.23.8"+ "zod": "^3.23.8",+ "zod-to-json-schema": "3.25.2"}}diff --git a/mcp-server/src/index.js b/mcp-server/src/index.jsindex bb0bf51ae..a361dc651 100755--- a/mcp-server/src/index.js+++ b/mcp-server/src/index.js@@ -11,6 +11,15 @@// node mcp-server/src/index.js//// Or wire into Claude Desktop / Cursor as documented in README.md.+//+// Testability: `buildServer()` constructs and returns the fully-registered+// McpServer WITHOUT connecting the stdio transport and WITHOUT requiring any+// runtime payment env — tool registration (names/descriptions/schemas) is+// secret-free. Only an actual paid tool *invocation* requires+// MCP_SVM_PAYMENT_ADDRESS (enforced lazily inside `paid()`). The stdio boot in+// `main()` runs only when this file is the process entry point.++import { pathToFileURL } from 'node:url';import { McpServer } from '@modelcontextprotocol/sdk/server/mcp.js';import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';@@ -28,54 +37,72 @@ import { buildAgenCListTasksTool } from './tools/agenc-list-tasks.js';import { buildAgenCGetTaskTool } from './tools/agenc-get-task.js';import { buildAgenCGetAgentTool } from './tools/agenc-get-agent.js';-async function main() {- // Force the shared x402 resource server to initialize before any tool is- // registered — this fetches /supported from each facilitator so verify- // + settle don't pay that cost on the first paid call.- await getResourceServer();- const initErr = getLastFacilitatorInitError();- if (initErr) {- console.error(`[mcp-server] facilitator init returned warnings: ${initErr.message}`);- }+const SERVER_INSTRUCTIONS =+ 'Paid x402 MCP tools from three.ws. Each tool quotes its USDC price in its description. ' ++ 'Tool calls without an x402 payment payload in _meta return a PaymentRequired structuredContent ' ++ '(v2 MCP transport spec). Tools cover: 3D avatar generation (text_to_avatar), ' ++ 'ENS + SNS name resolution ' ++ '(ens_sns_resolve), agent-to-agent delegation (agent_delegate_action), token sentiment pulse ' ++ '(sentiment_pulse), pose generation (get_pose_seed), Solana token snapshots (pump_snapshot), ' ++ 'ERC-8004 agent reputation (agent_reputation), Solana vanity address mining ' ++ '(vanity_grinder, upto-priced), and AgenC coordination protocol reads — ' ++ 'task discovery, task status + lifecycle, and agent registry lookup ' ++ '(agenc_list_tasks, agenc_get_task, agenc_get_agent).';- const server = new McpServer({- name: '3d-agent-mcp',- version: '1.0.0',- }, {- // Declare full tools capability so clients on the strict MCP 2025-06-18- // spec know we don't push tools/list_changed notifications (our tool- // surface is fixed per-process). `resources` + `logging` left- // undeclared because we don't ship resource or logging APIs over this- // transport; declaring them empty would mislead clients into calling- // resources/list and getting a method-not-found.- capabilities: { tools: { listChanged: false } },- instructions:- 'Paid x402 MCP tools from three.ws. Each tool quotes its USDC price in its description. ' +- 'Tool calls without an x402 payment payload in _meta return a PaymentRequired structuredContent ' +- '(v2 MCP transport spec). Tools cover: 3D avatar generation (text_to_avatar), ' +- 'ENS + SNS name resolution ' +- '(ens_sns_resolve), agent-to-agent delegation (agent_delegate_action), token sentiment pulse ' +- '(sentiment_pulse), pose generation (get_pose_seed), Solana token snapshots (pump_snapshot), ' +- 'ERC-8004 agent reputation (agent_reputation), Solana vanity address mining ' +- '(vanity_grinder, upto-priced), and AgenC coordination protocol reads — ' +- 'task discovery, task status + lifecycle, and agent registry lookup ' +- '(agenc_list_tasks, agenc_get_task, agenc_get_agent).',- });+// Every tool builder. Each returns a descriptor+// { name, title, description, inputSchema (Zod shape), handler }. None of these+// require payment env — the env requirement is deferred to the first paid call.+const TOOL_BUILDERS = [+ buildTextToAvatarTool,+ buildEnsSnsResolveTool,+ buildAgentDelegateActionTool,+ buildSentimentPulseTool,+ buildPoseSeedTool,+ buildPumpSnapshotTool,+ buildAgentReputationTool,+ buildVanityGrinderTool,+ buildAgenCListTasksTool,+ buildAgenCGetTaskTool,+ buildAgenCGetAgentTool,+];- const tools = await Promise.all([- buildTextToAvatarTool(),- buildEnsSnsResolveTool(),- buildAgentDelegateActionTool(),- buildSentimentPulseTool(),- buildPoseSeedTool(),- buildPumpSnapshotTool(),- buildAgentReputationTool(),- buildVanityGrinderTool(),- buildAgenCListTasksTool(),- buildAgenCGetTaskTool(),- buildAgenCGetAgentTool(),- ]);+/**+ * Build every tool descriptor. Side-effect-free w.r.t. payment env and the+ * stdio transport — safe to call from tests to enumerate the tool surface.+ *+ * @returns {Promise<Array<{name:string,title:string,description:string,inputSchema:object,handler:Function}>>}+ */+export async function buildTools() {+ return Promise.all(TOOL_BUILDERS.map((build) => build()));+}++/**+ * Construct and return a fully-registered McpServer WITHOUT connecting any+ * transport and WITHOUT requiring runtime payment env. Tool registration+ * (names/descriptions/schemas) works with no secrets; only an actual paid tool+ * invocation requires MCP_SVM_PAYMENT_ADDRESS.+ *+ * @returns {Promise<McpServer>}+ */+export async function buildServer() {+ const server = new McpServer(+ {+ name: '3d-agent-mcp',+ version: '1.0.0',+ },+ {+ // Declare full tools capability so clients on the strict MCP 2025-06-18+ // spec know we don't push tools/list_changed notifications (our tool+ // surface is fixed per-process). `resources` + `logging` left+ // undeclared because we don't ship resource or logging APIs over this+ // transport; declaring them empty would mislead clients into calling+ // resources/list and getting a method-not-found.+ capabilities: { tools: { listChanged: false } },+ instructions: SERVER_INSTRUCTIONS,+ },+ );+ const tools = await buildTools();for (const t of tools) {server.registerTool(t.name,@@ -88,13 +115,41 @@ async function main() {);}+ return server;+}++/**+ * Connect the server to stdio. Runs only as the process entry point. Eagerly+ * warms the shared x402 resource server so the first paid call doesn't pay the+ * /supported fetch cost, then connects the StdioServerTransport.+ */+async function main() {+ // Force the shared x402 resource server to initialize before any tool is+ // invoked — this fetches /supported from each facilitator so verify + settle+ // don't pay that cost on the first paid call.+ await getResourceServer();+ const initErr = getLastFacilitatorInitError();+ if (initErr) {+ console.error(`[mcp-server] facilitator init returned warnings: ${initErr.message}`);+ }++ const server = await buildServer();const transport = new StdioServerTransport();await server.connect(transport);// Log to stderr so the stdout channel stays clean for MCP JSON-RPC frames.- console.error(`[mcp-server] ready — ${tools.length} paid tools registered over stdio`);+ console.error('[mcp-server] ready — paid tools registered over stdio');}-main().catch((err) => {- console.error(`[mcp-server] fatal: ${err.stack || err.message || err}`);- process.exit(1);-});+// Run the stdio boot ONLY when this file is the process entry point. Importing+// the module for tests (or to reuse buildServer/buildTools) must NOT connect a+// transport or require payment env.+const isEntryPoint =+ Boolean(process.argv[1]) && import.meta.url === pathToFileURL(process.argv[1]).href;++if (isEntryPoint) {+ main().catch((err) => {+ // One clean, actionable line to stderr — never a raw multi-line stack.+ console.error(`mcp-server: ${err?.message || err}`);+ process.exit(1);+ });+}diff --git a/mcp-server/src/tools/agenc-get-agent.js b/mcp-server/src/tools/agenc-get-agent.jsindex a9cabe73e..34abb5915 100644--- a/mcp-server/src/tools/agenc-get-agent.js+++ b/mcp-server/src/tools/agenc-get-agent.js@@ -9,7 +9,8 @@ import { PublicKey } from '@solana/web3.js';import { createHash } from 'node:crypto';import { deriveAgentPda, getAgent } from '@tetsuo-ai/sdk';-import { paid } from '../payments.js';+import { paid, toolError } from '../payments.js';+import { jsonSchemaFromZod } from './_shared.js';import {getAgenCClient,parsePubkey,@@ -34,36 +35,27 @@ function resolveAgentId(input) {return Uint8Array.from(createHash('sha256').update(s, 'utf8').digest());}-const inputJsonSchema = {- type: 'object',- properties: {- agentPda: {- type: 'string',- description: 'Base58 agent account PDA. Mutually exclusive with agentId.',- minLength: 32,- maxLength: 44,- },- agentId: {- type: 'string',- description: '32-byte agent id as 64-char hex, "0x"-prefixed hex, or any UTF-8 label (SHA-256 hashed).',- minLength: 1,- maxLength: 256,- },- cluster: {- type: 'string',- enum: ['mainnet', 'devnet'],- description: 'Solana cluster. Defaults to mainnet.',- },- },- additionalProperties: false,-};-+// Single source of truth: Zod shape carries descriptions + bounds + cluster+// enum; JSON Schema derived. (No required fields — the handler enforces+// "agentPda OR agentId".)const inputZodShape = {- agentPda: z.string().min(32).max(44).optional(),- agentId: z.string().min(1).max(256).optional(),- cluster: z.enum(['mainnet', 'devnet']).optional(),+ agentPda: z+ .string()+ .min(32)+ .max(44)+ .describe('Base58 agent account PDA. Mutually exclusive with agentId.')+ .optional(),+ agentId: z+ .string()+ .min(1)+ .max(256)+ .describe('32-byte agent id as 64-char hex, "0x"-prefixed hex, or any UTF-8 label (SHA-256 hashed).')+ .optional(),+ cluster: z.enum(['mainnet', 'devnet']).describe('Solana cluster. Defaults to mainnet.').optional(),};+const inputJsonSchema = jsonSchemaFromZod(inputZodShape);+export async function buildAgenCGetAgentTool() {const handler = await paid({@@ -98,11 +90,7 @@ export async function buildAgenCGetAgentTool() {} else if (agentId) {pda = deriveAgentPda(resolveAgentId(agentId), client.programId);} else {- return {- ok: false,- error: 'missing_input',- message: 'Provide either agentPda or agentId.',- };+ return toolError('missing_input', 'Provide either agentPda or agentId.');}const agent = await getAgent(client.program, pda);diff --git a/mcp-server/src/tools/agenc-get-task.js b/mcp-server/src/tools/agenc-get-task.jsindex 2ed9d37a4..588e749d6 100644--- a/mcp-server/src/tools/agenc-get-task.js+++ b/mcp-server/src/tools/agenc-get-task.js@@ -13,7 +13,8 @@ import {getTaskLifecycleSummary,} from '@tetsuo-ai/sdk';-import { paid } from '../payments.js';+import { paid, toolError } from '../payments.js';+import { jsonSchemaFromZod } from './_shared.js';import {getAgenCClient,parsePubkey,@@ -38,48 +39,37 @@ function resolveTaskId(input) {return Uint8Array.from(createHash('sha256').update(s, 'utf8').digest());}-const inputJsonSchema = {- type: 'object',- properties: {- taskPda: {- type: 'string',- description: 'Base58 task account PDA. If omitted, supply creator + taskId.',- minLength: 32,- maxLength: 44,- },- creator: {- type: 'string',- description: 'Base58 task creator wallet (required if taskPda is omitted).',- minLength: 32,- maxLength: 44,- },- taskId: {- type: 'string',- description: '32-byte task id as 64-char hex, "0x"-prefixed hex, or any UTF-8 label (hashed via SHA-256).',- minLength: 1,- maxLength: 256,- },- cluster: {- type: 'string',- enum: ['mainnet', 'devnet'],- description: 'Solana cluster. Defaults to mainnet.',- },- includeLifecycle: {- type: 'boolean',- description: 'When true (default), include the lifecycle event timeline. Set false for a cheaper read.',- },- },- additionalProperties: false,-};-+// Single source of truth: Zod shape carries descriptions + bounds + cluster+// enum; JSON Schema derived. (No required fields — the handler enforces+// "taskPda OR {creator, taskId}".)const inputZodShape = {- taskPda: z.string().min(32).max(44).optional(),- creator: z.string().min(32).max(44).optional(),- taskId: z.string().min(1).max(256).optional(),- cluster: z.enum(['mainnet', 'devnet']).optional(),- includeLifecycle: z.boolean().optional(),+ taskPda: z+ .string()+ .min(32)+ .max(44)+ .describe('Base58 task account PDA. If omitted, supply creator + taskId.')+ .optional(),+ creator: z+ .string()+ .min(32)+ .max(44)+ .describe('Base58 task creator wallet (required if taskPda is omitted).')+ .optional(),+ taskId: z+ .string()+ .min(1)+ .max(256)+ .describe('32-byte task id as 64-char hex, "0x"-prefixed hex, or any UTF-8 label (hashed via SHA-256).')+ .optional(),+ cluster: z.enum(['mainnet', 'devnet']).describe('Solana cluster. Defaults to mainnet.').optional(),+ includeLifecycle: z+ .boolean()+ .describe('When true (default), include the lifecycle event timeline. Set false for a cheaper read.')+ .optional(),};+const inputJsonSchema = jsonSchemaFromZod(inputZodShape);+export async function buildAgenCGetTaskTool() {const handler = await paid({@@ -112,11 +102,7 @@ export async function buildAgenCGetTaskTool() {pda = parsePubkey(taskPda, 'taskPda');} else {if (!creator || !taskId) {- return {- ok: false,- error: 'missing_input',- message: 'Provide either taskPda OR both creator and taskId.',- };+ return toolError('missing_input', 'Provide either taskPda OR both creator and taskId.');}pda = deriveTaskPda(parsePubkey(creator, 'creator'),diff --git a/mcp-server/src/tools/agenc-list-tasks.js b/mcp-server/src/tools/agenc-list-tasks.jsindex e31e49d9e..808e31200 100644--- a/mcp-server/src/tools/agenc-list-tasks.js+++ b/mcp-server/src/tools/agenc-list-tasks.js@@ -11,6 +11,7 @@ import { z } from 'zod';import { getTasksByCreator } from '@tetsuo-ai/sdk';import { paid } from '../payments.js';+import { jsonSchemaFromZod } from './_shared.js';import {getAgenCClient,parsePubkey,@@ -22,30 +23,15 @@ const TOOL_NAME = 'agenc_list_tasks';const TOOL_DESCRIPTION ='List every public AgenC task created by a given Solana wallet. AgenC (agenc.tech, by Tetsuo Corp) is a Solana coordination protocol where agents bid on, claim, and complete tasks with SOL/SPL escrow and optional zero-knowledge settlement. Returns task PDA, state, reward, deadline, worker counts, and reward mint for each task. Specify cluster="devnet" for the dev cluster (program 6UcJzbT...), otherwise mainnet. Paid: $0.001 USDC.';-const inputJsonSchema = {- type: 'object',- properties: {- creator: {- type: 'string',- description: 'Base58 Solana pubkey of the task creator wallet.',- minLength: 32,- maxLength: 44,- },- cluster: {- type: 'string',- enum: ['mainnet', 'devnet'],- description: 'Solana cluster to query. Defaults to mainnet.',- },- },- required: ['creator'],- additionalProperties: false,-};-+// Single source of truth: Zod shape carries descriptions + bounds + cluster+// enum; JSON Schema derived.const inputZodShape = {- creator: z.string().min(32).max(44),- cluster: z.enum(['mainnet', 'devnet']).optional(),+ creator: z.string().min(32).max(44).describe('Base58 Solana pubkey of the task creator wallet.'),+ cluster: z.enum(['mainnet', 'devnet']).describe('Solana cluster to query. Defaults to mainnet.').optional(),};+const inputJsonSchema = jsonSchemaFromZod(inputZodShape);+export async function buildAgenCListTasksTool() {const handler = await paid({diff --git a/mcp-server/src/tools/agent-delegate-action.js b/mcp-server/src/tools/agent-delegate-action.jsindex bcc1a8f14..1c2f4344f 100644--- a/mcp-server/src/tools/agent-delegate-action.js+++ b/mcp-server/src/tools/agent-delegate-action.js@@ -12,7 +12,8 @@import { z } from 'zod';-import { paid } from '../payments.js';+import { paid, toolError } from '../payments.js';+import { jsonSchemaFromZod } from './_shared.js';const TOOL_NAME = 'agent_delegate_action';const TOOL_DESCRIPTION =@@ -23,26 +24,23 @@ function env(k, def) {return v && String(v).trim() ? String(v).trim() : def;}-const inputJsonSchema = {- type: 'object',- properties: {- agentId: { type: 'string', description: 'three.ws agent id (UUID).', minLength: 1, maxLength: 120 },- message: { type: 'string', minLength: 1, maxLength: 4000 },- model: {- type: 'string',- description: 'Optional Claude model override (e.g. claude-sonnet-4-6). Must be in the allowlist.',- },- },- required: ['agentId', 'message'],- additionalProperties: false,-};-+// Single source of truth: Zod shape carries descriptions + bounds; JSON Schema+// derived. The prior hand-written JSON Schema left `model` with no bounds; the+// Zod (min 1, max 100) is stricter and now wins, surfacing those bounds in the+// advertised schema too.const inputZodShape = {- agentId: z.string().min(1).max(120),+ agentId: z.string().min(1).max(120).describe('three.ws agent id (UUID).'),message: z.string().min(1).max(4000),- model: z.string().min(1).max(100).optional(),+ model: z+ .string()+ .min(1)+ .max(100)+ .describe('Optional Claude model override (e.g. claude-sonnet-4-6). Must be in the allowlist.')+ .optional(),};+const inputJsonSchema = jsonSchemaFromZod(inputZodShape);+export async function buildAgentDelegateActionTool() {const handler = await paid({@@ -74,15 +72,14 @@ export async function buildAgentDelegateActionTool() {body: JSON.stringify({ agentId, message, model }),});} catch (err) {- return { ok: false, error: 'upstream_unreachable', message: err?.message || 'fetch failed' };+ return toolError('upstream_unreachable', err?.message || 'fetch failed');}const data = await res.json().catch(() => null);if (!res.ok || !data || data.ok === false) {- return {- ok: false,- error: data?.code || data?.error || 'agent_delegate_failed',- message: data?.message || `endpoint returned ${res.status}`,- };+ return toolError(+ data?.code || data?.error || 'agent_delegate_failed',+ data?.message || `endpoint returned ${res.status}`,+ );}return data;},diff --git a/mcp-server/src/tools/ens-sns-resolve.js b/mcp-server/src/tools/ens-sns-resolve.jsindex a92dd42fc..1cc5b4f23 100644--- a/mcp-server/src/tools/ens-sns-resolve.js+++ b/mcp-server/src/tools/ens-sns-resolve.js@@ -17,7 +17,8 @@import { ethers } from 'ethers';import { z } from 'zod';-import { paid } from '../payments.js';+import { paid, toolError } from '../payments.js';+import { jsonSchemaFromZod } from './_shared.js';const TOOL_NAME = 'ens_sns_resolve';const TOOL_DESCRIPTION =@@ -100,24 +101,17 @@ async function resolveSns(name) {};}-const inputJsonSchema = {- type: 'object',- properties: {- name: {- type: 'string',- description: 'Name to resolve (e.g. "vitalik.eth", "bonfida.sol", or bare "vitalik" which is tried in both).',- minLength: 1,- maxLength: 253,- },- },- required: ['name'],- additionalProperties: false,-};-+// Single source of truth: Zod shape with description + bounds; JSON Schema derived.const inputZodShape = {- name: z.string().min(1).max(253),+ name: z+ .string()+ .min(1)+ .max(253)+ .describe('Name to resolve (e.g. "vitalik.eth", "bonfida.sol", or bare "vitalik" which is tried in both).'),};+const inputJsonSchema = jsonSchemaFromZod(inputZodShape);+export async function buildEnsSnsResolveTool() {const handler = await paid({@@ -143,7 +137,7 @@ export async function buildEnsSnsResolveTool() {if (isEns) tasks.push(['ens', resolveEns(trimmed).catch((e) => ({ error: e?.message || 'ens failed' }))]);if (isSol) tasks.push(['sns', resolveSns(trimmed).catch((e) => ({ error: e?.message || 'sns failed' }))]);if (!isEns && !isSol) {- return { ok: false, error: 'invalid_name', message: 'name does not look like a .eth, .sol, or bare label' };+ return toolError('invalid_name', 'name does not look like a .eth, .sol, or bare label');}const results = await Promise.all(tasks.map((t) => t[1]));const out = { ok: false, input: trimmed, ens: null, sns: null };diff --git a/mcp-server/src/tools/sentiment-pulse.js b/mcp-server/src/tools/sentiment-pulse.jsindex 12fd59f61..4126026a2 100644--- a/mcp-server/src/tools/sentiment-pulse.js+++ b/mcp-server/src/tools/sentiment-pulse.js@@ -79,11 +79,10 @@ export async function buildSentimentPulseTool() {}const data = await res.json().catch(() => null);if (!res.ok || !data || data.ok === false) {- return {- ok: false,- error: data?.code || data?.error || 'sentiment_failed',- message: data?.message || `endpoint returned ${res.status}`,- };+ return toolError(+ data?.code || data?.error || 'sentiment_failed',+ data?.message || `endpoint returned ${res.status}`,+ );}return data;},diff --git a/pages/extension-privacy.html b/pages/extension-privacy.htmlindex 1b3571c4a..51fc70782 100644--- a/pages/extension-privacy.html+++ b/pages/extension-privacy.html@@ -19,7 +19,7 @@</style></head><body>- <div id="nav-root"></div>+ <div id="nav-container"></div><div class="legal-wrap"><h1>Privacy Policy</h1><p class="updated">three.ws Walk Avatar Chrome Extension · Last updated 2026-05-25</p>@@ -64,7 +64,7 @@<h2>Contact</h2><p>Questions? Email <a href="mailto:[email protected]">[email protected]</a> or visit <a href="https://three.ws">three.ws</a>.</p></div>- <script type="module" src="/public/nav.js"></script>+ <script type="module" src="/nav.js"></script><script src="/brand.js" defer></script></body></html>diff --git a/pages/extension-terms.html b/pages/extension-terms.htmlindex fe0c60236..6ccb20121 100644--- a/pages/extension-terms.html+++ b/pages/extension-terms.html@@ -19,7 +19,7 @@</style></head><body>- <div id="nav-root"></div>+ <div id="nav-container"></div><div class="legal-wrap"><h1>Terms of Service</h1><p class="updated">three.ws Walk Avatar Chrome Extension · Last updated 2026-05-25</p>@@ -49,7 +49,7 @@<h2>Contact</h2><p><a href="mailto:[email protected]">[email protected]</a></p></div>- <script type="module" src="/public/nav.js"></script>+ <script type="module" src="/nav.js"></script><script src="/brand.js" defer></script></body></html>diff --git a/pages/pump-dashboard.html b/pages/pump-dashboard.htmlindex a4a98d0fb..ad9e774a9 100644--- a/pages/pump-dashboard.html+++ b/pages/pump-dashboard.html@@ -25,6 +25,7 @@<link rel="stylesheet" href="/fonts/fonts.css" /><link rel="stylesheet" href="/pump-dashboard.css" /><link rel="stylesheet" href="/mobile.css" />+ <script defer src="/nav.js"></script><script defer src="/footer-newsletter.js"></script><script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script><style>@@ -44,65 +45,7 @@<body class="home-page pump-dashboard-page"><a href="#pd-main" class="h-skip-link">Skip to main content</a>- <header>- <h1>- <a href="/" aria-label="three.ws home"- ><img class="wordmark-logo" src="/three.svg" alt="" aria-hidden="true" /><span- class="wordmark-dot"- aria-hidden="true"- ></span- >three.ws</a- >- </h1>- <nav class="home-nav" aria-label="Primary">- <ul class="nav-root" role="menubar">- <li class="nav-item nav-has-menu" role="none">- <button type="button" class="nav-trigger" aria-haspopup="true" aria-expanded="false" role="menuitem">- Build<span class="nav-caret" aria-hidden="true">▾</span>- </button>- <ul class="nav-menu" role="menu" aria-label="Build">- <li role="none"><a href="/create" role="menuitem"><span class="nav-mi-title">Create agent</span><span class="nav-mi-sub">Avatar + brain wizard</span></a></li>- <li role="none"><a href="/app" role="menuitem"><span class="nav-mi-title">Viewer</span><span class="nav-mi-sub">Drag-and-drop GLB</span></a></li>- <li role="none"><a href="/validation" role="menuitem"><span class="nav-mi-title">glTF Validator</span><span class="nav-mi-sub">Khronos spec check</span></a></li>- </ul>- </li>- <li role="none"><a href="/discover" role="menuitem">Discover</a></li>- <li class="nav-item nav-has-menu" role="none">- <button type="button" class="nav-trigger" aria-haspopup="true" aria-expanded="false" role="menuitem">- Solana<span class="nav-caret" aria-hidden="true">▾</span>- </button>- <ul class="nav-menu" role="menu" aria-label="Solana">- <li role="none"><a href="/pumpfun" role="menuitem"><span class="nav-mi-title">Pump.fun stream</span><span class="nav-mi-sub">Mint agent tokens</span></a></li>- <li role="none"><a href="/vanity-wallet" role="menuitem"><span class="nav-mi-title">Vanity wallet</span><span class="nav-mi-sub">Grind a Solana address</span></a></li>- <li role="none"><a href="/pump-live" role="menuitem"><span class="nav-mi-title">Live launches</span><span class="nav-mi-sub">Real-time mint feed</span></a></li>- <li role="none"><a href="/pump-dashboard" role="menuitem" aria-current="page"><span class="nav-mi-title">Pump Dashboard</span><span class="nav-mi-sub">Watches · scanner · quotes</span></a></li>- <li role="none"><a href="/docs#solana" role="menuitem"><span class="nav-mi-title">Solana SDK</span><span class="nav-mi-sub">Attestations + agent-kit</span></a></li>- </ul>- </li>- <li class="nav-item nav-has-menu" role="none">- <button type="button" class="nav-trigger" aria-haspopup="true" aria-expanded="false" role="menuitem">- Embed<span class="nav-caret" aria-hidden="true">▾</span>- </button>- <ul class="nav-menu" role="menu" aria-label="Embed">- <li role="none"><a href="/studio" role="menuitem"><span class="nav-mi-title">Widget Studio</span><span class="nav-mi-sub">Pick avatar → copy snippet</span></a></li>- <li role="none"><a href="/docs#embedding" role="menuitem"><span class="nav-mi-title">Embed docs</span><span class="nav-mi-sub">iframe + oEmbed</span></a></li>- </ul>- </li>- <li class="nav-item" role="none"><a href="/marketplace" role="menuitem">Marketplace</a></li>- <li class="nav-item" role="none"><a href="/chat" role="menuitem">Chat</a></li>- <li class="nav-item" role="none"><a href="/tutorials" role="menuitem">Tutorials</a></li>- <li class="nav-item" id="home-nav-my-agents-li" role="none" hidden>- <a href="/my-agents" id="home-nav-my-agents" role="menuitem">My Agents</a>- </li>- <li class="nav-item" id="home-nav-user-li" role="none" hidden>- <a href="/dashboard" id="home-nav-user" class="nav-user" role="menuitem"></a>- </li>- <li class="nav-item" role="none">- <a href="/login" class="nav-cta" id="home-nav-cta" role="menuitem">Get started</a>- </li>- </ul>- </nav>- </header>+ <header><div id="nav-container"></div></header><div class="pd-app" id="pd-main"><aside class="pd-sidebar" id="pd-sidebar">@@ -2847,42 +2790,6 @@state.monitorInterval = setInterval(pollMonitorStats, 10000);setInterval(updateUptime, 1000);});-- // Auth-aware nav CTA (matches the pattern used on the rest of the site)- (function () {- try {- const raw = localStorage.getItem('3dagent:auth-hint');- if (!raw) return;- const { authed, name } = JSON.parse(raw);- if (!authed) return;- const cta = $('home-nav-cta');- if (cta) { cta.textContent = 'Dashboard'; cta.href = '/dashboard'; }- const myAgentsLi = $('home-nav-my-agents-li');- if (myAgentsLi) myAgentsLi.hidden = false;- const userLi = $('home-nav-user-li');- const userEl = $('home-nav-user');- if (userEl && userLi && name) { userEl.textContent = name; userLi.hidden = false; }- } catch {}- })();-- // Dropdown nav (same pattern as tutorials.html)- (function () {- const triggers = document.querySelectorAll('.home-nav .nav-trigger');- if (!triggers.length) return;- function closeAll(except) {- triggers.forEach((t) => { if (t !== except) t.setAttribute('aria-expanded', 'false'); });- }- triggers.forEach((trigger) => {- trigger.addEventListener('click', (e) => {- e.stopPropagation();- const open = trigger.getAttribute('aria-expanded') === 'true';- closeAll(open ? null : trigger);- trigger.setAttribute('aria-expanded', open ? 'false' : 'true');- });- });- document.addEventListener('click', (e) => { if (!e.target.closest('.home-nav')) closeAll(null); });- document.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeAll(null); });- })();</script><script src="/footer.js" defer></script>diff --git a/pages/tutorial.html b/pages/tutorial.htmlindex a0ae40d5d..c9d389310 100644--- a/pages/tutorial.html+++ b/pages/tutorial.html@@ -35,6 +35,7 @@<link rel="stylesheet" href="/mobile.css" /><script src="https://cdn.jsdelivr.net/npm/[email protected]/marked.min.js"></script><script src="https://cdnjs.cloudflare.com/ajax/libs/highlight.js/11.9.0/highlight.min.js"></script>+ <script defer src="/nav.js"></script><script defer src="/footer-newsletter.js"></script><script defer src="/tutorials-manifest.js"></script><script type="module" src="https://ajax.googleapis.com/ajax/libs/model-viewer/4.0.0/model-viewer.min.js"></script>@@ -567,69 +568,7 @@<div class="cursor" id="cursor" aria-hidden="true"></div><a href="#main-content" class="h-skip-link">Skip to main content</a>- <header>- <h1>- <a href="/" aria-label="three.ws home"- ><img class="wordmark-logo" src="/three.svg" alt="" aria-hidden="true" /><span- class="wordmark-dot"- aria-hidden="true"- ></span- >three.ws</a- >- </h1>- <nav class="home-nav" aria-label="Primary">- <ul class="nav-root" role="menubar">- <li class="nav-item nav-has-menu" role="none">- <button type="button" class="nav-trigger" aria-haspopup="true" aria-expanded="false" role="menuitem">- Build<span class="nav-caret" aria-hidden="true">▾</span>- </button>- <ul class="nav-menu" role="menu" aria-label="Build">- <li role="none"><a href="/create" role="menuitem"><span class="nav-mi-title">Create agent</span><span class="nav-mi-sub">Avatar + brain wizard</span></a></li>- <li role="none"><a href="/app" role="menuitem"><span class="nav-mi-title">Viewer</span><span class="nav-mi-sub">Drag-and-drop GLB</span></a></li>- <li role="none"><a href="/validation" role="menuitem"><span class="nav-mi-title">glTF Validator</span><span class="nav-mi-sub">Khronos spec check</span></a></li>- </ul>- </li>- <li role="none"><a href="/discover" role="menuitem">Discover</a></li>- <li class="nav-item nav-has-menu" role="none">- <button type="button" class="nav-trigger" aria-haspopup="true" aria-expanded="false" role="menuitem">- Solana<span class="nav-caret" aria-hidden="true">▾</span>- </button>- <ul class="nav-menu" role="menu" aria-label="Solana">- <li role="none"><a href="/pumpfun" role="menuitem"><span class="nav-mi-title">Pump.fun stream</span><span class="nav-mi-sub">Mint agent tokens</span></a></li>- <li role="none"><a href="/vanity-wallet" role="menuitem"><span class="nav-mi-title">Vanity wallet</span><span class="nav-mi-sub">Grind a Solana address</span></a></li>- <li role="none"><a href="/eth-vanity" role="menuitem"><span class="nav-mi-title">ETH vanity (CREATE2)</span><span class="nav-mi-sub">Grind a smart-contract address</span></a></li>- <li role="none"><a href="/strategy-lab" role="menuitem"><span class="nav-mi-title">Strategy Lab</span><span class="nav-mi-sub">DCA + subscriptions</span></a></li>- <li role="none"><a href="/pump-live" role="menuitem"><span class="nav-mi-title">Live launches</span><span class="nav-mi-sub">Real-time mint feed</span></a></li>- <li role="none"><a href="/pump-dashboard" role="menuitem"><span class="nav-mi-title">Pump Dashboard</span><span class="nav-mi-sub">Watches · scanner · quotes</span></a></li>- <li role="none"><a href="/docs#solana" role="menuitem"><span class="nav-mi-title">Solana SDK</span><span class="nav-mi-sub">Attestations + agent-kit</span></a></li>- </ul>- </li>- <li class="nav-item nav-has-menu" role="none">- <button type="button" class="nav-trigger" aria-haspopup="true" aria-expanded="false" role="menuitem">- Embed<span class="nav-caret" aria-hidden="true">▾</span>- </button>- <ul class="nav-menu" role="menu" aria-label="Embed">- <li role="none"><a href="/studio" role="menuitem"><span class="nav-mi-title">Widget Studio</span><span class="nav-mi-sub">Pick avatar → copy snippet</span></a></li>- <li role="none"><a href="/artifact" role="menuitem"><span class="nav-mi-title">Artifact viewer</span><span class="nav-mi-sub">Claude artifact bundle</span></a></li>- <li role="none"><a href="/docs#embedding" role="menuitem"><span class="nav-mi-title">Embed docs</span><span class="nav-mi-sub">iframe + oEmbed</span></a></li>- <li role="none"><a href="/docs#web-component" role="menuitem"><span class="nav-mi-title"><agent-3d></span><span class="nav-mi-sub">Web component reference</span></a></li>- </ul>- </li>- <li class="nav-item" role="none"><a href="/marketplace" role="menuitem">Marketplace</a></li>- <li class="nav-item" role="none"><a href="/chat" role="menuitem">Chat</a></li>- <li class="nav-item" role="none"><a href="/tutorials" role="menuitem" aria-current="page">Tutorials</a></li>- <li class="nav-item" id="home-nav-my-agents-li" role="none" hidden>- <a href="/my-agents" id="home-nav-my-agents" role="menuitem">My Agents</a>- </li>- <li class="nav-item" id="home-nav-user-li" role="none" hidden>- <a href="/dashboard" id="home-nav-user" class="nav-user" role="menuitem"></a>- </li>- <li class="nav-item" role="none">- <a href="/login" class="nav-cta" id="home-nav-cta" role="menuitem">Get started</a>- </li>- </ul>- </nav>- </header>+ <header><div id="nav-container"></div></header><main id="main-content"><div class="tdoc-hero" id="tdoc-hero" hidden>@@ -788,52 +727,6 @@});})();- // Auth-aware nav CTA- (function () {- try {- const raw = localStorage.getItem('3dagent:auth-hint');- if (!raw) return;- const { authed, name } = JSON.parse(raw);- if (!authed) return;- const cta = document.getElementById('home-nav-cta');- if (cta) { cta.textContent = 'Dashboard'; cta.href = '/dashboard'; }- const myAgentsLi = document.getElementById('home-nav-my-agents-li');- if (myAgentsLi) myAgentsLi.hidden = false;- const userLi = document.getElementById('home-nav-user-li');- const userEl = document.getElementById('home-nav-user');- if (userEl && userLi && name) { userEl.textContent = name; userLi.hidden = false; }- } catch (_) {}- })();-- // Dropdown nav- (function () {- const triggers = document.querySelectorAll('.home-nav .nav-trigger');- if (!triggers.length) return;- function closeAll(except) {- triggers.forEach((t) => { if (t !== except) t.setAttribute('aria-expanded', 'false'); });- }- triggers.forEach((trigger) => {- trigger.addEventListener('click', (e) => {- e.stopPropagation();- const open = trigger.getAttribute('aria-expanded') === 'true';- closeAll(open ? null : trigger);- trigger.setAttribute('aria-expanded', open ? 'false' : 'true');- if (!open) trigger.nextElementSibling?.querySelector('a')?.focus();- });- const menu = trigger.nextElementSibling;- if (!menu) return;- menu.addEventListener('keydown', (e) => {- const items = Array.from(menu.querySelectorAll('a'));- const idx = items.indexOf(document.activeElement);- if (e.key === 'ArrowDown') { e.preventDefault(); items[(idx + 1) % items.length]?.focus(); }- else if (e.key === 'ArrowUp') { e.preventDefault(); items[(idx - 1 + items.length) % items.length]?.focus(); }- else if (e.key === 'Escape') { trigger.setAttribute('aria-expanded', 'false'); trigger.focus(); }- });- });- document.addEventListener('click', (e) => { if (!e.target.closest('.home-nav')) closeAll(null); });- document.addEventListener('keydown', (e) => { if (e.key === 'Escape') closeAll(null); });- })();-// ── Tutorial viewer ──────────────────────────────────────────function currentSlug() {const m = location.pathname.match(/^\/tutorials\/([a-z0-9-]+)\/?$/);diff --git a/src/game/home-town.js b/src/game/home-town.jsindex 2aeb4482e..07d08667c 100644--- a/src/game/home-town.js+++ b/src/game/home-town.js@@ -17,9 +17,11 @@ export const HOME_TOWN = {name: 'three.ws',symbol: 'three',image: 'https://ipfs.io/ipfs/bafybeihe22b5sxr3ihnxt7pregfieyteqvubqhik3j3y4bbx243xlqjw3q',- // The signature look for the home town: the Neon Expanse, whose cyan/magenta- // neon over deep indigo matches the platform's monochrome-with-accent brand.- biome: 'alien',+ // The signature look for the home town: Dust Gulch, an old-west frontier town —+ // a packed-dirt square ringed by false-front storefronts (saloon, bank,+ // sheriff…) under a low golden-hour sun, with a water tower on the skyline and+ // tumbleweeds drifting the mesa. See the `frontier` biome in world-env.js.+ biome: 'frontier',official: true,};diff --git a/src/game/world-env.js b/src/game/world-env.jsindex a8abd8ca8..9621c6f43 100644--- a/src/game/world-env.js+++ b/src/game/world-env.js@@ -20,6 +20,7 @@ import {HemisphereLight, DirectionalLight, AmbientLight,Mesh, MeshStandardMaterial, MeshBasicMaterial,CircleGeometry, RingGeometry, CylinderGeometry, ConeGeometry, IcosahedronGeometry,+ BoxGeometry, TorusGeometry,GridHelper, CanvasTexture,} from 'three';@@ -102,6 +103,20 @@ const BIOMES = [hill: 0x3fae9a, trunk: 0x7a5a36, leafA: 0x3f9a54, leafB: 0x5fbf66,flora: 'palm', density: 30,},+ {+ // Old-west frontier town — a dusty main square ringed by false-front+ // storefronts under a low golden-hour sun that throws the long shadows of+ // every porch post and water tower across the packed-dirt plaza. `town`+ // flags the storefront/prop builder below; sagebrush + the odd saguaro+ // dress the mesa band beyond.+ id: 'frontier', label: 'Dust Gulch',+ sky: ['#6b78a2', '#d6b483', '#f5e6c0'], fog: '#e9d6aa', fogNear: 72, fogFar: 300,+ hemi: [0xffe9c2, 0xa9824c, 0.82], ambient: 0.32,+ sun: { color: 0xffce86, intensity: 2.35, elevation: 17, azimuth: 252 },+ ground: 0xc9a974, plaza: 0xb6985e, grid: 0x8a6f42, ring: 0xd98a38,+ hill: 0xc09a60, trunk: 0x6a4a2e, leafA: 0x7d8a4c, leafB: 0x97a560,+ flora: 'sagebrush', density: 18, town: 'frontier',+ },];// Map any seed to a biome. Exposed so the UI can name the world the player is in.@@ -229,6 +244,253 @@ function makePalm(g, mats, rand) {return palm;}+// Frontier scrub: a low cluster of dusty sage mounds, with the odd tall saguaro+// rising out of it. Reuses the cactus body so the band reads as high-desert.+function makeSagebrush(g, mats, rand) {+ const clump = new Group();+ const mounds = 2 + Math.floor(rand() * 3);+ for (let i = 0; i < mounds; i++) {+ const bush = new Mesh(g.bush, rand() > 0.5 ? mats.leafA : mats.leafB);+ const s = 0.5 + rand() * 0.7;+ bush.scale.set(s, s * (0.5 + rand() * 0.3), s);+ bush.position.set((rand() - 0.5) * 1.8, s * 0.32, (rand() - 0.5) * 1.8);+ bush.castShadow = true;+ clump.add(bush);+ }+ // ~1 in 4 clumps anchors a saguaro for a recognisable western silhouette.+ if (rand() > 0.74) {+ const body = new Mesh(g.cactus, mats.leafB);+ body.position.y = 1.6; body.castShadow = true;+ clump.add(body);+ const arm = new Mesh(g.cactusArm, mats.leafB);+ arm.position.set(0.6, 1.9, 0); arm.rotation.z = 0.5; arm.castShadow = true;+ clump.add(arm);+ }+ return clump;+}++// --- Frontier town ---------------------------------------------------------+// A painted board sign for a storefront's false front. Unlit so the lettering+// stays legible at dusk; weathered cream serif on dark stained wood.+function frontierSignTexture(label) {+ const c = document.createElement('canvas');+ c.width = 256; c.height = 80;+ const x = c.getContext('2d');+ x.fillStyle = '#2b1d12'; x.fillRect(0, 0, 256, 80);+ x.strokeStyle = '#5a3f27'; x.lineWidth = 6; x.strokeRect(4, 4, 248, 72);+ x.fillStyle = '#e9d9b6';+ x.textAlign = 'center'; x.textBaseline = 'middle';+ let size = 38;+ do { x.font = `700 ${size}px Georgia, "Times New Roman", serif`; size -= 2; }+ while (x.measureText(label).width > 224 && size > 16);+ x.fillText(label, 128, 44);+ const tex = new CanvasTexture(c);+ tex.colorSpace = SRGBColorSpace;+ return tex;+}++// One false-front storefront, facade on its local +Z so the ring can rotate it+// to face the square. Body + tall flat false front + porch awning on posts ++// door, glass, and a painted sign. Geometry/material are shared (a unit box and+// unit post scaled per part), so a whole street is a handful of buffers.+function makeStorefront(geo, mats, rand, label) {+ const g = new Group();+ const w = 5 + rand() * 3.5, d = 4 + rand() * 2, h = 3 + rand() * 1.4;+ const wood = mats.wood[Math.floor(rand() * mats.wood.length)];++ const body = new Mesh(geo.box, wood);+ body.scale.set(w, h, d); body.position.y = h / 2;+ body.castShadow = true; body.receiveShadow = true; g.add(body);++ // Tall flat false front that hides the roof and carries the sign.+ const ffH = h * (0.5 + rand() * 0.25);+ const ff = new Mesh(geo.box, wood);+ ff.scale.set(w, ffH, 0.3); ff.position.set(0, h + ffH / 2, d / 2 - 0.15);+ ff.castShadow = true; g.add(ff);++ // Shallow shed roof sloping back, just peeking past the false front.+ const roof = new Mesh(geo.box, mats.roof);+ roof.scale.set(w + 0.4, 0.2, d + 0.4); roof.position.set(0, h + 0.05, -0.15);+ roof.rotation.x = -0.07; roof.castShadow = true; g.add(roof);++ // Porch awning over the boardwalk, on two posts.+ const porchD = 1.7;+ const awn = new Mesh(geo.box, mats.roof);+ awn.scale.set(w, 0.16, porchD); awn.position.set(0, h * 0.74, d / 2 + porchD / 2);+ awn.rotation.x = 0.13; awn.castShadow = true; g.add(awn);+ for (const sx of [-1, 1]) {+ const post = new Mesh(geo.post, mats.beam);+ post.scale.set(1, h * 0.74, 1);+ post.position.set(sx * (w / 2 - 0.45), h * 0.37, d / 2 + porchD - 0.25);+ post.castShadow = true; g.add(post);+ }++ // Door + two windows. The saloon glows warm; everyone else has dark glass.+ const door = new Mesh(geo.box, mats.door);+ door.scale.set(1.1, h * 0.62, 0.12); door.position.set(0, h * 0.31, d / 2 + 0.07); g.add(door);+ const winMat = label === 'SALOON' ? mats.litWindow : mats.glass;+ for (const sx of [-1, 1]) {+ const win = new Mesh(geo.box, winMat);+ win.scale.set(1.2, 1.0, 0.12); win.position.set(sx * (w * 0.27), h * 0.6, d / 2 + 0.07); g.add(win);+ }++ // Painted sign across the false front.+ const sign = new Mesh(geo.box, new MeshBasicMaterial({ map: frontierSignTexture(label) }));+ sign.scale.set(Math.min(w * 0.92, 4.8), Math.min(ffH * 0.62, 1.5), 0.14);+ sign.position.set(0, h + ffH * 0.5, d / 2 + 0.02); g.add(sign);++ return g;+}++// A timber water tower: a banded tank on four braced legs under a conic cap —+// the tallest thing on the skyline and the town's signature silhouette.+function makeWaterTower(geo, mats) {+ const g = new Group();+ const legH = 7;+ for (const [sx, sz] of [[-1, -1], [-1, 1], [1, -1], [1, 1]]) {+ const leg = new Mesh(geo.post, mats.beam);+ leg.scale.set(1.1, legH, 1.1);+ leg.position.set(sx * 1.7, legH / 2, sz * 1.7);+ leg.rotation.x = sz * 0.06; leg.rotation.z = -sx * 0.06;+ leg.castShadow = true; g.add(leg);+ }+ // Cross brace.+ const brace = new Mesh(geo.box, mats.beam);+ brace.scale.set(4.6, 0.2, 0.2); brace.position.y = legH * 0.5; g.add(brace);+ const tank = new Mesh(geo.tank, mats.wood[0]);+ tank.position.y = legH + 1.7; tank.castShadow = true; g.add(tank);+ const cap = new Mesh(geo.cap, mats.roof);+ cap.position.y = legH + 3.7; cap.castShadow = true; g.add(cap);+ return g;+}++// Scatter props: barrels, crates, wagon wheels, hitching rails, water troughs —+// the small clutter that turns an empty lot into a lived-in town.+function makeProp(kind, geo, mats, rand) {+ const g = new Group();+ if (kind === 'barrel') {+ const b = new Mesh(geo.barrel, mats.wood[1]);+ b.position.y = 0.5; b.castShadow = true; g.add(b);+ } else if (kind === 'crate') {+ const c = new Mesh(geo.box, mats.crate);+ const s = 0.7 + rand() * 0.4; c.scale.setScalar(s); c.position.y = s / 2;+ c.rotation.y = rand() * Math.PI; c.castShadow = true; g.add(c);+ } else if (kind === 'wheel') {+ const w = new Mesh(geo.wheel, mats.beam);+ w.position.y = 0.55; w.rotation.x = Math.PI / 2; w.rotation.z = (rand() - 0.5) * 0.4;+ w.castShadow = true; g.add(w);+ for (let i = 0; i < 4; i++) {+ const spoke = new Mesh(geo.box, mats.beam);+ spoke.scale.set(0.07, 0.07, 1); spoke.position.y = 0.55;+ spoke.rotation.x = Math.PI / 2; spoke.rotation.y = (i / 4) * Math.PI;+ g.add(spoke);+ }+ } else if (kind === 'hitch') {+ for (const sx of [-1, 1]) {+ const post = new Mesh(geo.post, mats.beam);+ post.scale.set(0.8, 1.1, 0.8); post.position.set(sx * 1.1, 0.55, 0);+ post.castShadow = true; g.add(post);+ }+ const rail = new Mesh(geo.box, mats.beam);+ rail.scale.set(2.6, 0.16, 0.16); rail.position.y = 1.0; g.add(rail);+ } else if (kind === 'trough') {+ const t = new Mesh(geo.box, mats.wood[2]);+ t.scale.set(2.2, 0.6, 0.8); t.position.y = 0.3; t.castShadow = true; g.add(t);+ const water = new Mesh(geo.box, mats.water);+ water.scale.set(2.0, 0.05, 0.6); water.position.y = 0.56; g.add(water);+ }+ return g;+}++// Build the whole frontier town into `root`: a ring of storefronts facing the+// square, a water tower, scattered props, and a couple of tumbleweeds that the+// caller animates. Everything sits OUTSIDE playRadius so it frames the plaza+// without ever blocking a player.+function buildFrontierTown(root, rand, playRadius) {+ const between = (a, b) => a + (b - a) * rand();+ const mats = {+ wood: [+ new MeshStandardMaterial({ color: 0x6e5238, roughness: 1, metalness: 0 }),+ new MeshStandardMaterial({ color: 0x8a5a3c, roughness: 1, metalness: 0 }),+ new MeshStandardMaterial({ color: 0x9a7a4e, roughness: 1, metalness: 0 }),+ new MeshStandardMaterial({ color: 0x8a3b2e, roughness: 1, metalness: 0 }), // barn red+ new MeshStandardMaterial({ color: 0x4d6b66, roughness: 1, metalness: 0 }), // faded teal+ ],+ beam: new MeshStandardMaterial({ color: 0x4a3624, roughness: 1, metalness: 0 }),+ roof: new MeshStandardMaterial({ color: 0x3a2c1e, roughness: 1, metalness: 0 }),+ door: new MeshStandardMaterial({ color: 0x2a1d12, roughness: 0.9, metalness: 0 }),+ crate: new MeshStandardMaterial({ color: 0xa8824a, roughness: 1, metalness: 0 }),+ glass: new MeshStandardMaterial({ color: 0x1a1612, roughness: 0.4, metalness: 0.1 }),+ litWindow: new MeshBasicMaterial({ color: 0xffb15a }),+ water: new MeshStandardMaterial({ color: 0x3a5a64, roughness: 0.3, metalness: 0.1 }),+ };+ const geo = {+ box: new BoxGeometry(1, 1, 1),+ post: new CylinderGeometry(0.16, 0.18, 1, 8),+ barrel: new CylinderGeometry(0.5, 0.42, 1, 12),+ wheel: new TorusGeometry(0.5, 0.09, 6, 16),+ tank: new CylinderGeometry(2.4, 2.4, 3.4, 18),+ cap: new ConeGeometry(2.9, 1.8, 18),+ bush: new IcosahedronGeometry(1, 0),+ cactus: new CylinderGeometry(0.5, 0.6, 3.2, 8),+ cactusArm: new CylinderGeometry(0.26, 0.3, 1.6, 7),+ };++ // Storefronts around the square. A seeded, shuffled name list keeps every+ // town's row of shops stable per coin but never in the same order twice.+ const NAMES = [+ 'SALOON', 'GENERAL STORE', 'SHERIFF', 'BANK', 'HOTEL', 'LIVERY',+ 'ASSAY OFFICE', 'BARBER', 'GAZETTE', 'TELEGRAPH', 'GUNSMITH', 'TRADING POST',+ 'LAND OFFICE', 'STABLES', 'JAIL', 'POST OFFICE',+ ];+ const names = NAMES.slice();+ for (let i = names.length - 1; i > 0; i--) {+ const j = Math.floor(rand() * (i + 1));+ [names[i], names[j]] = [names[j], names[i]];+ }+ const COUNT = 13;+ for (let i = 0; i < COUNT; i++) {+ // Even spread with a little jitter, leaving a clear gap at the spawn-facing+ // south (the open road into town) so the entrance never walls a player in.+ const a = (i / COUNT) * Math.PI * 2 + between(-0.06, 0.06) + 0.24;+ const R = playRadius + 5.5 + between(0, 3);+ const shop = makeStorefront(geo, mats, rand, names[i % names.length]);+ shop.position.set(Math.cos(a) * R, 0, Math.sin(a) * R);+ shop.rotation.y = Math.atan2(-Math.cos(a), -Math.sin(a)); // facade faces the square+ root.add(shop);+ }++ // Water tower off one corner of the square.+ const ta = 0.9;+ const tower = makeWaterTower(geo, mats);+ tower.position.set(Math.cos(ta) * (playRadius + 14), 0, Math.sin(ta) * (playRadius + 14));+ root.add(tower);++ // Clutter scattered through the band between the boundary and the storefronts.+ const KINDS = ['barrel', 'crate', 'wheel', 'hitch', 'trough', 'barrel', 'crate'];+ for (let i = 0; i < 26; i++) {+ const a = rand() * Math.PI * 2;+ const R = playRadius + between(2.5, 12);+ const prop = makeProp(KINDS[Math.floor(rand() * KINDS.length)], geo, mats, rand);+ prop.position.set(Math.cos(a) * R, 0, Math.sin(a) * R);+ prop.rotation.y = rand() * Math.PI * 2;+ root.add(prop);+ }++ // A couple of tumbleweeds drifting the mesa band beyond the town — pure life.+ // Returned to the caller so they roll on the same animator clock as the world.+ const tumbleMat = new MeshStandardMaterial({ color: 0x8a6e44, roughness: 1, metalness: 0, flatShading: true, wireframe: true });+ const tumbleGeo = new IcosahedronGeometry(0.9, 1);+ const tumbles = [];+ for (let i = 0; i < 2; i++) {+ const tw = new Mesh(tumbleGeo, tumbleMat);+ tw.castShadow = true;+ root.add(tw);+ tumbles.push({ mesh: tw, phase: i * 0.5, lane: playRadius + 16 + i * 6, speed: 6 + i * 1.5 });+ }+ return tumbles;+}+export function createWorldEnvironment(scene, renderer, playRadius = 58, opts = {}) {const seed = (typeof opts.seed === 'number' ? opts.seed : seedFromString(opts.mint)) >>> 0;// A curated world can pin its archetype by id; everyone else draws theirs from@@ -330,10 +592,12 @@ export function createWorldEnvironment(scene, renderer, playRadius = 58, opts =crystal: new ConeGeometry(0.6, 1, 5),palmTrunk: new CylinderGeometry(0.22, 0.36, 5.2, 7),frond: new ConeGeometry(0.5, 3.4, 4),+ bush: new IcosahedronGeometry(1, 0),};const builder = {conifer: makeConifer, snowpine: (g, m, r) => makeConifer(g, m, r, true),cactus: makeCactus, deadtree: makeDeadtree, crystal: makeCrystal, palm: makePalm,+ sagebrush: makeSagebrush,}[biome.flora] || makeConifer;const crystals = [];@@ -357,6 +621,23 @@ export function createWorldEnvironment(scene, renderer, playRadius = 58, opts =});}+ // --- Town dressing -----------------------------------------------------+ // Biomes that flag a `town` get built structures ringing the square. The+ // frontier town's tumbleweeds roll on the shared animator clock, looping a+ // long chord through the mesa band and spinning as they go.+ if (biome.town === 'frontier') {+ const tumbles = buildFrontierTown(root, rand, playRadius);+ const SPAN = 90; // length of the roll before it loops back+ animators.push((t, dt) => {+ for (const tw of tumbles) {+ const travel = ((t * tw.speed) + tw.phase * SPAN) % SPAN;+ tw.mesh.position.set(travel - SPAN / 2, 0.9, tw.lane);+ tw.mesh.rotation.z -= dt * tw.speed * 0.9; // roll matches its drift+ tw.mesh.rotation.x += dt * 0.6;+ }+ });+ }+// --- Live-market reactivity --------------------------------------------// The boundary ring is the world's heartbeat: a slow breathing pulse is the// baseline, but a trade can kick it to a colour (green on a buy, red on a