Skip to content

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

feat: mesh-forge MCP tool, bulk-launch admin, agent-strategy 200 on empty

nirholasbb158efcfebf
diff --git a/api/admin/bulk-launch.js b/api/admin/bulk-launch.js
new file mode 100644
index 000000000..2e2832f5a
--- /dev/null
+++ b/api/admin/bulk-launch.js
@@ -0,0 +1,492 @@
+// GET /api/admin/bulk-launch — SSE stream that deploys agents on-chain as
+// Metaplex Core assets inside the three.ws Agent Collection (NOT pump.fun).
+//
+// Each agent becomes a real Solana Metaplex Core NFT — its on-chain identity:
+// • minted into the "three.ws Agents" Collection (authority-managed by three.ws),
+// • owned by the agent's own custodial Solana wallet (so the agent holds its
+// identity and can transfer/sell it later),
+// • carrying an on-chain Attributes plugin (platform, links, $THREE) written
+// into the asset account itself, plus an enforced 5% Royalties plugin,
+// • pointing at a pinned manifest (Metaplex token-metadata + agent-manifest/0.1).
+//
+// One funded wallet does everything: it is the collection authority, the mint
+// fee payer, and — on first run — the deployer of the Collection account. The
+// agent wallets need no SOL (the owner of a Core asset does not sign the mint).
+//
+// Query params:
+// network mainnet | devnet (default: mainnet)
+// limit max agents to process this run (default: 100, max 500)
+// dry_run true | false (default: false) — skips all on-chain steps
+//
+// SSE events:
+// init { total, network, funder, funder_balance_sol, dry_run }
+// collection { address, source: env|db|deployed, authority, signature? }
+// wallet { agent_id, name, owner }
+// deployed { agent_id, name, asset, owner, metadata_uri, signature, explorer_url, avatar_thumb }
+// skip { agent_id, name, reason }
+// error { agent_id, name, error }
+// paused { funder_balance_sol, deployed, reason }
+// done { deployed, errors, skipped }
+
+import { Keypair, LAMPORTS_PER_SOL } from '@solana/web3.js';
+import bs58 from 'bs58';
+import { CID } from 'multiformats/cid';
+import * as raw from 'multiformats/codecs/raw';
+import { sha256 } from 'multiformats/hashes/sha2';
+import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';
+import { mplCore, create, createCollection, ruleSet } from '@metaplex-foundation/mpl-core';
+import {
+ generateSigner,
+ publicKey as umiPublicKey,
+ createSignerFromKeypair,
+ signerIdentity,
+} from '@metaplex-foundation/umi';
+import { sql } from '../_lib/db.js';
+import { cors, method, error } from '../_lib/http.js';
+import { requireAdmin } from '../_lib/admin.js';
+import { env } from '../_lib/env.js';
+import { putObject, publicUrl as r2PublicUrl } from '../_lib/r2.js';
+import {
+ buildAgentManifest,
+ buildAgentOnchainAttributes,
+ agentRoyaltyConfig,
+ agentHomeUrl,
+} from '../_lib/three-brand.js';
+import { getAgentCollection } from '../_lib/solana-collection.js';
+import { solanaRpcEndpoints } from '../_lib/solana/connection.js';
+import { generateSolanaAgentWallet } from '../_lib/agent-wallet.js';
+import { publishFeedEvent } from '../_lib/feed.js';
+
+// Genesis-hash chain refs (CAIP-2) for the onchain block, mirroring the
+// interactive deploy path in api/agents/onchain/[action].js.
+const SOLANA_REFS = {
+ mainnet: '5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp',
+ devnet: 'EtWTRABZaYq6iMfeYKouRu166VU2xqa1',
+};
+
+// A Core asset minted into a collection costs ~0.0037 SOL of rent + fee. Pause
+// the run if the funder can't cover one more mint with a little headroom.
+const EST_MINT_LAMPORTS = Math.floor(0.004 * LAMPORTS_PER_SOL);
+// Deploying the Collection account on first run costs ~0.003 SOL of rent + fee.
+const EST_COLLECTION_LAMPORTS = Math.floor(0.005 * LAMPORTS_PER_SOL);
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+function sse(res, event, data) {
+ if (!res.writableEnded) {
+ res.write(`event: ${event}\ndata: ${JSON.stringify(data)}\n\n`);
+ }
+}
+
+function explorerUrl(asset, network) {
+ const suffix = network === 'devnet' ? '?cluster=devnet' : '';
+ return `https://solscan.io/account/${asset}${suffix}`;
+}
+
+// Pin the manifest. Try web3.storage for true IPFS pinning; otherwise fall back
+// to R2 while computing the real CIDv1 (raw codec, sha2-256) from the bytes, so
+// the content is verifiable IPFS content-addressing and the returned HTTPS URL
+// is real and resolvable — never a stub. Mirrors api/agents/onchain/[action].js.
+async function pinManifest(manifest, agentId) {
+ const bytes = Buffer.from(JSON.stringify(manifest), 'utf-8');
+ const token = process.env.WEB3_STORAGE_TOKEN;
+ if (token) {
+ try {
+ const r = await fetch('https://api.web3.storage/upload', {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${token}` },
+ body: bytes,
+ });
+ if (r.ok) {
+ const data = await r.json();
+ if (data.cid) return { cid: data.cid, uri: `ipfs://${data.cid}` };
+ }
+ } catch {
+ /* fall through to R2 */
+ }
+ }
+ const digest = await sha256.digest(bytes);
+ const cid = CID.create(1, raw.code, digest).toString();
+ const key = `agent-manifests/bulk/${agentId}.json`;
+ await putObject({ key, body: bytes, contentType: 'application/json' });
+ return { cid, uri: r2PublicUrl(key) };
+}
+
+// Resolve the three.ws Agent Collection for this network: prefer the env var
+// (keeps the interactive deploy + edit paths aligned), then a persisted setting,
+// then deploy the Collection account on first run and persist its address.
+async function resolveCollection({ umi, authoritySigner, network, dryRun, res }) {
+ const authority = authoritySigner.publicKey.toString();
+
+ const envAddr = getAgentCollection(network);
+ if (envAddr) {
+ sse(res, 'collection', { address: envAddr, source: 'env', authority });
+ return envAddr;
+ }
+
+ await sql`
+ CREATE TABLE IF NOT EXISTS app_settings (
+ key text PRIMARY KEY,
+ value jsonb NOT NULL,
+ updated_at timestamptz NOT NULL DEFAULT now()
+ )
+ `;
+ const settingKey = `solana_agent_collection_${network}`;
+ const [row] = await sql`SELECT value FROM app_settings WHERE key = ${settingKey}`;
+ if (row?.value?.address) {
+ sse(res, 'collection', { address: row.value.address, source: 'db', authority });
+ return row.value.address;
+ }
+
+ if (dryRun) {
+ sse(res, 'collection', { address: null, source: 'none', authority, dry_run: true });
+ return null;
+ }
+
+ // First run for this network: deploy the Collection account, funded +
+ // authority-signed by the funder. Needs ~0.003 SOL of rent + fee.
+ const bal = await umi.rpc.getBalance(authoritySigner.publicKey).then((b) => Number(b.basisPoints)).catch(() => 0);
+ if (bal < EST_COLLECTION_LAMPORTS) {
+ throw new Error(
+ `funder needs ~${(EST_COLLECTION_LAMPORTS / LAMPORTS_PER_SOL).toFixed(3)} SOL to deploy the three.ws Agents collection — top up ${authority} and re-run`,
+ );
+ }
+ const collectionSigner = generateSigner(umi);
+ const collectionUri = `${env.APP_ORIGIN}/api/agents/solana-collection-metadata?network=${network}`;
+ const result = await createCollection(umi, {
+ collection: collectionSigner,
+ name: 'three.ws Agents',
+ uri: collectionUri,
+ plugins: [
+ {
+ type: 'Attributes',
+ attributeList: [
+ { key: 'platform', value: 'three.ws' },
+ { key: 'url', value: env.APP_ORIGIN },
+ { key: 'standard', value: 'metaplex-core' },
+ { key: 'schema', value: 'agent-manifest/0.1' },
+ { key: 'chain', value: `solana:${SOLANA_REFS[network]}` },
+ ],
+ },
+ ],
+ }).sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });
+
+ const address = collectionSigner.publicKey.toString();
+ const signature = bs58.encode(result.signature);
+ await sql`
+ INSERT INTO app_settings (key, value)
+ VALUES (${settingKey}, ${JSON.stringify({ address, authority, signature, deployed_at: new Date().toISOString() })}::jsonb)
+ ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value, updated_at = now()
+ `;
+ sse(res, 'collection', { address, source: 'deployed', authority, signature });
+ return address;
+}
+
+export default async function handler(req, res) {
+ if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET'])) return;
+
+ const admin = await requireAdmin(req, res);
+ if (!admin) return;
+
+ const q = req.query ?? {};
+ const network = q.network === 'devnet' ? 'devnet' : 'mainnet';
+ const limit = Math.min(500, Math.max(1, Number(q.limit) || 100));
+ const dryRun = q.dry_run === 'true';
+
+ // One funded wallet is the collection authority, the mint fee payer, and the
+ // collection deployer. Prefer the canonical collection-authority key so the
+ // interactive deploy/edit paths co-sign with the same authority; fall back to
+ // the launch funder key.
+ const signerSecret =
+ process.env.SOLANA_AGENT_COLLECTION_AUTHORITY_KEY || process.env.LAUNCH_FUNDER_SECRET;
+ if (!signerSecret) {
+ return error(
+ res,
+ 500,
+ 'config_error',
+ 'Set SOLANA_AGENT_COLLECTION_AUTHORITY_KEY (or LAUNCH_FUNDER_SECRET) to the funded authority wallet secret.',
+ );
+ }
+ let authorityKeypair;
+ try {
+ authorityKeypair = Keypair.fromSecretKey(bs58.decode(signerSecret));
+ } catch {
+ return error(res, 500, 'config_error', 'authority/funder secret is not a valid base58 keypair');
+ }
+
+ // SSE headers
+ res.statusCode = 200;
+ res.setHeader('content-type', 'text/event-stream; charset=utf-8');
+ res.setHeader('cache-control', 'no-cache, no-transform');
+ res.setHeader('connection', 'keep-alive');
+ res.setHeader('x-accel-buffering', 'no');
+
+ let aborted = false;
+ req.on('close', () => { aborted = true; });
+
+ // Umi with the authority as identity (payer) + signer.
+ const rpcUrl = solanaRpcEndpoints(network)[0];
+ const umi = createUmi(rpcUrl).use(mplCore());
+ const authoritySigner = createSignerFromKeypair(
+ umi,
+ umi.eddsa.createKeypairFromSecretKey(authorityKeypair.secretKey),
+ );
+ umi.use(signerIdentity(authoritySigner));
+ const authorityPk = authoritySigner.publicKey;
+
+ async function funderLamports() {
+ try {
+ const bal = await umi.rpc.getBalance(authorityPk);
+ return Number(bal.basisPoints);
+ } catch {
+ return 0;
+ }
+ }
+
+ const startBalance = await funderLamports();
+
+ // Agents needing an on-chain identity on this network. mainnet uses the
+ // canonical meta.sol_mint_address (what every read path keys on); devnet test
+ // runs are isolated under meta.devnet so they never block a real mainnet mint.
+ const agents =
+ network === 'mainnet'
+ ? await sql`
+ SELECT ai.id, ai.user_id, ai.name, ai.description, ai.meta, ai.avatar_id,
+ av.thumbnail_key, av.storage_key
+ FROM agent_identities ai
+ LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL
+ WHERE ai.deleted_at IS NULL
+ AND ai.meta->>'sol_mint_address' IS NULL
+ ORDER BY ai.created_at ASC
+ LIMIT ${limit}
+ `
+ : await sql`
+ SELECT ai.id, ai.user_id, ai.name, ai.description, ai.meta, ai.avatar_id,
+ av.thumbnail_key, av.storage_key
+ FROM agent_identities ai
+ LEFT JOIN avatars av ON av.id = ai.avatar_id AND av.deleted_at IS NULL
+ WHERE ai.deleted_at IS NULL
+ AND ai.meta->'devnet'->>'sol_mint_address' IS NULL
+ ORDER BY ai.created_at ASC
+ LIMIT ${limit}
+ `;
+
+ sse(res, 'init', {
+ total: agents.length,
+ network,
+ funder: authorityPk.toString(),
+ funder_balance_sol: startBalance / LAMPORTS_PER_SOL,
+ dry_run: dryRun,
+ });
+
+ // Resolve (or deploy) the collection up front.
+ let collectionAddr;
+ try {
+ collectionAddr = await resolveCollection({ umi, authoritySigner, network, dryRun, res });
+ } catch (err) {
+ sse(res, 'error', { agent_id: null, name: 'collection', error: `collection: ${err.message}` });
+ sse(res, 'done', { deployed: 0, errors: 1, skipped: 0 });
+ return res.end();
+ }
+ const collectionPk = collectionAddr ? umiPublicKey(collectionAddr) : null;
+
+ let deployed = 0;
+ let errors = 0;
+ let skipped = 0;
+
+ for (const agent of agents) {
+ if (aborted) break;
+ const agentName = agent.name || 'Agent';
+ let meta = { ...(agent.meta || {}) };
+
+ // 1. Owner = the agent's own custodial Solana wallet (generate if missing).
+ // The owner does not sign the mint, so it needs no SOL.
+ if (!meta.solana_address) {
+ if (!dryRun) {
+ try {
+ const wallet = await generateSolanaAgentWallet();
+ meta = {
+ ...meta,
+ solana_address: wallet.address,
+ encrypted_solana_secret: wallet.encrypted_secret,
+ solana_wallet_source: 'bulk_onchain',
+ };
+ await sql`
+ UPDATE agent_identities
+ SET meta = ${JSON.stringify(meta)}::jsonb, updated_at = NOW()
+ WHERE id = ${agent.id}
+ `;
+ } catch (err) {
+ sse(res, 'error', { agent_id: agent.id, name: agentName, error: `wallet: ${err.message}` });
+ errors++;
+ continue;
+ }
+ }
+ sse(res, 'wallet', { agent_id: agent.id, name: agentName, owner: meta.solana_address || '(dry run)' });
+ }
+ const ownerAddress = meta.solana_address;
+
+ // 2. Media + manifest.
+ const image = agent.thumbnail_key ? r2PublicUrl(agent.thumbnail_key) : '';
+ const animationUrl = agent.storage_key ? r2PublicUrl(agent.storage_key) : '';
+ const createdAt = new Date().toISOString();
+
+ if (dryRun) {
+ sse(res, 'deployed', {
+ agent_id: agent.id,
+ name: agentName,
+ asset: '(dry run)',
+ owner: ownerAddress || '(dry run)',
+ metadata_uri: null,
+ signature: null,
+ explorer_url: null,
+ avatar_thumb: image || null,
+ dry_run: true,
+ });
+ deployed++;
+ continue;
+ }
+
+ // 3. Funder balance gate.
+ const bal = await funderLamports();
+ if (bal < EST_MINT_LAMPORTS + 5000) {
+ sse(res, 'paused', {
+ funder_balance_sol: bal / LAMPORTS_PER_SOL,
+ deployed,
+ reason: 'funder wallet is low on SOL — top up and re-run',
+ });
+ break;
+ }
+
+ try {
+ // 4. Pin manifest.
+ const manifest = buildAgentManifest({
+ name: agentName,
+ description: agent.description || '',
+ avatarId: agent.avatar_id || null,
+ image,
+ animationUrl,
+ externalUrl: agentHomeUrl(agent.id),
+ ownerAddress,
+ createdAt,
+ });
+ const { uri: metadataUri } = await pinManifest(manifest, agent.id);
+
+ // 5. Mint the Core asset into the collection.
+ const attributes = buildAgentOnchainAttributes({
+ name: agentName,
+ agentUrl: agentHomeUrl(agent.id),
+ createdAt,
+ });
+ const royalty = agentRoyaltyConfig(ownerAddress);
+ const ownerPk = umiPublicKey(ownerAddress);
+ const assetSigner = generateSigner(umi);
+
+ const createArgs = {
+ asset: assetSigner,
+ owner: ownerPk,
+ name: agentName.slice(0, 32) || 'Agent',
+ uri: metadataUri,
+ plugins: [
+ ...(attributes.length ? [{ type: 'Attributes', attributeList: attributes }] : []),
+ ...(royalty
+ ? [{
+ type: 'Royalties',
+ basisPoints: royalty.basisPoints,
+ creators: royalty.creators.map((c) => ({ address: umiPublicKey(c.address), percentage: c.percentage })),
+ ruleSet: ruleSet('None'),
+ }]
+ : []),
+ ],
+ };
+ if (collectionPk) {
+ createArgs.collection = collectionPk;
+ createArgs.authority = authoritySigner;
+ }
+
+ const result = await create(umi, createArgs).sendAndConfirm(umi, {
+ confirm: { commitment: 'confirmed' },
+ });
+ const asset = assetSigner.publicKey.toString();
+ const signature = bs58.encode(result.signature);
+
+ // 6. Persist the on-chain identity. Mainnet writes the canonical fields
+ // every read path keys on; devnet is isolated under meta.devnet.
+ const onchain = {
+ chain: `solana:${SOLANA_REFS[network]}`,
+ family: 'solana',
+ cluster: network,
+ onchain_id: asset,
+ sol_asset: asset,
+ contract_or_mint: asset,
+ metadata_uri: metadataUri,
+ owner: ownerAddress,
+ custody: true,
+ tx_hash: signature,
+ ...(collectionAddr ? { collection: collectionAddr } : {}),
+ confirmed_at: new Date().toISOString(),
+ };
+ const merged =
+ network === 'mainnet'
+ ? {
+ ...meta,
+ chain_type: 'solana',
+ network,
+ sol_mint_address: asset,
+ ...(collectionAddr ? { collection: collectionAddr, update_authority: 'threews' } : {}),
+ onchain,
+ }
+ : { ...meta, devnet: { sol_mint_address: asset, collection: collectionAddr || null, onchain } };
+
+ await sql`
+ UPDATE agent_identities
+ SET meta = ${JSON.stringify(merged)}::jsonb, updated_at = NOW()
+ WHERE id = ${agent.id}
+ `;
+
+ await sql`
+ INSERT INTO agent_actions (agent_id, type, payload, source_skill)
+ VALUES (
+ ${agent.id},
+ ${'solana.deploy'},
+ ${JSON.stringify({ asset, network, signature, collection: collectionAddr || null, owner: ownerAddress, source: 'bulk_onchain' })}::jsonb,
+ ${'bulk_onchain'}
+ )
+ `.catch(() => {});
+
+ // Truthful on-chain feed event — fired only after the tx confirms.
+ if (network === 'mainnet') {
+ publishFeedEvent({
+ type: 'agent-onchain',
+ ts: Date.now(),
+ actor: agentName,
+ agentId: agent.id,
+ name: agentName,
+ chain: 'Solana',
+ }).catch(() => {});
+ }
+
+ deployed++;
+ sse(res, 'deployed', {
+ agent_id: agent.id,
+ name: agentName,
+ asset,
+ owner: ownerAddress,
+ metadata_uri: metadataUri,
+ signature,
+ explorer_url: explorerUrl(asset, network),
+ avatar_thumb: image || null,
+ });
+ } catch (err) {
+ sse(res, 'error', { agent_id: agent.id, name: agentName, error: `deploy: ${err.message}` });
+ errors++;
+ }
+
+ // ~2 mints/sec — stay well within RPC limits.
+ await sleep(400);
+ }
+
+ sse(res, 'done', { deployed, errors, skipped });
+ res.end();
+}
diff --git a/api/agent-strategy.js b/api/agent-strategy.js
index 528a68930..cde0a201e 100644
--- a/api/agent-strategy.js
+++ b/api/agent-strategy.js
@@ -42,8 +42,9 @@ export default wrap(async (req, res) => {
const rl = await limits.widgetRead(clientIp(req));
if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');
+ // "no strategy set" is a valid empty state, not an error — return null with
+ // 200 so owners viewing an un-configured agent don't generate console 404s.
const strategy = agent.meta?.strategy ?? null;
- if (strategy === null) return error(res, 404, 'not_found', 'no strategy set');
return json(res, 200, { data: { strategy } });
}
diff --git a/mcp-server/README.md b/mcp-server/README.md
index e8d585db1..2ae210dc2 100644
--- a/mcp-server/README.md
+++ b/mcp-server/README.md
@@ -33,6 +33,8 @@ Restart Claude Desktop. The four tools appear immediately — no install step re
| Tool | Price | What it returns |
|------|-------|-----------------|
+| `mesh_forge` | $0.25 | Textured 3D GLB from a text prompt via a chain of specialist models — an IBM Granite "prompt director" rewrites the prompt into an optimized single-subject 3D spec, FLUX renders a reference image, and Microsoft TRELLIS / Tencent Hunyuan3D reconstruct the mesh. Returns the durable `glbUrl`, a three.ws viewer `preview`, the `directedPrompt`, and timing. |
+| `text_to_avatar` | $0.15 | Textured 3D GLB avatar from a text prompt or reference image URLs, driving Replicate (Hunyuan-3D 3.1 by default). Returns the GLB URL, model version, prediction id, and timing. |
| `get_pose_seed` | $0.001 | Deterministic seed + full Euler-rotation pose map (radians) for the three.ws pose-studio mannequin, matched from the in-repo preset library. Includes a `previewUrl` at `https://three.ws/pose?seed=…&preset=…`. |
| `pump_snapshot` | $0.005 | Live token snapshot — USD price (Jupiter), 24h volume + pair (Dexscreener), mint metadata + image (pump.fun frontend-api-v3), and on-chain top-holder distribution (Solana RPC). Adds Helius DAS data when `HELIUS_API_KEY` is set. |
| `agent_reputation` | $0.01 | ERC-8004 reputation: `getReputation`, `getTotalStake`, and the latest `ReputationSubmitted` / `ReputationStaked` events from the canonical ReputationRegistry on the requested chain (default Base). Resolves `agentId` from a wallet address automatically. |
diff --git a/mcp-server/server.json b/mcp-server/server.json
index fa941a2b2..b96ebc0c3 100644
--- a/mcp-server/server.json
+++ b/mcp-server/server.json
@@ -1,7 +1,7 @@
{
"$schema": "https://static.modelcontextprotocol.io/schemas/2025-12-11/server.schema.json",
"name": "io.github.nirholas/3d-agent-mcp",
- "description": "Paid MCP tools for the 3d-agent stack by three.ws — pose generation, pump.fun snapshots, ERC-8004 agent reputation, and a Solana vanity grinder. Settled in USDC on Solana via x402.",
+ "description": "Paid MCP tools for the 3d-agent stack by three.ws — text-to-3D mesh + avatar generation, pose generation, pump.fun snapshots, ERC-8004 agent reputation, and a Solana vanity grinder. Settled in USDC on Solana via x402.",
"repository": {
"url": "https://github.com/nirholas/three.ws",
"source": "github",
diff --git a/mcp-server/src/index.js b/mcp-server/src/index.js
index c6f9ec542..5130450f9 100755
--- a/mcp-server/src/index.js
+++ b/mcp-server/src/index.js
@@ -30,6 +30,7 @@ import { buildPumpSnapshotTool } from './tools/pump-snapshot.js';
import { buildAgentReputationTool } from './tools/agent-reputation.js';
import { buildVanityGrinderTool } from './tools/vanity-grinder.js';
import { buildTextToAvatarTool } from './tools/text-to-avatar.js';
+import { buildMeshForgeTool } from './tools/mesh-forge.js';
import { buildSentimentPulseTool } from './tools/sentiment-pulse.js';
import { buildEnsSnsResolveTool } from './tools/ens-sns-resolve.js';
import { buildAgentDelegateActionTool } from './tools/agent-delegate-action.js';
@@ -41,6 +42,7 @@ 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), ' +
+ 'text-to-3D mesh generation via a Granite-directed model chain (mesh_forge), ' +
'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), ' +
@@ -54,6 +56,7 @@ const SERVER_INSTRUCTIONS =
// require payment env — the env requirement is deferred to the first paid call.
const TOOL_BUILDERS = [
buildTextToAvatarTool,
+ buildMeshForgeTool,
buildEnsSnsResolveTool,
buildAgentDelegateActionTool,
buildSentimentPulseTool,
diff --git a/mcp-server/src/tools/mesh-forge.js b/mcp-server/src/tools/mesh-forge.js
new file mode 100644
index 000000000..5e94895f7
--- /dev/null
+++ b/mcp-server/src/tools/mesh-forge.js
@@ -0,0 +1,301 @@
+// `mesh_forge` — paid MCP tool: text → textured 3D GLB, as a model chain.
+//
+// Pricing: $0.25 USDC, settled `exact` on Solana.
+//
+// This is a thin, x402-gated client over the three.ws production pipeline — it
+// does NOT hold any generation credentials itself. The npx-distributed MCP
+// server can run anywhere; all GPU/LLM work happens on three.ws prod (which
+// holds the Replicate / watsonx keys). The x402 USDC payment is what gates the
+// call.
+//
+// The pipeline is a chain of specialist models, each doing one job:
+// 1. Prompt director (IBM Granite via /api/chat, provider=watsonx) — rewrites
+// the caller's rough idea into an optimized 3D-generation spec (subject,
+// style, materials, single-subject framing). Fail-soft: if the director is
+// unreachable or disabled, the original prompt is forwarded unchanged and
+// `directed:false` is reported — never a fabricated result.
+// 2. Reference synthesis + reconstruction (/api/forge) — FLUX renders a clean
+// reference image, then Microsoft TRELLIS / Tencent Hunyuan3D reconstructs
+// a textured GLB. This tool submits the job and polls to a terminal state.
+// 3. Delivery — returns the durable GLB URL and a three.ws viewer link.
+//
+// Image→3D and auto-rigging are deliberately NOT exposed yet: no public prod
+// endpoint reconstructs an arbitrary caller-supplied image into a riggable mesh
+// today, and this tool never advertises an input it can't honor.
+//
+// Environment (all optional — sensible prod defaults):
+// MESH_FORGE_API_BASE — three.ws origin. Default https://three.ws
+// MESH_FORGE_DIRECTOR — "0" to skip the Granite director stage. Default on.
+// MESH_FORGE_DIRECTOR_MODEL — watsonx model id for direction. Default server default.
+// MESH_FORGE_TIMEOUT_MS — overall reconstruct poll budget. Default 180000.
+// MESH_FORGE_POLL_MS — poll interval. Default 3000.
+
+import { z } from 'zod';
+
+import { paid, toolError } from '../payments.js';
+import { jsonSchemaFromZod } from './_shared.js';
+
+const TOOL_NAME = 'mesh_forge';
+const TOOL_DESCRIPTION =
+ 'Generate a textured 3D GLB model from a text prompt through a chain of specialist models: an IBM Granite "prompt director" rewrites the prompt into an optimized 3D spec, FLUX renders a reference image, and Microsoft TRELLIS / Tencent Hunyuan3D reconstruct the mesh. Returns the GLB URL, a three.ws viewer link, the directed prompt, and timing. Paid: $0.25 USDC.';
+
+const VALID_ASPECT = new Set(['1:1', '4:3', '3:4', '16:9', '9:16']);
+
+function env(k, def) {
+ const v = process.env[k];
+ return v && String(v).trim() ? String(v).trim() : def;
+}
+
+function apiBase() {
+ return env('MESH_FORGE_API_BASE', 'https://three.ws').replace(/\/$/, '');
+}
+
+// The director system instruction. Granite turns a loose idea into a tight,
+// single-subject generation spec — the single biggest lever on mesh quality.
+const DIRECTOR_INSTRUCTION =
+ 'You are a 3D asset art director. Rewrite the user\'s idea into ONE concise prompt for a ' +
+ 'text-to-3D generator. Describe a SINGLE isolated subject on a plain background, naming form, ' +
+ 'materials, color, and surface detail. No scenes, no multiple objects, no text or logos, no ' +
+ 'background environment. Output ONLY the rewritten prompt as a single line — no preamble, no quotes.';
+
+// Drive the deployed /api/chat SSE endpoint with IBM Granite (provider=watsonx)
+// to refine the prompt. Returns the refined prompt string, or null on any
+// failure so the caller can fall back to the original prompt (fail-soft, never
+// fabricated). watsonx is a server-side key on prod; an anonymous caller may
+// request provider:"watsonx" explicitly per api/chat.js routing.
+async function directPrompt(rawPrompt) {
+ const base = apiBase();
+ const model = env('MESH_FORGE_DIRECTOR_MODEL');
+ let res;
+ try {
+ res = await fetch(`${base}/api/chat`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json', accept: 'text/event-stream' },
+ body: JSON.stringify({
+ provider: 'watsonx',
+ ...(model ? { model } : {}),
+ message: `${DIRECTOR_INSTRUCTION}\n\nIdea: ${rawPrompt}`,
+ }),
+ signal: AbortSignal.timeout(30_000),
+ });
+ } catch {
+ return null;
+ }
+ if (!res.ok || !res.body) return null;
+
+ // Collect SSE `data: {type:'chunk',text}` events until `done`/stream end.
+ let acc = '';
+ try {
+ const reader = res.body.getReader();
+ const decoder = new TextDecoder();
+ let buf = '';
+ for (;;) {
+ const { value, done } = await reader.read();
+ if (done) break;
+ buf += decoder.decode(value, { stream: true });
+ const lines = buf.split('\n');
+ buf = lines.pop() ?? '';
+ for (const line of lines) {
+ if (!line.startsWith('data: ')) continue;
+ let evt;
+ try {
+ evt = JSON.parse(line.slice(6));
+ } catch {
+ continue;
+ }
+ if (evt.type === 'chunk' && typeof evt.text === 'string') acc += evt.text;
+ else if (evt.type === 'error') return null;
+ else if (evt.type === 'done') {
+ if (typeof evt.text === 'string' && !acc) acc = evt.text;
+ }
+ }
+ }
+ } catch {
+ return null;
+ }
+
+ const refined = acc.trim().replace(/^["']|["']$/g, '').split('\n')[0].trim();
+ return refined.length >= 3 && refined.length <= 1000 ? refined : null;
+}
+
+async function startForge(prompt, aspect) {
+ const base = apiBase();
+ const res = await fetch(`${base}/api/forge`, {
+ method: 'POST',
+ headers: { 'content-type': 'application/json' },
+ body: JSON.stringify({ prompt, aspect_ratio: aspect }),
+ signal: AbortSignal.timeout(30_000),
+ });
+ const data = await res.json().catch(() => ({}));
+ if (res.status === 503) {
+ const e = new Error(data?.message || 'text-to-3D is not configured on the three.ws deployment');
+ e.code = 'not_configured';
+ throw e;
+ }
+ if (res.status === 429) {
+ const e = new Error(data?.message || 'the 3D generator is busy; try again shortly');
+ e.code = 'rate_limited';
+ e.retryAfter = data?.retry_after;
+ throw e;
+ }
+ if (!res.ok || !data?.job_id) {
+ const e = new Error(data?.message || `forge returned ${res.status}`);
+ e.code = 'provider_error';
+ throw e;
+ }
+ return data; // { job_id, creation_id, status, preview_image_url, ... }
+}
+
+async function pollForge(jobId, { timeoutMs, intervalMs }) {
+ const base = apiBase();
+ const deadline = Date.now() + timeoutMs;
+ let last = null;
+ while (Date.now() < deadline) {
+ let res;
+ try {
+ res = await fetch(`${base}/api/forge?job=${encodeURIComponent(jobId)}`, {
+ headers: { accept: 'application/json' },
+ signal: AbortSignal.timeout(Math.max(intervalMs * 3, 15_000)),
+ });
+ } catch (err) {
+ if (err?.name === 'AbortError' || err?.name === 'TimeoutError') {
+ await new Promise((r) => setTimeout(r, intervalMs));
+ continue;
+ }
+ const e = new Error(`forge poll failed: ${err?.message || err}`);
+ e.code = 'provider_error';
+ throw e;
+ }
+ const data = await res.json().catch(() => ({}));
+ if (!res.ok) {
+ const e = new Error(data?.message || `forge poll returned ${res.status}`);
+ e.code = 'provider_error';
+ throw e;
+ }
+ last = data;
+ if (data.status === 'done' && data.glb_url) return data;
+ if (data.status === 'failed') {
+ const e = new Error(data.error || 'generation failed');
+ e.code = 'generation_failed';
+ throw e;
+ }
+ await new Promise((r) => setTimeout(r, intervalMs));
+ }
+ return { ...(last || {}), _timedOut: true };
+}
+
+const inputZodShape = {
+ prompt: z
+ .string()
+ .min(3)
+ .max(1000)
+ .describe('Natural-language description of the single object to model, e.g. "a worn leather armchair".'),
+ aspect_ratio: z
+ .enum(['1:1', '4:3', '3:4', '16:9', '9:16'])
+ .describe('Reference image aspect ratio. Default 1:1 (best for isolated objects).')
+ .optional(),
+ direct: z
+ .boolean()
+ .describe('Run the IBM Granite prompt-director stage to optimize the prompt before generation. Default true.')
+ .optional(),
+};
+
+const inputJsonSchema = jsonSchemaFromZod(inputZodShape);
+
+export async function buildMeshForgeTool() {
+ const handler = await paid(
+ {
+ toolName: TOOL_NAME,
+ description: TOOL_DESCRIPTION,
+ scheme: 'exact',
+ priceUsd: '$0.25',
+ inputSchema: inputJsonSchema,
+ example: { prompt: 'a worn leather armchair, brass studs', aspect_ratio: '1:1' },
+ outputExample: {
+ ok: true,
+ glbUrl: 'https://three.ws/cdn/creations/abc123/mesh.glb',
+ preview: 'https://three.ws/viewer?src=https%3A%2F%2Fthree.ws%2Fcdn%2F...',
+ prompt: 'a worn leather armchair, brass studs',
+ directedPrompt: 'A single worn brown leather wingback armchair with brass stud trim...',
+ directed: true,
+ jobId: 'k7m2q9x4',
+ creationId: 'abc123',
+ referenceImageUrl: 'https://replicate.delivery/.../ref.png',
+ durationMs: 96000,
+ },
+ },
+ async ({ prompt, aspect_ratio, direct }) => {
+ const aspect = VALID_ASPECT.has(aspect_ratio) ? aspect_ratio : '1:1';
+ const started = Date.now();
+
+ // Stage 1 — Granite prompt director (fail-soft, opt-out).
+ const runDirector = direct !== false && env('MESH_FORGE_DIRECTOR', '1') !== '0';
+ let directedPrompt = null;
+ if (runDirector) directedPrompt = await directPrompt(prompt);
+ const effectivePrompt = directedPrompt || prompt;
+
+ // Stage 2 — submit reference synthesis + reconstruction.
+ let job;
+ try {
+ job = await startForge(effectivePrompt, aspect);
+ } catch (err) {
+ return toolError(err.code || 'provider_error', err.message, {
+ ...(err.retryAfter ? { retryAfter: err.retryAfter } : {}),
+ });
+ }
+
+ // Stage 3 — poll to a terminal state. 3D reconstruction is slow; budget
+ // generously but bound it so the caller never hangs forever.
+ const timeoutMs = Number(env('MESH_FORGE_TIMEOUT_MS', '180000'));
+ const intervalMs = Number(env('MESH_FORGE_POLL_MS', '3000'));
+ let final;
+ try {
+ final = await pollForge(job.job_id, { timeoutMs, intervalMs });
+ } catch (err) {
+ return toolError(err.code || 'provider_error', err.message, {
+ jobId: job.job_id,
+ creationId: job.creation_id ?? null,
+ durationMs: Date.now() - started,
+ });
+ }
+
+ const durationMs = Date.now() - started;
+
+ if (final._timedOut) {
+ return toolError('timeout', `reconstruction did not finish within ${timeoutMs}ms`, {
+ jobId: job.job_id,
+ creationId: job.creation_id ?? null,
+ status: final.status || 'running',
+ resumeUrl: `${apiBase()}/api/forge?job=${job.job_id}`,
+ durationMs,
+ });
+ }
+
+ const glbUrl = final.glb_url;
+ const preview = `${apiBase()}/viewer?src=${encodeURIComponent(glbUrl)}`;
+
+ return {
+ ok: true,
+ glbUrl,
+ preview,
+ prompt,
+ directedPrompt: directedPrompt || null,
+ directed: Boolean(directedPrompt),
+ jobId: job.job_id,
+ creationId: final.creation_id ?? job.creation_id ?? null,
+ referenceImageUrl: job.preview_image_url ?? null,
+ durable: Boolean(final.durable),
+ durationMs,
+ fetchedAt: new Date().toISOString(),
+ };
+ },
+ );
+
+ return {
+ name: TOOL_NAME,
+ title: 'Text → 3D mesh ($0.25)',
+ description: TOOL_DESCRIPTION,
+ inputSchema: inputZodShape,
+ handler,
+ };
+}
diff --git a/pages/bulk-launch.html b/pages/bulk-launch.html
new file mode 100644
index 000000000..70d81e0cf
--- /dev/null
+++ b/pages/bulk-launch.html
@@ -0,0 +1,602 @@
+<!DOCTYPE html>
+<html lang="en">
+<head>
+<meta charset="UTF-8">
+<meta name="viewport" content="width=device-width, initial-scale=1.0">
+<title>Bulk Launch · three.ws Admin</title>
+<style>
+ :root {
+ --green: #00ff88;
+ --gold: #f5c542;
+ --red: #ff4444;
+ --bg: #080c10;
+ --surface: #111620;
+ --border: #1e2a3a;
+ --text: #c8d8e8;
+ --muted: #5a7080;
+ }
+ * { margin: 0; padding: 0; box-sizing: border-box; }
+ body {
+ background: var(--bg);
+ color: var(--text);
+ font-family: 'SF Mono', 'Fira Code', monospace;
+ font-size: 13px;
+ min-height: 100vh;
+ }
+
+ header {
+ display: flex;
+ align-items: center;
+ gap: 16px;
+ padding: 20px 32px;
+ border-bottom: 1px solid var(--border);
+ background: var(--surface);
+ }
+ header h1 {
+ font-size: 18px;
+ font-weight: 600;
+ color: #fff;
+ letter-spacing: -0.5px;
+ }
+ header .badge {
+ font-size: 11px;
+ background: #1a2a1a;
+ color: var(--green);
+ border: 1px solid var(--green);
+ border-radius: 4px;
+ padding: 2px 8px;
+ }
+
+ .layout {
+ display: grid;
+ grid-template-columns: 320px 1fr;
+ gap: 0;
+ height: calc(100vh - 65px);
+ }
+
+ .sidebar {
+ background: var(--surface);
+ border-right: 1px solid var(--border);
+ padding: 24px;
+ display: flex;
+ flex-direction: column;
+ gap: 20px;
+ overflow-y: auto;
+ }
+
+ .stat-block {
+ background: var(--bg);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 16px;
+ }
+ .stat-block label {
+ display: block;
+ font-size: 11px;
+ color: var(--muted);
+ text-transform: uppercase;
+ letter-spacing: 0.8px;
+ margin-bottom: 6px;
+ }
+ .stat-block .value {
+ font-size: 22px;
+ font-weight: 700;
+ color: #fff;
+ }
+ .stat-block .value.green { color: var(--green); }
+ .stat-block .value.gold { color: var(--gold); }
+ .stat-block .value.red { color: var(--red); }
+
+ .funder-addr {
+ background: var(--bg);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 16px;
+ }
+ .funder-addr label {
+ display: block;
+ font-size: 11px;
+ color: var(--muted);
+ text-transform: uppercase;
+ letter-spacing: 0.8px;
+ margin-bottom: 8px;
+ }
+ .funder-addr .addr {
+ word-break: break-all;
+ font-size: 12px;
+ color: var(--green);
+ cursor: pointer;
+ user-select: all;
+ line-height: 1.5;
+ }
+ .funder-addr .addr:hover { opacity: 0.8; }
+ .funder-addr .hint {
+ margin-top: 8px;
+ font-size: 11px;
+ color: var(--muted);
+ }
+
+ .controls {
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ }
+ .controls select, .controls input {
+ background: var(--bg);
+ border: 1px solid var(--border);
+ border-radius: 6px;
+ color: var(--text);
+ padding: 8px 12px;
+ font-family: inherit;
+ font-size: 13px;
+ width: 100%;
+ }
+ .controls label {
+ font-size: 11px;
+ color: var(--muted);
+ margin-bottom: 4px;
+ display: block;
+ }
+
+ .btn {
+ background: var(--green);
+ color: #000;
+ border: none;
+ border-radius: 6px;
+ padding: 11px 20px;
+ font-size: 13px;
+ font-weight: 700;
+ font-family: inherit;
+ cursor: pointer;
+ width: 100%;
+ transition: opacity 0.15s;
+ }
+ .btn:hover { opacity: 0.85; }
+ .btn:disabled { opacity: 0.4; cursor: not-allowed; }
+ .btn.danger { background: var(--red); color: #fff; }
+ .btn.secondary { background: transparent; border: 1px solid var(--border); color: var(--text); }
+
+ .log-panel {
+ background: var(--bg);
+ border: 1px solid var(--border);
+ border-radius: 8px;
+ padding: 12px;
+ font-size: 11px;
+ color: var(--muted);
+ max-height: 120px;
+ overflow-y: auto;
+ line-height: 1.6;
+ }
+ .log-panel .log-line { margin-bottom: 2px; }
+ .log-panel .log-line.ok { color: var(--green); }
+ .log-panel .log-line.err { color: var(--red); }
+ .log-panel .log-line.info { color: var(--gold); }
+
+ /* ── Feed ────────────────────────────────────────────────── */
+ .feed {
+ padding: 24px;
+ overflow-y: auto;
+ display: flex;
+ flex-direction: column;
+ gap: 0;
+ }
+
+ .feed-header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ margin-bottom: 20px;
+ }
+ .feed-header h2 {
+ font-size: 14px;
+ font-weight: 600;
+ color: #fff;
+ }
+ .feed-header .progress-bar-wrap {
+ width: 240px;
+ height: 4px;
+ background: var(--border);
+ border-radius: 2px;
+ overflow: hidden;
+ }
+ .feed-header .progress-bar-fill {
+ height: 100%;
+ background: var(--green);
+ border-radius: 2px;
+ transition: width 0.4s ease;
+ width: 0%;
+ }
+
+ .cards {
+ display: grid;
+ grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
+ gap: 12px;
+ }
+
+ .agent-card {
+ background: var(--surface);
+ border: 1px solid var(--border);
+ border-radius: 10px;
+ padding: 14px;
+ display: flex;
+ flex-direction: column;
+ gap: 10px;
+ animation: cardIn 0.35s cubic-bezier(0.34, 1.56, 0.64, 1);
+ position: relative;
+ overflow: hidden;
+ }
+ .agent-card::before {
+ content: '';
+ position: absolute;
+ inset: 0;
+ background: linear-gradient(135deg, rgba(0,255,136,0.04) 0%, transparent 60%);
+ pointer-events: none;
+ }
+ @keyframes cardIn {
+ from { opacity: 0; transform: translateY(12px) scale(0.95); }
+ to { opacity: 1; transform: translateY(0) scale(1); }
+ }
+
+ .card-thumb {
+ width: 100%;
+ aspect-ratio: 1;
+ border-radius: 6px;
+ background: var(--border);
+ object-fit: cover;
+ display: block;
+ }
+ .card-thumb-placeholder {
+ width: 100%;
+ aspect-ratio: 1;
+ border-radius: 6px;
+ background: linear-gradient(135deg, #1a2535 0%, #0d1520 100%);
+ display: flex;
+ align-items: center;
+ justify-content: center;
+ font-size: 32px;
+ color: var(--muted);
+ }
+
+ .card-name {
+ font-size: 12px;
+ font-weight: 600;
+ color: #fff;
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ }
+ .card-symbol {
+ font-size: 11px;
+ color: var(--muted);
+ margin-top: -6px;
+ }
+ .card-mint {
+ font-size: 10px;
+ color: var(--green);
+ word-break: break-all;
+ line-height: 1.4;
+ }
+ .card-link {
+ display: block;
+ font-size: 11px;
+ color: var(--muted);
+ text-decoration: none;
+ border: 1px solid var(--border);
+ border-radius: 4px;
+ padding: 4px 8px;
+ text-align: center;
+ transition: border-color 0.15s, color 0.15s;
+ }
+ .card-link:hover { border-color: var(--green); color: var(--green); }
+
+ .card-error {
+ background: #1a0808;
+ border-color: var(--red);
+ }
+ .card-error .card-name { color: var(--red); }
+
+ .empty-state {
+ text-align: center;
+ color: var(--muted);
+ padding: 60px 20px;
+ font-size: 14px;
+ line-height: 2;
+ }
+
+ .done-banner {
+ background: #0a1f10;
+ border: 1px solid var(--green);
+ border-radius: 8px;
+ padding: 16px 20px;
+ display: flex;
+ align-items: center;
+ gap: 12px;
+ margin-bottom: 16px;
+ font-size: 13px;
+ color: var(--green);
+ animation: cardIn 0.3s ease;
+ }
+ .done-banner .done-icon { font-size: 20px; }
+</style>
+</head>
+<body>
+
+<header>
+ <h1>Deploy Agents On-Chain</h1>
+ <span class="badge">ADMIN</span>
+ <span class="badge" style="background:#0d1a2a;color:#5aa9ff;border-color:#2a4a6a">SOLANA · METAPLEX CORE</span>
+</header>
+
+<div class="layout">
+ <aside class="sidebar">
+ <div class="funder-addr">
+ <label>Authority Wallet — send SOL here</label>
+ <div class="addr" id="funder-addr" title="Click to copy">—</div>
+ <div class="hint" id="funder-balance-hint">Loading balance…</div>
+ <div class="hint">Pays mint rent (~0.004 SOL/agent), signs as collection authority, and deploys the collection on first run.</div>
+ </div>
+
+ <div class="funder-addr" id="collection-block" style="display:none">
+ <label>three.ws Agents Collection</label>
+ <div class="addr" id="collection-addr" title="Click to copy">—</div>
+ <div class="hint" id="collection-source"></div>
+ </div>
+
+ <div style="display:grid;grid-template-columns:1fr 1fr;gap:10px">
+ <div class="stat-block">
+ <label>Deployed</label>
+ <div class="value green" id="stat-launched">0</div>
+ </div>
+ <div class="stat-block">
+ <label>Errors</label>
+ <div class="value red" id="stat-errors">0</div>
+ </div>
+ <div class="stat-block">
+ <label>Remaining</label>
+ <div class="value" id="stat-remaining">—</div>
+ </div>
+ <div class="stat-block">
+ <label>Funder SOL</label>
+ <div class="value gold" id="stat-funder-sol">—</div>
+ </div>
+ </div>
+
+ <div class="controls">
+ <div>
+ <label>Network</label>
+ <select id="network-select">
+ <option value="mainnet">mainnet</option>
+ <option value="devnet">devnet</option>
+ </select>
+ </div>
+ <div>
+ <label>Agents per run</label>
+ <input type="number" id="limit-input" value="100" min="1" max="500" />
+ </div>
+ <div style="display:flex;align-items:center;gap:8px;padding:4px 0">
+ <input type="checkbox" id="dry-run" style="width:auto" />
+ <label style="margin:0;cursor:pointer" for="dry-run">Dry run (preview only)</label>
+ </div>
+ </div>
+
+ <button class="btn" id="start-btn" onclick="startLaunch()">Deploy On-Chain</button>
+ <button class="btn danger" id="stop-btn" style="display:none" onclick="stopLaunch()">Stop</button>
+
+ <div class="log-panel" id="log-panel">
+ <div class="log-line info">Ready. Fund the wallet above and click Deploy.</div>
+ </div>
+ </aside>
+
+ <main class="feed">
+ <div class="feed-header">
+ <h2 id="feed-title">Agents</h2>
+ <div class="progress-bar-wrap">
+ <div class="progress-bar-fill" id="progress-bar"></div>
+ </div>
+ </div>
+ <div id="done-banner-slot"></div>
+ <div class="cards" id="cards-grid">
+ <div class="empty-state">
+ Fund the wallet and click <strong>Deploy On-Chain</strong> to begin.<br>
+ Each card appears the moment its agent is minted as a Metaplex Core asset.
+ </div>
+ </div>
+ </main>
+</div>
+
+<script type="module">
+let es = null;
+let deployed = 0, errors = 0, total = 0;
+
+const SOL_PER_AGENT = 0.004;
+
+function setCollection(d) {
+ if (!d || !d.address) return;
+ document.getElementById('collection-block').style.display = '';
+ document.getElementById('collection-addr').textContent = d.address;
+ const label = d.source === 'deployed' ? 'just deployed' : d.source === 'db' ? 'persisted' : 'configured';
+ document.getElementById('collection-source').textContent =
+ `Metaplex Core collection · ${label}`;
+}
+
+function setFunder(d) {
+ document.getElementById('funder-addr').textContent = d.funder;
+ document.getElementById('stat-funder-sol').textContent = (+d.funder_balance_sol).toFixed(3);
+ document.getElementById('funder-balance-hint').textContent =
+ `Balance: ${(+d.funder_balance_sol).toFixed(4)} SOL · covers ~${Math.floor(d.funder_balance_sol / SOL_PER_AGENT)} agents`;
+}
+
+// Probe funder address + balance on load via a 1-agent dry run (closes on init).
+(() => {
+ try {
+ const probe = new EventSource('/api/admin/bulk-launch?dry_run=true&limit=1');
+ probe.addEventListener('init', e => { setFunder(JSON.parse(e.data)); probe.close(); });
+ probe.addEventListener('done', () => probe.close());
+ probe.onerror = () => probe.close();
+ } catch {}
+})();
+
+// Copy address on click (funder + collection)
+for (const id of ['funder-addr', 'collection-addr']) {
+ document.getElementById(id).addEventListener('click', () => {
+ const addr = document.getElementById(id).textContent.trim();
+ if (addr && addr !== '—') navigator.clipboard.writeText(addr).catch(() => {});
+ });
+}
+
+window.startLaunch = function () {
+ if (es) return;
+ deployed = 0; errors = 0; total = 0;
+ document.getElementById('stat-launched').textContent = '0';
+ document.getElementById('stat-errors').textContent = '0';
+ document.getElementById('done-banner-slot').innerHTML = '';
+ document.getElementById('cards-grid').innerHTML = '';
+
+ const network = document.getElementById('network-select').value;
+ const limit = document.getElementById('limit-input').value || 100;
+ const dryRun = document.getElementById('dry-run').checked;
+ const url = `/api/admin/bulk-launch?network=${network}&limit=${limit}&dry_run=${dryRun}`;
+
+ document.getElementById('start-btn').style.display = 'none';
+ document.getElementById('stop-btn').style.display = '';
+ addLog('Starting…', 'info');
+
+ es = new EventSource(url);
+
+ es.addEventListener('init', e => {
+ const d = JSON.parse(e.data);
+ total = d.total;
+ document.getElementById('stat-remaining').textContent = total;
+ setFunder(d);
+ addLog(`Deploying ${total} agents on ${d.network}${d.dry_run ? ' (dry run)' : ''}`, 'info');
+ });
+
+ es.addEventListener('collection', e => {
+ const d = JSON.parse(e.data);
+ setCollection(d);
+ if (d.address) addLog(`collection ${d.source}: ${d.address}`, d.source === 'deployed' ? 'ok' : 'info');
+ });
+
+ es.addEventListener('wallet', e => {
+ const d = JSON.parse(e.data);
+ addLog(`wallet: ${d.name} → ${shortAddr(d.owner)}`, 'ok');
+ });
+
+ es.addEventListener('deployed', e => {
+ const d = JSON.parse(e.data);
+ deployed++;
+ document.getElementById('stat-launched').textContent = deployed;
+ document.getElementById('stat-remaining').textContent = Math.max(0, total - deployed - errors);
+ document.getElementById('progress-bar').style.width = total > 0 ? `${(deployed / total) * 100}%` : '0%';
+ addCard(d);
+ addLog(`deployed: ${d.name} ${d.dry_run ? '(dry)' : shortAddr(d.asset)}`, 'ok');
+ });
+
+ es.addEventListener('error', e => {
+ try {
+ const d = JSON.parse(e.data);
+ errors++;
+ document.getElementById('stat-errors').textContent = errors;
+ addErrorCard(d);
+ addLog(`error: ${d.name} — ${d.error}`, 'err');
+ } catch {}
+ });
+
+ es.addEventListener('skip', e => {
+ const d = JSON.parse(e.data);
+ addLog(`skip: ${d.name} — ${d.reason}`, 'info');
+ });
+
+ es.addEventListener('paused', e => {
+ const d = JSON.parse(e.data);
+ document.getElementById('stat-funder-sol').textContent = (+d.funder_balance_sol).toFixed(3);
+ addLog(`paused — ${d.reason}`, 'err');
+ done();
+ });
+
+ es.addEventListener('done', e => {
+ const d = JSON.parse(e.data);
+ addLog(`done — deployed: ${d.deployed}, errors: ${d.errors}`, 'ok');
+ showDoneBanner(d);
+ done();
+ });
+
+ es.onerror = () => {
+ addLog('stream disconnected', 'err');
+ done();
+ };
+};
+
+window.stopLaunch = function () {
+ if (es) { es.close(); es = null; }
+ done();
+ addLog('Stopped by user.', 'info');
+};
+
+function done() {
+ if (es) { es.close(); es = null; }
+ document.getElementById('start-btn').style.display = '';
+ document.getElementById('stop-btn').style.display = 'none';
+}
+
+function addLog(msg, type = '') {
+ const panel = document.getElementById('log-panel');
+ const el = document.createElement('div');
+ el.className = `log-line ${type}`;
+ el.textContent = `${new Date().toLocaleTimeString()} ${msg}`;
+ panel.appendChild(el);
+ panel.scrollTop = panel.scrollHeight;
+}
+
+function shortAddr(a) {
+ return a && a.length > 12 ? `${a.slice(0, 4)}…${a.slice(-4)}` : (a || '');
+}
+
+function addCard(d) {
+ const grid = document.getElementById('cards-grid');
+ const card = document.createElement('div');
+ card.className = 'agent-card';
+ card.innerHTML = `
+ ${d.avatar_thumb
+ ? `<img class="card-thumb" src="${escHtml(d.avatar_thumb)}" alt="" loading="lazy" onerror="this.style.display='none'">`
+ : `<div class="card-thumb-placeholder">🤖</div>`}
+ <div>
+ <div class="card-name">${escHtml(d.name)}</div>
+ <div class="card-symbol">${d.owner ? 'owner ' + escHtml(shortAddr(d.owner)) : ''}</div>
+ </div>
+ ${d.asset && !d.dry_run
+ ? `<div class="card-mint">${escHtml(d.asset)}</div>
+ <a class="card-link" href="${escHtml(d.explorer_url)}" target="_blank" rel="noopener">Solscan ↗</a>`
+ : `<div class="card-mint" style="color:var(--muted)">(dry run)</div>`}
+ `;
+ grid.appendChild(card);
+}
+
+function addErrorCard(d) {
+ const grid = document.getElementById('cards-grid');
+ const card = document.createElement('div');
+ card.className = 'agent-card card-error';
+ card.innerHTML = `
+ <div class="card-thumb-placeholder" style="font-size:24px">⚠</div>
+ <div class="card-name">${escHtml(d.name)}</div>
+ <div style="font-size:10px;color:var(--red);word-break:break-word">${escHtml(d.error)}</div>
+ `;
+ grid.appendChild(card);
+}
+
+function showDoneBanner(d) {
+ document.getElementById('done-banner-slot').innerHTML = `
+ <div class="done-banner">
+ <span class="done-icon">✓</span>
+ Run complete — <strong>${d.deployed}</strong> deployed, <strong>${d.errors}</strong> errors.
+ Re-run to continue with remaining agents.
+ </div>
+ `;
+}
+
+function escHtml(s) {
+ return String(s ?? '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;');
+}
+</script>
+</body>
+</html>
diff --git a/scripts/onchain-deploy-smoke.mjs b/scripts/onchain-deploy-smoke.mjs
new file mode 100644
index 000000000..b6da313dc
--- /dev/null
+++ b/scripts/onchain-deploy-smoke.mjs
@@ -0,0 +1,198 @@
+#!/usr/bin/env node
+/**
+ * Smoke test for the on-chain agent deploy path used by api/admin/bulk-launch.js.
+ * Proves the exact Metaplex Core mint works with the installed deps
+ * (umi 1.5 / mpl-core 1.10) before any mainnet SOL is spent. No database writes.
+ *
+ * It runs in two phases:
+ * BUILD (always, offline, no SOL): construct the exact `createCollection` and
+ * `create` transactions the handler builds and assert they are well-formed —
+ * fee payer = funder, required signers correct, the mpl-core program is
+ * targeted, the Attributes + Royalties plugins serialize, and the whole tx
+ * fits Solana's 1232-byte limit. This deterministically catches SDK/plugin/
+ * version-compat regressions without depending on a faucet.
+ * SEND (only when the funder holds devnet SOL): actually deploy the collection,
+ * mint an asset owned by a fresh agent wallet, fetch it back, and assert
+ * owner / collection / plugins on-chain.
+ *
+ * Usage:
+ * node scripts/onchain-deploy-smoke.mjs
+ * FUNDER_SECRET=<bs58> node scripts/onchain-deploy-smoke.mjs # reuse a key
+ */
+
+import { Keypair, Connection, LAMPORTS_PER_SOL } from '@solana/web3.js';
+import bs58 from 'bs58';
+import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';
+import {
+ mplCore,
+ create,
+ createCollection,
+ fetchAsset,
+ ruleSet,
+ MPL_CORE_PROGRAM_ID,
+} from '@metaplex-foundation/mpl-core';
+import {
+ generateSigner,
+ publicKey as umiPublicKey,
+ createSignerFromKeypair,
+ signerIdentity,
+} from '@metaplex-foundation/umi';
+
+const RPC = process.env.SOLANA_RPC_URL_DEVNET || 'https://api.devnet.solana.com';
+const DEVNET_REF = 'EtWTRABZaYq6iMfeYKouRu166VU2xqa1';
+// Any valid 32-byte base58 hash works for offline build verification — the
+// signer set and instructions are independent of the blockhash.
+const DUMMY_BLOCKHASH = '11111111111111111111111111111111';
+
+function explorer(addr) {
+ return `https://solscan.io/account/${addr}?cluster=devnet`;
+}
+
+function check(label, pass, results) {
+ results.push(pass);
+ console.log(` ${pass ? '✓' : '✗'} ${label}`);
+}
+
+// Assert a builder compiles to a valid tx with the expected fee payer, signers,
+// program target, and size — without sending it.
+function verifyBuild(umi, builder, { label, expectFeePayer, expectSigners, results }) {
+ const tx = builder.setBlockhash(DUMMY_BLOCKHASH).build(umi);
+ const serialized = umi.transactions.serialize(tx);
+ const signerKeys = new Set(builder.getSigners(umi).map((s) => s.publicKey.toString()));
+ const programs = new Set(builder.getInstructions().map((i) => i.programId.toString()));
+
+ console.log(`\n[build] ${label}`);
+ check('compiles to a transaction', !!tx && serialized.length > 0, results);
+ check(`fits 1232-byte tx limit (${serialized.length}B)`, serialized.length <= 1232, results);
+ check(`fee payer = funder`, tx.message.accounts?.[0]?.toString() === expectFeePayer, results);
+ check(`targets mpl-core program`, programs.has(MPL_CORE_PROGRAM_ID.toString()), results);
+ for (const s of expectSigners) {
+ check(`signer present: ${s.label}`, signerKeys.has(s.key), results);
+ }
+}
+
+async function main() {
+ const results = [];
+
+ const funder = process.env.FUNDER_SECRET
+ ? Keypair.fromSecretKey(bs58.decode(process.env.FUNDER_SECRET))
+ : Keypair.generate();
+ console.log(`Funder (authority + payer): ${funder.publicKey.toBase58()}`);
+
+ // Umi with funder as identity (payer) + signer — exactly like the handler.
+ const umi = createUmi(RPC).use(mplCore());
+ const authoritySigner = createSignerFromKeypair(
+ umi,
+ umi.eddsa.createKeypairFromSecretKey(funder.secretKey),
+ );
+ umi.use(signerIdentity(authoritySigner));
+ const funderKey = authoritySigner.publicKey.toString();
+
+ // ── BUILD phase (offline, no SOL) ──────────────────────────────────────────
+ const collectionSigner = generateSigner(umi);
+ const collectionBuilder = createCollection(umi, {
+ collection: collectionSigner,
+ name: 'three.ws Agents',
+ uri: 'https://three.ws/api/agents/solana-collection-metadata?network=devnet',
+ plugins: [
+ {
+ type: 'Attributes',
+ attributeList: [
+ { key: 'platform', value: 'three.ws' },
+ { key: 'standard', value: 'metaplex-core' },
+ { key: 'chain', value: `solana:${DEVNET_REF}` },
+ ],
+ },
+ ],
+ });
+ verifyBuild(umi, collectionBuilder, {
+ label: 'createCollection (three.ws Agents)',
+ expectFeePayer: funderKey,
+ expectSigners: [
+ { label: 'funder/authority', key: funderKey },
+ { label: 'collection', key: collectionSigner.publicKey.toString() },
+ ],
+ results,
+ });
+
+ const agentOwner = Keypair.generate(); // stands in for the custodial agent wallet
+ const ownerPk = umiPublicKey(agentOwner.publicKey.toBase58());
+ const assetSigner = generateSigner(umi);
+ const assetArgs = {
+ asset: assetSigner,
+ collection: collectionSigner.publicKey,
+ authority: authoritySigner,
+ owner: ownerPk,
+ name: 'Smoke Agent',
+ uri: 'https://three.ws/api/agents/smoke/metadata',
+ plugins: [
+ {
+ type: 'Attributes',
+ attributeList: [
+ { key: 'platform', value: 'three.ws' },
+ { key: 'agent', value: 'Smoke Agent' },
+ { key: 'standard', value: 'metaplex-core' },
+ ],
+ },
+ {
+ type: 'Royalties',
+ basisPoints: 500,
+ creators: [{ address: ownerPk, percentage: 100 }],
+ ruleSet: ruleSet('None'),
+ },
+ ],
+ };
+ verifyBuild(umi, create(umi, assetArgs), {
+ label: 'create agent asset (into collection, owner = agent wallet)',
+ expectFeePayer: funderKey,
+ expectSigners: [
+ { label: 'funder/authority', key: funderKey },
+ { label: 'asset', key: assetSigner.publicKey.toString() },
+ ],
+ results,
+ });
+
+ const owner = agentOwner.publicKey.toBase58();
+ check('owner (agent wallet) is NOT a required signer', owner !== funderKey, results);
+
+ const buildOk = results.every(Boolean);
+ console.log(`\n[build] ${buildOk ? '✅ all checks passed' : '❌ FAILED'} (${results.filter(Boolean).length}/${results.length})`);
+
+ // ── SEND phase (only if the funder has devnet SOL) ─────────────────────────
+ const conn = new Connection(RPC, 'confirmed');
+ let bal = 0;
+ try { bal = await conn.getBalance(funder.publicKey); } catch {}
+ if (bal < 0.01 * LAMPORTS_PER_SOL) {
+ console.log(`\n[send] skipped — funder holds ${(bal / LAMPORTS_PER_SOL).toFixed(4)} SOL on devnet.`);
+ console.log(' (public devnet faucet is rate-limiting this host; build verification above is authoritative.)');
+ process.exit(buildOk ? 0 : 1);
+ }
+
+ console.log(`\n[send] funder has ${(bal / LAMPORTS_PER_SOL).toFixed(4)} SOL — performing a real devnet mint…`);
+ await createCollection(umi, {
+ collection: collectionSigner,
+ name: 'three.ws Agents',
+ uri: 'https://three.ws/api/agents/solana-collection-metadata?network=devnet',
+ plugins: [{ type: 'Attributes', attributeList: [{ key: 'platform', value: 'three.ws' }, { key: 'standard', value: 'metaplex-core' }] }],
+ }).sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });
+ console.log(` ✓ collection → ${explorer(collectionSigner.publicKey)}`);
+
+ const res = await create(umi, assetArgs).sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });
+ console.log(` ✓ minted, sig ${bs58.encode(res.signature)}`);
+
+ const asset = await fetchAsset(umi, assetSigner.publicKey);
+ check('owner == agent wallet', asset.owner.toString() === owner, results);
+ check('in collection', asset.updateAuthority?.address?.toString() === collectionSigner.publicKey.toString(), results);
+ check('has Royalties plugin (500 bps)', asset.royalties?.basisPoints === 500, results);
+ console.log(`\nAsset: ${explorer(assetSigner.publicKey)}`);
+ console.log(`Collection: ${explorer(collectionSigner.publicKey)}`);
+
+ const ok = results.every(Boolean);
+ console.log(ok ? '\n✅ Smoke passed — on-chain deploy works end-to-end.' : '\n❌ Smoke failed — see ✗ above.');
+ process.exit(ok ? 0 : 1);
+}
+
+main().catch((err) => {
+ console.error('\n❌ Smoke error:', err?.stack || err?.message || err);
+ process.exit(1);
+});
diff --git a/vercel.json b/vercel.json
index d250d1bb1..14ed9b334 100644
--- a/vercel.json
+++ b/vercel.json
@@ -439,6 +439,10 @@
"src": "/pump-live/?",
"dest": "/pump-live.html"
},
+ {
+ "src": "/admin/bulk-launch/?",
+ "dest": "/bulk-launch.html"
+ },
{
"src": "/pump-dashboard/?",
"dest": "/pump-dashboard.html"
diff --git a/vite.config.js b/vite.config.js
index 25935ace1..65d07ddfb 100644
--- a/vite.config.js
+++ b/vite.config.js
@@ -286,6 +286,7 @@ const appConfig = {
shopper: resolve(__dirname, 'pages/shopper.html'),
go: resolve(__dirname, 'pages/go.html'),
'pump-live': resolve(__dirname, 'pages/pump-live.html'),
+ 'bulk-launch': resolve(__dirname, 'pages/bulk-launch.html'),
'pump-dashboard': resolve(__dirname, 'pages/pump-dashboard.html'),
autopilot: resolve(__dirname, 'pages/autopilot.html'),
'pump-visualizer': resolve(__dirname, 'pages/pump-visualizer.html'),