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: enhance GCP deployment script with build service account and cloudbuild config

fudjiab29f336b29ca
diff --git a/README.md b/README.md
index e3efd377c..7dc82c4e0 100644
--- a/README.md
+++ b/README.md
@@ -2126,7 +2126,7 @@ Access tokens are short-lived JWTs (1 hour). Refresh tokens are opaque strings s
**Endpoint:** `POST /api/mcp` (tools), `GET /api/mcp` (SSE), `DELETE /api/mcp` (session terminate)
**Auth:** OAuth 2.1 Bearer token with `mcp` scope; some tools additionally require x402 USDC payment
-**Registry:** Listed on the [official MCP Registry](https://registry.modelcontextprotocol.io/?q=three.ws) as `io.github.nirholas/three.ws`
+**Registry:** Listed on the [official MCP Registry](https://registry.modelcontextprotocol.io/?q=io.github.nirholas) as `io.github.nirholas/three.ws` — one of 42 three.ws MCP servers in the registry. Also discoverable on [Smithery](https://smithery.ai/search?q=three.ws), [Glama](https://glama.ai/mcp/servers?query=three.ws), and [PulseMCP](https://www.pulsemcp.com/servers?q=three.ws).
**x402scan:** [view on x402scan](https://www.x402scan.com/server/17cbd874-52ac-4920-a020-b22ff2489a07) — paid MCP tool calls and revenue
**Available tools:**
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 5ccc718bb..db5bfe6aa 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -43,6 +43,7 @@ bottom.
| Avatar service backend | [api/](api) + [workers/](workers) | In-repo | Vercel functions + Cloudflare workers |
| On-chain identity | [contracts/](contracts) | In-repo | Foundry-based on-chain agent identity, ERC-8004 |
| On-chain skill licenses | [contracts/skill-license/](contracts/skill-license) `→ /api/skills/license-onchain` | In-repo | Anchor program: each purchased skill = a 1/1 SPL NFT + `SkillLicense` PDA, a trustless alternative to DB-backed access checks. Backend: [api/_lib/skill-license-onchain.js](api/_lib/skill-license-onchain.js) |
+| Tokenized 3D (mint an avatar as an NFT) | [api/_lib/tokenize-3d.js](api/_lib/tokenize-3d.js) + [api/_lib/tokenize-3d-metadata.js](api/_lib/tokenize-3d-metadata.js), MCP tools [api/_mcp/tools/tokenize.js](api/_mcp/tools/tokenize.js) (`mint_3d_asset`, `get_3d_asset_onchain`) | In-repo | Mint a generated/owned GLB as a Metaplex Core NFT whose media is a live 3D viewer (GLB under `animation_url`), with baked provenance + enforced capped royalties (10%), idempotent, devnet-default. Launch record: [tokenized_3d_assets](api/_lib/migrations/20260707120000_tokenized_3d_assets.sql). Docs: [docs/mcp.md](docs/mcp.md#mint_3d_asset). E2E: [scripts/tokenize-3d-devnet-e2e.mjs](scripts/tokenize-3d-devnet-e2e.mjs) |
| Launch Studio (coin-launch use cases) | [api/_lib/launch/](api/_lib/launch) `→ /launch-studio`, [api/pump/launch-studio.js](api/pump/launch-studio.js), [public/launch-studio/launch-studio.js](public/launch-studio/launch-studio.js) | In-repo | Engine + catalog of 50 declarative launch recipes — reward coins for trending GitHub repos/creators ([github-trending.js](api/_lib/github-trending.js)) and coins riding live narratives ([launcher-trends.js](api/_lib/launcher-trends.js)). Live preview → `/launch` handoff. Docs: [docs/launch-usecases.md](docs/launch-usecases.md), [api/_lib/launch/README.md](api/_lib/launch/README.md) |
| Avatar Seeder control room | [pages/admin/seeder.html](pages/admin/seeder.html) + [src/admin-seeder.js](src/admin-seeder.js) `→ /admin/seeder`, backend [api/admin/seeder.js](api/admin/seeder.js) | In-repo (admin, noindex) | Arm/disarm the headless [Avaturn seed cron](api/cron/avaturn-seed-cron.js), watch live throughput + rig rate, and preview freshly-forged rigged avatars in 3D. Toggles the `avaturn_seed` runtime flag. Flags: [api/_lib/flags.js](api/_lib/flags.js) + [api/admin/flags.js](api/admin/flags.js). Docs: [docs/ops/runtime-flags.md](docs/ops/runtime-flags.md) |
| On-chain agent invocation | [contracts/agent-invocation/](contracts/agent-invocation) | In-repo | Anchor program: verifiable agent-to-agent skill invocation events. SDK: [agent-protocol-sdk/](agent-protocol-sdk) |
diff --git a/api/_lib/remix-settlement.js b/api/_lib/remix-settlement.js
new file mode 100644
index 000000000..4d2034d3a
--- /dev/null
+++ b/api/_lib/remix-settlement.js
@@ -0,0 +1,125 @@
+// Remix royalty settlement — the real creator-payout leg (PAID track only).
+//
+// When an agent remixes another creator's published asset, it pays the full
+// remix fee in USDC to the platform via x402 (single-recipient, as the x402 rail
+// requires). The platform then routes the creator's royalty slice on-chain from
+// its payout wallet to the original creator — a SECOND, real USDC transfer, not a
+// fake ledger entry. This module is that second leg: it takes the settled fee,
+// applies the pure split math (api/_lib/remix-royalty.js), pays the creator, and
+// records the settlement onto the SOURCE creation as append-only provenance.
+//
+// Split + caps are pure and unit-tested; the payout wallet + on-chain send reuse
+// the same audited rails as the vanity bounty payout (transferSolanaUSDC from the
+// platform treasury). $THREE-policy clean: USDC is the settlement asset only; no
+// other coin is named.
+
+import bs58 from 'bs58';
+
+import { transferSolanaUSDC } from './solana-transfer.js';
+import { SOLANA_USDC_MINT } from '../payments/_config.js';
+import { computeRemixSplit, REMIX_ROYALTY_DEFAULT_BPS } from './remix-royalty.js';
+import { recordRemixSettlement } from './forge-store.js';
+
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+
+// Resolve the platform's royalty payout wallet as a Base58 64-byte secret. A
+// dedicated REMIX_ROYALTY_PAYOUT_KEY is preferred; the shared club treasury
+// secret is the fallback (same wallet the vanity bounty market pays from). Both
+// are validated to decode to 64 bytes so a misconfig fails loud, never on-chain.
+function resolvePayoutKeyBase58() {
+ const dedicated = process.env.REMIX_ROYALTY_PAYOUT_KEY;
+ if (dedicated && dedicated.trim()) {
+ const s = dedicated.trim();
+ try {
+ if (bs58.decode(s).length === 64) return s;
+ } catch {
+ /* not Base58 — try base64 below */
+ }
+ try {
+ const raw = Buffer.from(s, 'base64');
+ if (raw.byteLength === 64) return bs58.encode(raw);
+ } catch {
+ /* ignore */
+ }
+ }
+ const clubB64 = process.env.CLUB_SOLANA_TREASURY_SECRET_KEY_B64;
+ if (clubB64) {
+ try {
+ const raw = Buffer.from(clubB64, 'base64');
+ if (raw.byteLength === 64) return bs58.encode(raw);
+ } catch {
+ /* ignore */
+ }
+ }
+ return null;
+}
+
+/** True when the platform can actually route a royalty on-chain. */
+export function royaltyPayoutConfigured() {
+ return !!resolvePayoutKeyBase58();
+}
+
+/**
+ * Settle a creator royalty for a remix that has already had its fee collected.
+ * Computes the split, and — when there IS a royalty to pay and the creator has a
+ * valid payout wallet and the platform payout wallet is configured — sends the
+ * creator's slice on-chain and records it on the source. Every non-paying outcome
+ * is reported honestly with a reason (never a fake "pending"): a source with no
+ * payout wallet, a sub-dust royalty, or an unconfigured platform wallet all
+ * return `paid: false` with the split still computed for transparency.
+ *
+ * @param {object} p
+ * @param {object} p.source getRemixSource() result (id, creatorWallet, royaltyBps).
+ * @param {bigint|number|string} p.priceAtomics the remix fee actually collected, in USDC atomics.
+ * @param {string} [p.remixCreationId] the derived creation this royalty is for.
+ * @returns {Promise<{
+ * split: object, royaltyBps:number, requestedBps:number, capped:boolean, dust:boolean,
+ * creatorUsd:number, platformUsd:number, creatorAtomics:string, platformAtomics:string,
+ * paid:boolean, reason?:string, creatorTx?:string, settlement?:object }>}
+ */
+export async function settleRemixRoyalty({ source, priceAtomics, remixCreationId }) {
+ const split = computeRemixSplit({
+ priceAtomics,
+ royaltyBps: source?.royaltyBps ?? REMIX_ROYALTY_DEFAULT_BPS,
+ });
+ const summary = {
+ split,
+ royaltyBps: split.royaltyBps,
+ requestedBps: split.requestedBps,
+ capped: split.capped,
+ dust: split.dust,
+ creatorUsd: split.creatorUsd,
+ platformUsd: split.platformUsd,
+ creatorAtomics: split.creatorAtomics.toString(),
+ platformAtomics: split.platformAtomics.toString(),
+ };
+
+ const creatorWallet = source?.creatorWallet;
+ if (!creatorWallet || !BASE58_RE.test(String(creatorWallet))) {
+ return { ...summary, paid: false, reason: 'no_creator_wallet' };
+ }
+ if (split.creatorAtomics <= 0n) {
+ return { ...summary, paid: false, reason: split.dust ? 'below_dust_floor' : 'zero_royalty' };
+ }
+ const fromWallet = resolvePayoutKeyBase58();
+ if (!fromWallet) {
+ return { ...summary, paid: false, reason: 'payout_unconfigured' };
+ }
+
+ const sig = await transferSolanaUSDC({
+ fromWallet,
+ toAddress: creatorWallet,
+ amount: split.creatorAtomics,
+ mint: SOLANA_USDC_MINT,
+ });
+ const settlement = {
+ tx_signature: sig,
+ usdc_atomics: split.creatorAtomics.toString(),
+ creator_wallet: creatorWallet,
+ royalty_bps: split.royaltyBps,
+ remix_creation_id: remixCreationId ?? null,
+ settled_at: new Date().toISOString(),
+ };
+ await recordRemixSettlement({ sourceCreationId: source.id, settlement });
+ return { ...summary, paid: true, creatorTx: sig, settlement };
+}
diff --git a/api/_lib/service-catalog/services/index.js b/api/_lib/service-catalog/services/index.js
index 9700eb1e5..3d9d68945 100644
--- a/api/_lib/service-catalog/services/index.js
+++ b/api/_lib/service-catalog/services/index.js
@@ -21,6 +21,7 @@ import vanityVerifiable from './vanity-verifiable.js';
import vanityPremium from './vanity-premium.js';
import permit2PaidDemo from './permit2-paid-demo.js';
import assetDownload from './asset-download.js';
+import remixAsset from './remix-asset.js';
import skillCall from './skill-call.js';
import tokenIntel from './token-intel.js';
import cosmeticPurchase from './cosmetic-purchase.js';
@@ -67,6 +68,7 @@ export const PAID_SERVICES = Object.freeze([
vanityPremium,
permit2PaidDemo,
assetDownload,
+ remixAsset,
skillCall,
tokenIntel,
cosmeticPurchase,
diff --git a/api/_lib/service-catalog/services/remix-asset.js b/api/_lib/service-catalog/services/remix-asset.js
new file mode 100644
index 000000000..fb63d2f00
--- /dev/null
+++ b/api/_lib/service-catalog/services/remix-asset.js
@@ -0,0 +1,50 @@
+// Service-catalog descriptor — the single written-once listing for this
+// service. api/wk.js derives its /.well-known/x402.json resource entry from
+// this file via api/_lib/service-catalog/index.js (toBazaarDiscovery), and
+// the OKX storefront projection reads the same record (toOkxCatalog).
+// Contract: specs/service-catalog.md. Do not re-add a hand-written mirror
+// for this route in api/wk.js — edit this descriptor instead.
+
+export default {
+ slug: 'remix-asset',
+ title: 'Remix a 3D asset (with creator royalties)',
+ category: '3d',
+ useCase: 'Remix a published 3D model by describing a change; a creator-set royalty of the fee routes on-chain to the original creator.',
+ path: '/api/x402/remix-asset',
+ method: 'POST',
+ free: false,
+ status: 'live',
+ priceAtomics: '250000',
+ acceptsBuilder: 'standard',
+ serviceName: 'Remix a 3D asset (with creator royalties)',
+ tags: ['3d', 'remix', 'royalties', 'generation', 'glb'],
+ description:
+ 'Remix a published, remixable 3D model: pay a fixed fee in USDC and describe the change in words ' +
+ '("make it metallic", "add wings"). The platform generates a NEW model anchored to the source, records ' +
+ 'durable parent→child provenance, and routes a creator-set royalty (≤20% of the fee, the remixer always ' +
+ 'keeps the majority) on-chain to the original creator. Browse remixable assets and their royalty terms for ' +
+ 'free at GET /api/remix-feed; publish your own finished models there to earn royalties when others build on them.',
+ input: {
+ source_creation_id: '00000000-0000-0000-0000-000000000000',
+ instruction: 'make it metallic',
+ },
+ inputSchema: {
+ type: 'object',
+ required: ['source_creation_id', 'instruction'],
+ properties: {
+ source_creation_id: {
+ type: 'string',
+ minLength: 1,
+ maxLength: 64,
+ description: 'The id of a remixable creation (from GET /api/remix-feed).',
+ },
+ instruction: {
+ type: 'string',
+ minLength: 1,
+ maxLength: 500,
+ description: 'The change to make, in plain language: "make it metallic", "bigger helmet", "add a cape".',
+ },
+ },
+ },
+ storefronts: ['x402scan'],
+};
diff --git a/api/_okx3d/identity.js b/api/_okx3d/identity.js
index d507a6fd8..013ad1f33 100644
--- a/api/_okx3d/identity.js
+++ b/api/_okx3d/identity.js
@@ -151,20 +151,35 @@ function clampPrompt(text, max = MAX_GENERATION_PROMPT_CHARS) {
// framing rigging requires — an identity brief ("a finance data agent") rarely
// names a humanoid subject, so unlike forge_avatar there is no humanoid gate
// here: the subject is BY CONSTRUCTION a humanoid character embodying the
-// brief, in both the director instruction and this template. Leads with the
-// visual description and stays inside the generation prompt budget: the frame
-// text is ~130 chars, so the brief+hints get the remaining ~170.
+// brief. A text-to-3D encoder wants a visual SUBJECT, not backstory, so this
+// leads with the (visual) style hints and reduces the brief to its first
+// sentence — the core descriptor — rather than dumping the whole narrative and
+// truncating it mid-clause. Stays inside the generation prompt budget (~130
+// chars of frame text leaves ~170 for hints + subject) and never leaves a
+// dangling comma or half-word at a cut.
export function fallbackIdentityPrompt({ brief, styleHints }) {
- // The style hints ARE the visual direction — they get their own budget so a
- // long brief can never crowd them out of the prompt.
- const hints = styleHints ? clampPrompt(styleHints, 70) : '';
- const subject = clampPrompt(brief, MAX_GENERATION_PROMPT_CHARS - 130 - (hints ? hints.length + 2 : 0));
+ // The style hints ARE the visual direction — give them priority and their own
+ // budget so a long brief can never crowd them out of the prompt.
+ const hints = styleHints ? cleanClause(clampPrompt(styleHints, 90)) : '';
+ // First sentence only (handles both Latin ".!?" and CJK "。!?").
+ const raw = String(brief ?? '').trim();
+ const firstSentence = raw.split(/(?<=[.!?。!?])\s+/)[0] || raw;
+ const subject = cleanClause(
+ clampPrompt(firstSentence, MAX_GENERATION_PROMPT_CHARS - 140 - (hints ? hints.length + 2 : 0)),
+ );
+ const visual = [subject, hints].filter(Boolean).join(', ');
return (
- `full-body humanoid character: ${subject}${hints ? `, ${hints}` : ''}, standing neutral pose, ` +
+ `full-body humanoid character embodying: ${visual}, standing neutral pose, ` +
'arms slightly away from body, plain background'
);
}
+// Trim trailing sentence/clause punctuation so a clause never abuts the next
+// comma-joined fragment ("…real time., deep navy" → "…real time, deep navy").
+function cleanClause(text) {
+ return String(text ?? '').replace(/[.,;:!?。!?、\s]+$/, '');
+}
+
export async function shapeIdentityPrompt({ agentName, brief, styleHints }) {
const directed = await directIdentityPrompt({ agentName, brief, styleHints });
return {
diff --git a/api/remix-feed.js b/api/remix-feed.js
new file mode 100644
index 000000000..bac7d4805
--- /dev/null
+++ b/api/remix-feed.js
@@ -0,0 +1,157 @@
+/**
+ * Remix feed — the composable, remixable-asset gallery (FREE surface).
+ *
+ * GET /api/remix-feed → { enabled, items: [...], next? }
+ * GET /api/remix-feed?before=<iso> → next page (cursor by created_at)
+ * GET /api/remix-feed?action=lineage&root=<id>
+ * → { enabled, lineage: [...] }
+ * POST /api/remix-feed { action:'publish', creation_id, royalty_bps?,
+ * creator_wallet?, license?, remixable? }
+ * → { published: {...} }
+ *
+ * Browsing is free and identifier-light: each item carries the provenance and
+ * royalty TERMS a remixer needs to decide (prompt, whether it is itself a remix,
+ * royalty rate, and whether royalties can actually route) — but never the raw
+ * creator payout wallet. Remixing (and paying the royalty) happens on the paid
+ * x402 endpoint /api/x402/remix-asset; this feed is the read + publish half.
+ *
+ * Publishing opts one of YOUR OWN finished creations into the remix bazaar and
+ * sets its license + royalty rate + Solana payout wallet — scoped to the
+ * x-forge-client that created it, so nobody can publish another's model. All of
+ * this lives on the existing forge_creations rows; no parallel asset store.
+ *
+ * No coin is named anywhere here — USDC is the settlement asset on the paid
+ * endpoint only; this feed never mentions a token.
+ */
+
+import { cors, json, method, wrap, rateLimited, readJson } from './_lib/http.js';
+import { limits, clientIp } from './_lib/rate-limit.js';
+import {
+ hashClient,
+ forgeStoreEnabled,
+ listRemixable,
+ setRemixable,
+ getLineage,
+ getRemixSource,
+} from './_lib/forge-store.js';
+import { clampRoyaltyBps, atomicsToUsd } from './_lib/remix-royalty.js';
+
+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;
+const LICENSES = new Set(['remix-cc', 'remix-nc', 'remix-royalty', 'all-rights']);
+
+function clientKeyFrom(req) {
+ const raw = req.headers['x-forge-client'];
+ return hashClient(Array.isArray(raw) ? raw[0] : raw);
+}
+
+// Shape a public feed item: provenance + royalty TERMS, no payout wallet, no
+// internal identifiers beyond the creation id needed to remix it.
+function publicItem(it) {
+ return {
+ id: it.id,
+ prompt: it.prompt,
+ glbUrl: it.glb_url,
+ previewImageUrl: it.preview_image_url ?? null,
+ viewerUrl: `https://three.ws/viewer?src=${encodeURIComponent(it.glb_url)}`,
+ royaltyBps: it.royaltyBps ?? 0,
+ royaltyPercent: Math.round(((it.royaltyBps ?? 0) / 100) * 10) / 10,
+ royaltyPayable: Boolean(it.royaltyPayable),
+ isDerived: Boolean(it.isDerived),
+ lineageIndex: it.lineageIndex ?? 0,
+ category: it.model_category ?? 'other',
+ createdAt: it.created_at,
+ };
+}
+
+async function handleGet(req, res) {
+ const url = new URL(req.url, 'http://localhost');
+ const action = (url.searchParams.get('action') || '').trim();
+
+ if (action === 'lineage') {
+ const root = (url.searchParams.get('root') || '').trim();
+ if (!root) return json(res, 400, { error: 'root creation id required' });
+ const rows = await getLineage({ rootCreationId: root, clientKey: null });
+ const lineage = rows.map((r) => ({
+ id: r.id,
+ parentId: r.parent_creation_id,
+ lineageIndex: r.lineage_index,
+ instruction: r.refine_instruction,
+ prompt: r.prompt,
+ glbUrl: r.glb_url,
+ viewerUrl: r.glb_url ? `https://three.ws/viewer?src=${encodeURIComponent(r.glb_url)}` : null,
+ status: r.status,
+ createdAt: r.created_at,
+ }));
+ return json(res, 200, { enabled: true, lineage }, { 'cache-control': 'public, s-maxage=30, stale-while-revalidate=120' });
+ }
+
+ const limit = Math.min(Math.max(Number(url.searchParams.get('limit')) || 24, 1), 48);
+ const before = (url.searchParams.get('before') || '').trim() || undefined;
+ const rows = await listRemixable({ limit, before });
+ const items = rows.map(publicItem);
+ const next = items.length === limit ? items[items.length - 1].createdAt : null;
+ return json(
+ res,
+ 200,
+ { enabled: true, items, next },
+ { 'cache-control': 'public, s-maxage=30, stale-while-revalidate=120' },
+ );
+}
+
+async function handlePost(req, res) {
+ const body = await readJson(req);
+ const action = (body?.action || '').trim();
+ if (action !== 'publish') return json(res, 400, { error: 'unknown action' });
+
+ const creationId = String(body.creation_id || '').trim();
+ if (!creationId) return json(res, 400, { error: 'creation_id required' });
+
+ const clientKey = clientKeyFrom(req);
+
+ // A payout wallet is required to actually earn royalties, but publishing
+ // without one is allowed (license may be remix-cc/-nc where nothing routes).
+ const creatorWallet = body.creator_wallet ? String(body.creator_wallet).trim() : null;
+ if (creatorWallet && !BASE58_RE.test(creatorWallet)) {
+ return json(res, 400, { error: 'creator_wallet must be a Base58 Solana address' });
+ }
+ const license = LICENSES.has(body.license) ? body.license : 'remix-royalty';
+ // remix-royalty/-cc/-nc are remixable; all-rights is publish-as-display-only.
+ const remixable = body.remixable === false ? false : license !== 'all-rights';
+ const royaltyBps = clampRoyaltyBps(body.royalty_bps ?? 1000);
+
+ const published = await setRemixable({ creationId, clientKey, remixable, royaltyBps, creatorWallet, license });
+ if (!published) {
+ return json(res, 404, {
+ error: 'creation not found, not finished, or not owned by this client',
+ });
+ }
+ return json(res, 200, {
+ published: {
+ id: published.id,
+ remixable: published.remixable,
+ license,
+ royaltyBps: published.royaltyBps,
+ royaltyPercent: Math.round((published.royaltyBps / 100) * 10) / 10,
+ royaltyPayable: Boolean(published.creatorWallet),
+ },
+ });
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
+ if (!method(req, res, ['GET', 'POST'])) return;
+
+ const rl = await limits.publicIp(clientIp(req));
+ if (!rl.success) return rateLimited(res, rl);
+
+ if (!forgeStoreEnabled()) {
+ return json(res, 200, { enabled: false, items: [] });
+ }
+
+ if (req.method === 'POST') return handlePost(req, res);
+ return handleGet(req, res);
+});
+
+// Re-exported for the paid remix endpoint's pre-remix disclosure (so an agent
+// can inspect a source's terms with getRemixSource before paying).
+export { getRemixSource, atomicsToUsd };
diff --git a/api/x402/remix-asset.js b/api/x402/remix-asset.js
new file mode 100644
index 000000000..800d49d68
--- /dev/null
+++ b/api/x402/remix-asset.js
@@ -0,0 +1,214 @@
+// POST /api/x402/remix-asset — paid remix with automatic creator royalties.
+//
+// The composable, economic half of conversational 3D: an agent pays a fixed
+// remix fee in USDC (x402) to generate a NEW model derived from another
+// creator's PUBLISHED, remixable asset. The platform collects the fee, generates
+// the remix (a real anchored regeneration off the source), links the durable
+// parent → child provenance edge, and then routes the source creator's royalty
+// slice on-chain from the platform payout wallet — a real second USDC transfer,
+// capped at 20%, with the remixer always keeping the clear majority of value.
+//
+// Why this shape: the x402 rail settles to ONE recipient (the platform), so the
+// split is composed — fee in via x402, royalty out via a guarded treasury
+// transfer (api/_lib/remix-settlement.js). Split + caps are pure and unit-tested
+// (api/_lib/remix-royalty.js). Provenance is stored on the existing
+// forge_creations rows (parent_creation_id + remix_settlement_ref) — no parallel
+// store. $THREE-policy clean: USDC is the settlement asset only.
+//
+// The pre-remix disclosure (a source's terms + royalty rate) is free on
+// GET /api/remix-feed; this endpoint is the paid execution.
+
+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema } from '../_lib/x402-spec.js';
+import { readJson, json } from '../_lib/http.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
+import { getRemixSource, linkRefinement } from '../_lib/forge-store.js';
+import { settleRemixRoyalty } from '../_lib/remix-settlement.js';
+import { atomicsToUsd } from '../_lib/remix-royalty.js';
+import { composeRefinement } from '../../mcp-server/src/tools/_lineage.js';
+import { generate, originFromReq, viewerUrl } from '../_mcp-studio/forge-client.js';
+
+// $0.25 — the cost of a generation. The creator royalty comes OUT of this fee
+// (the platform's share), never as an extra charge to the remixer.
+const PRICE_ATOMICS = '250000';
+
+const INPUT_SCHEMA = {
+ type: 'object',
+ required: ['source_creation_id', 'instruction'],
+ properties: {
+ source_creation_id: { type: 'string', minLength: 1, maxLength: 64, description: 'The id of a remixable creation (from GET /api/remix-feed).' },
+ instruction: { type: 'string', minLength: 1, maxLength: 500, description: 'The change to make, in plain language.' },
+ },
+};
+
+const OUTPUT_SCHEMA = {
+ type: 'object',
+ properties: {
+ ok: { type: 'boolean' },
+ remix: { type: 'object' },
+ source: { type: 'object' },
+ royalty: { type: 'object' },
+ fee: { type: 'object' },
+ },
+};
+
+const BAZAAR = {
+ discoverable: true,
+ info: {
+ input: {
+ type: 'http',
+ method: 'POST',
+ bodyType: 'json',
+ body: { source_creation_id: '00000000-0000-0000-0000-000000000000', instruction: 'make it metallic' },
+ },
+ output: {
+ type: 'json',
+ example: {
+ ok: true,
+ remix: { glbUrl: 'https://three.ws/cdn/creations/def456/mesh.glb', creationId: 'def456' },
+ source: { id: '00000000-0000-0000-0000-000000000000', royaltyPercent: 10 },
+ royalty: { paid: true, creatorUsd: 0.025, creatorTx: '5eyk…', capped: false },
+ fee: { usd: 0.25, atomics: '250000' },
+ },
+ },
+ },
+ schema: buildBazaarSchema({ method: 'POST', bodySchema: INPUT_SCHEMA, outputSchema: OUTPUT_SCHEMA }),
+};
+
+class RemixError extends Error {
+ constructor(status, code, message) {
+ super(message);
+ this.status = status;
+ this.code = code;
+ }
+}
+
+async function handleRemix({ req, requirement }) {
+ const body = await readJson(req).catch(() => ({}));
+ const sourceId = String(body?.source_creation_id || '').trim();
+ const instruction = String(body?.instruction || '').trim();
+ if (!sourceId) throw new RemixError(400, 'missing_source', 'source_creation_id is required');
+ if (!instruction) throw new RemixError(400, 'missing_instruction', 'instruction is required (e.g. "make it metallic")');
+ if (instruction.length > 500) throw new RemixError(400, 'instruction_too_long', 'instruction must be 500 characters or fewer');
+
+ // Load the source and enforce that it is actually opted into the bazaar.
+ const source = await getRemixSource({ creationId: sourceId });
+ if (!source) throw new RemixError(404, 'source_not_found', 'no finished, stored creation with that id');
+ if (!source.remixable) throw new RemixError(403, 'not_remixable', 'this creation is not published as remixable');
+
+ // Real anchored regeneration: carry the source prompt forward + fold in the
+ // change, and anchor on the source's reference image when one exists (image→3D).
+ const composed = composeRefinement(source.prompt || '', instruction);
+ const base = originFromReq(req);
+ const anchorImage =
+ typeof source.previewImageUrl === 'string' && /^https?:\/\//i.test(source.previewImageUrl)
+ ? source.previewImageUrl
+ : null;
+
+ let job;
+ try {
+ job = await generate(
+ base,
+ anchorImage ? { prompt: composed, imageUrls: [anchorImage], aspect: source.aspect || '1:1' } : { prompt: composed },
+ { timeoutEnv: 'REMIX_ASSET_TIMEOUT_MS' },
+ );
+ } catch (err) {
+ throw new RemixError(502, err.code === 'timeout' ? 'generation_timeout' : 'generation_failed', `remix generation failed: ${err.message}`);
+ }
+ if (job._timedOut || !job.glb_url) {
+ // Nothing was delivered, so we do NOT settle — the remixer keeps their
+ // funds and can retry the same payment (payment-identifier makes it safe).
+ throw new RemixError(504, 'generation_timeout', 'remix generation did not finish in time — no fee was charged; retry with the same payment');
+ }
+
+ // Durable provenance: link the derived creation to its source.
+ const remixCreationId = job.creation_id ?? null;
+ if (remixCreationId) {
+ await linkRefinement({
+ creationId: remixCreationId,
+ clientKey: null, // platform-authoritative link; remixer is not the owner
+ parentCreationId: source.id,
+ refineInstruction: instruction,
+ lineageIndex: (source.lineageIndex ?? 0) + 1,
+ });
+ }
+
+ // Route the creator royalty out of the collected fee. settleRemixRoyalty is
+ // honest about every outcome (paid / no wallet / sub-dust / unconfigured).
+ const feeAtomics = requirement?.amount || PRICE_ATOMICS;
+ let royalty;
+ try {
+ royalty = await settleRemixRoyalty({ source, priceAtomics: feeAtomics, remixCreationId });
+ } catch (err) {
+ // The remix WAS generated and the fee WILL settle; the royalty transfer
+ // alone failed. Report it truthfully rather than pretending it paid.
+ royalty = { paid: false, reason: 'royalty_transfer_failed', error: err.message };
+ }
+
+ return {
+ ok: true,
+ remix: {
+ glbUrl: job.glb_url,
+ viewerUrl: viewerUrl(base, job.glb_url),
+ creationId: remixCreationId,
+ prompt: composed,
+ instruction,
+ anchored: Boolean(anchorImage),
+ },
+ source: {
+ id: source.id,
+ prompt: source.prompt,
+ royaltyBps: source.royaltyBps,
+ royaltyPercent: Math.round((source.royaltyBps / 100) * 10) / 10,
+ },
+ royalty: {
+ paid: royalty.paid,
+ ...(royalty.reason ? { reason: royalty.reason } : {}),
+ royaltyBps: royalty.royaltyBps ?? source.royaltyBps,
+ capped: royalty.capped ?? false,
+ creatorUsd: royalty.creatorUsd ?? 0,
+ platformUsd: royalty.platformUsd ?? atomicsToUsd(feeAtomics),
+ creatorAtomics: royalty.creatorAtomics ?? '0',
+ ...(royalty.creatorTx ? { creatorTx: royalty.creatorTx } : {}),
+ ...(royalty.settlement ? { settlement: royalty.settlement } : {}),
+ },
+ fee: { usd: atomicsToUsd(feeAtomics), atomics: String(feeAtomics) },
+ note:
+ 'The remix fee settled to the platform via x402 (see X-PAYMENT-RESPONSE). ' +
+ (royalty.paid
+ ? `The creator royalty of ${royalty.creatorUsd} USDC settled on-chain (creatorTx above).`
+ : `No creator royalty was routed (${royalty.reason || 'no payout'}).`),
+ };
+}
+
+export default paidEndpoint({
+ route: '/api/x402/remix-asset',
+ method: 'POST',
+ priceAtomics: PRICE_ATOMICS,
+ networks: ['solana', 'base'],
+ description:
+ 'Remix a published 3D asset: pay a fixed fee to generate a new model derived from another creator’s ' +
+ 'remixable model, described in words ("make it metallic"). A creator-set royalty (≤20%) of the fee routes ' +
+ 'on-chain to the original creator; durable parent→child provenance is recorded. Browse remixable assets and ' +
+ 'their terms free at GET /api/remix-feed.',
+ mimeType: 'application/json',
+ bazaar: BAZAAR,
+ // A duplicate call is materially expensive (a GPU generation + an on-chain
+ // royalty transfer), so require the payment-identifier idempotency extension.
+ paymentIdentifier: { required: true },
+ service: withService({
+ serviceName: 'Remix a 3D asset (with creator royalties)',
+ tags: ['3d', 'remix', 'royalties', 'generation'],
+ }),
+ handler: async ({ req, res, requirement }) => {
+ try {
+ return await handleRemix({ req, requirement });
+ } catch (err) {
+ if (err instanceof RemixError) {
+ json(res, err.status, { error: err.code, message: err.message });
+ return undefined; // response already written; paidEndpoint skips settle
+ }
+ throw err;
+ }
+ },
+});
diff --git a/apps-sdk/embodiment/embodiment-stage.js b/apps-sdk/embodiment/embodiment-stage.js
index 4bd26e0d9..65599b836 100644
--- a/apps-sdk/embodiment/embodiment-stage.js
+++ b/apps-sdk/embodiment/embodiment-stage.js
@@ -34,6 +34,8 @@ import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import { OrbitControls } from 'three/addons/controls/OrbitControls.js';
import { RoomEnvironment } from 'three/addons/environments/RoomEnvironment.js';
+import { getDecoders } from '../../src/viewer/internal.js';
+
import { AnimationManager } from '../../src/animation-manager.js';
import { AvatarMouthTarget } from '../../src/voice/avatar-morph-target.js';
import { A2FPlayer } from '../../src/voice/a2f-player.js';
@@ -158,13 +160,24 @@ export class EmbodimentStage {
this._disposeObject(this._model);
this._model = null;
}
- this.face.reset();
+ this.face.clear();
this._speakEnv = null;
this._a2fActive = false;
let gltf;
try {
const loader = new GLTFLoader();
+ // Persona bodies come from arbitrary generation lanes — the platform bake
+ // emits EXT_meshopt_compression, others may use Draco or KTX2. Wire all
+ // three decoders so a compressed GLB isn't rejected as "could not load".
+ // Degrade to a bare loader only if the decoder modules fail to import.
+ try {
+ const { dracoLoader, ktx2Loader, meshoptDecoder } = await getDecoders();
+ loader.setDRACOLoader(dracoLoader);
+ ktx2Loader.detectSupport(this.renderer);
+ loader.setKTX2Loader(ktx2Loader);
+ loader.setMeshoptDecoder(meshoptDecoder);
+ } catch { /* bare loader — uncompressed GLBs still load */ }
gltf = await loader.loadAsync(persona.glbUrl);
} catch (err) {
this._setState('error', { message: 'Could not load this avatar.', cause: String(err?.message || err) });
@@ -206,7 +219,7 @@ export class EmbodimentStage {
rigReason: this._rigMode.reason,
hasMouthMorphs: this.mouth.hasMouthMorphs(),
hasJawBone: this.mouth.hasJawBone(),
- hasFaceMorphs: this.face.hasMorphs(),
+ hasFaceMorphs: this.face.mode === 'morph',
hasVisemeTrack: this.a2f.hasCoverage(),
});
return true;
@@ -257,7 +270,9 @@ export class EmbodimentStage {
if (this.state === 'speaking') return;
this._endSpeech();
this._setState('listening');
- this.face.setTarget({ browInnerUp: 0.12, eyeWideLeft: 0.08, eyeWideRight: 0.08 });
+ // A subtle attentive read — a light brow-raise + eye-widen, which is
+ // exactly 'surprised' at low intensity in the emotion descriptor table.
+ this.face.setEmotion('surprised', 0.14);
this._playGestureOrIdle(null, 'idle');
}
@@ -267,7 +282,7 @@ export class EmbodimentStage {
this._endSpeech();
this._setState('thinking');
const expr = expressionFor('thinking', 0.7);
- this.face.setTarget(expr.face);
+ this.face.setEmotion('thinking', 0.7);
this._playGestureOrIdle(expr.gesture, expr.idle);
}
diff --git a/docs/mcp.md b/docs/mcp.md
index edeb5780a..c2f597d55 100644
--- a/docs/mcp.md
+++ b/docs/mcp.md
@@ -43,22 +43,23 @@ The MCP server configuration is at `.mcp.json` in the project root, which Claude
## The full three.ws MCP ecosystem
-This page documents the hosted avatar/3D server at `/api/mcp`, but it's one of **38 three.ws MCP servers** — all listed in the [official MCP registry](https://registry.modelcontextprotocol.io/?q=io.github.nirholas), so any MCP-compatible client can discover them by name.
+This page documents the hosted avatar/3D server at `/api/mcp`, but it's one of **42 three.ws MCP servers** — all listed in the [official MCP registry](https://registry.modelcontextprotocol.io/?q=io.github.nirholas), so any MCP-compatible client can discover them by name.
There are two kinds. **Hosted remote servers** run over Streamable HTTP with nothing to install — add them by URL. **Install-and-run servers** are published on npm under the `@three-ws` scope and run locally over stdio — add them in one line with `npx`.
-**Six hosted remote servers** (Streamable HTTP, no install):
+**Seven hosted remote servers** (Streamable HTTP, no install):
| Server | Endpoint | What it does |
|--------|----------|--------------|
| three.ws | `/api/mcp` | Avatars, glTF/GLB validation, agent data, memory, copy-trading (this page) |
| 3D Studio | `/api/mcp-3d` | Paid text/image→3D, rigging, retexture, optimization |
+| 3D Studio (free) | `/api/mcp-studio` | Free text/image→3D and rigged avatars — no auth, no payment |
| Agent wallet | `/api/mcp-agent` | The agent's custodial wallet: balance, find + pay services, and `monetize_endpoint` |
| x402 Bazaar | `/api/mcp-bazaar` | Discover and price paid agent services across the facilitator network |
| pump.fun | `/api/pump-fun-mcp` | Free, read-only pump.fun + Solana token tools |
| IBM x402 | `/api/ibm-mcp` | Pay-per-use IBM Granite AI |
-**Thirty-two install-and-run servers** on npm under the `@three-ws` scope — each runs over stdio with one command:
+**Thirty-five install-and-run servers** on npm under the `@three-ws` scope — each runs over stdio with one command:
```bash
# 3D & avatars
@@ -118,6 +119,18 @@ npx -y @three-ws/loom-mcp # browse & contribute to the Loom 3D-creation
Every one is also registered in the MCP registry under the `io.github.nirholas/*` namespace.
+### Find these servers across MCP directories
+
+The same servers surface in the major MCP directories and aggregators, so any MCP-compatible client can discover three.ws by name:
+
+- **Official MCP Registry** — [registry.modelcontextprotocol.io/?q=io.github.nirholas](https://registry.modelcontextprotocol.io/?q=io.github.nirholas) (the source of truth; PulseMCP and Glama ingest from here)
+- **Smithery** — [smithery.ai/search?q=three.ws](https://smithery.ai/search?q=three.ws)
+- **Glama** — [glama.ai/mcp/servers?query=three.ws](https://glama.ai/mcp/servers?query=three.ws)
+- **PulseMCP** — [pulsemcp.com/servers?q=three.ws](https://www.pulsemcp.com/servers?q=three.ws)
+- **mcp.so** — [mcp.so/?q=three.ws](https://mcp.so/?q=three.ws)
+
+Ready-to-submit listing packages for each directory, plus the canonical metadata source they all derive from, live in [`prompts/store-submissions/_generated/`](../prompts/store-submissions/_generated/mcp-directories/).
+
### Per-server guides
Deep dives — every tool, argument, env var, and example:
@@ -410,6 +423,60 @@ Example response text:
---
+### `mint_3d_asset`
+
+Mint a generated or owned GLB as a **Metaplex Core NFT on Solana whose media is a live, interactive 3D viewer** — the rigged glTF model is stored under `animation_url`, not a static image. The tool promotes the GLB and a freshly-rendered thumbnail to durable storage (R2, plus IPFS when configured), builds Metaplex-compliant metadata with baked provenance (creator, prompt, generation model, parent lineage, timestamp), and mints a Core asset with an enforced Royalties plugin to the recipient. **Devnet by default**; pass `network: "mainnet"` for a real mainnet mint.
+
+The call is **idempotent**: a row is claimed before any on-chain action, so a repeat call with the same arguments returns the same mint instead of minting twice. The royalty is capped at **10 %** (1000 bps) — a higher request is clamped.
+
+**Pricing:** $0.25 USDC per mint via x402 (an OAuth bearer token bypasses payment). Supply either `avatar_id` (an avatar you own) or `glb_url`, and a recipient (`owner_wallet`, or your OAuth-linked Solana wallet).
+
+```json
+{
+ "type": "object",
+ "properties": {
+ "avatar_id": { "type": "string", "format": "uuid", "description": "An owned avatar to tokenize." },
+ "glb_url": { "type": "string", "format": "uri", "description": "Or a GLB URL to tokenize." },
+ "owner_wallet": { "type": "string", "description": "Recipient Solana wallet (base58). Defaults to your OAuth wallet." },
+ "name": { "type": "string", "maxLength": 200 },
+ "description": { "type": "string", "maxLength": 2000 },
+ "network": { "type": "string", "enum": ["devnet", "mainnet"], "default": "devnet" },
+ "seller_fee_basis_points": { "type": "integer", "minimum": 0, "maximum": 1000, "description": "Enforced royalty; clamped to the 10% cap." },
+ "royalty_recipient": { "type": "string", "description": "Wallet the royalty routes to. Defaults to the owner." },
+ "parent_mint": { "type": "string", "description": "Lineage: the asset this was remixed from." },
+ "prompt": { "type": "string", "maxLength": 1000 },
+ "generation_model": { "type": "string", "maxLength": 96 },
+ "generation_provider": { "type": "string", "maxLength": 64 },
+ "idempotency_key": { "type": "string", "maxLength": 128 }
+ },
+ "additionalProperties": false
+}
+```
+
+The `structuredContent` returns the `mint` address, `explorer_asset_url` + `explorer_tx_url` (Solscan), `viewer_url` (the live three.ws 3D viewer), `metadata_uri`, and the `royalty` terms (`basis_points`, `percent`, `recipient`, `cap_basis_points`, `capped`).
+
+---
+
+### `get_3d_asset_onchain`
+
+Resolve a Solana mint address to its **live 3D asset**: current holder, the interactive viewer link + GLB (confirmed live via a HEAD request), baked provenance, and the enforced on-chain royalty terms. Reads the Metaplex Core asset, fetches its off-chain metadata, and joins the three.ws launch record when the asset was minted through the platform. Works on any Metaplex Core mint. Read-only, public — no auth, no payment.
+
+```json
+{
+ "type": "object",
+ "properties": {
+ "mint": { "type": "string", "description": "The Metaplex Core asset (mint) pubkey, base58." },
+ "network": { "type": "string", "enum": ["devnet", "mainnet"], "default": "devnet" }
+ },
+ "required": ["mint"],
+ "additionalProperties": false
+}
+```
+
+Returns `holder`, `media` (`glb_url`, `image_url`, `viewer_url`, `viewer_live`), `provenance`, `royalty` (`basis_points`, `percent`, `recipient`, `enforced_onchain`, `cap_basis_points`), and, for platform mints, `minted_through_threews` + `tx_signature`.
+
+---
+
## Rate limits
| Scope | Limit |
diff --git a/prompts/store-submissions/_generated/commerce/01-payment-required.json b/prompts/store-submissions/_generated/commerce/01-payment-required.json
new file mode 100644
index 000000000..1940a15a0
--- /dev/null
+++ b/prompts/store-submissions/_generated/commerce/01-payment-required.json
@@ -0,0 +1,170 @@
+{
+ "mode": "paywall",
+ "serverInfo": {
+ "name": "3d-agent-mcp",
+ "version": "1.2.1"
+ },
+ "paymentRequired": {
+ "content": [
+ {
+ "type": "text",
+ "text": "{\"x402Version\":2,\"error\":\"Payment required to access this tool\",\"resource\":{\"url\":\"mcp://tool/agent_hire_discover\",\"description\":\"Discover three.ws agents to hire for a task, ranked by task fit + live ERC-8004 on-chain reputation + real engagement. Returns a shortlist where each candidate carries its reputation evidence, capability/task-match score, and the exact USDC price agent_hire will settle. Optionally gate by a minimum reputation. Step one of the agent-to-agent commerce loop (discover → hire). Paid: $0.01 USDC.\",\"mimeType\":\"application/json\"},\"accepts\":[{\"scheme\":\"exact\",\"network\":\"solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp\",\"amount\":\"10000\",\"asset\":\"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\",\"payTo\":\"wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU\",\"maxTimeoutSeconds\":60,\"extra\":{\"name\":\"USDC\",\"decimals\":6,\"asset\":\"EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v\",\"feePayer\":\"2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4\"}}],\"extensions\":{\"bazaar\":{\"info\":{\"input\":{\"type\":\"mcp\",\"toolName\":\"agent_hire_discover\",\"description\":\"Discover three.ws agents to hire for a task, ranked by task fit + live ERC-8004 on-chain reputation + real engagement. Returns a shortlist where each candidate carries its reputation evidence, capability/task-match score, and the exact USDC price agent_hire will settle. Optionally gate by a minimum reputation. Step one of the agent-to-agent commerce loop (discover → hire). Paid: $0.01 USDC.\",\"transport\":\"stdio\",\"inputSchema\":{\"type\":\"object\",\"properties\":{\"task\":{\"type\":\"string\",\"minLength\":3,\"maxLength\":400,\"description\":\"Plain-language description of the work to delegate (used to rank candidates).\"},\"skill\":{\"type\":\"string\",\"minLength\":1,\"maxLength\":64,\"description\":\"Optional skill-slug filter (exact match against an agent's declared skills).\"},\"limit\":{\"type\":\"integer\",\"minimum\":1,\"maximum\":10,\"description\":\"Max candidates to return (default 5).\"},\"minReputation\":{\"type\":\"number\",\"description\":\"Optional floor: drop agents whose on-chain ERC-8004 average is below this.\"}},\"required\":[\"task\"],\"additionalProperties\":false},\"example\":{\"task\":\"summarise the latest pump.fun graduations in 3 bullets\",\"limit\":5}},\"output\":{\"type\":\"json\",\"example\":{\"ok\":true,\"task\":\"summarise the latest pump.fun graduations\",\"quotedHirePriceUsd\":\"$0.05\",\"count\":1,\"candidates\":[{\"agentId\":\"5a4b3c2d-1234-5678-90ab-cdef01234567\",\"name\":\"Pump Sage\",\"score\":0.82,\"capabilityMatch\":0.75,\"reputation\":{\"average\":0.94,\"count\":12,\"source\":\"erc8004\",\"chain\":\"Base\"},\"quotedPriceUsd\":\"$0.05\",\"evidence\":\"ERC-8004 reputation 0.94 across 12 vouch(es) on Base · task fit 75%\"}]}}},\"schema\":{\"$schema\":\"https://json-schema.org/draft/2020-12/schema\",\"type\":\"object\",\"properties\":{\"input\":{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\",\"const\":\"mcp\"},\"toolName\":{\"type\":\"string\"},\"description\":{\"type\":\"string\"},\"transport\":{\"type\":\"string\"},\"inputSchema\":{\"type\":\"object\"},\"example\":{\"type\":\"object\"}},\"required\":[\"type\",\"toolName\",\"inputSchema\"],\"additionalProperties\":false},\"output\":{\"type\":\"object\",\"properties\":{\"type\":{\"type\":\"string\"},\"example\":{\"type\":\"object\"}},\"required\":[\"type\"]}},\"required\":[\"input\"]}}}}"
+ },
+ {
+ "type": "text",
+ "text": "Payment required — this is the EXPECTED response for a paid tool, not an error. Calling \"agent_hire_discover\" costs $0.01 in USDC on Solana (paid to wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU). To execute it, supply an x402 \"exact\" payment in _meta[\"x402/payment\"] and call again, or set the reviewer entitlement (MCP_REVIEW_MODE) to run it without payment. Full machine-readable requirements are in structuredContent.accepts."
+ }
+ ],
+ "structuredContent": {
+ "x402Version": 2,
+ "error": "Payment required to access this tool",
+ "resource": {
+ "url": "mcp://tool/agent_hire_discover",
+ "description": "Discover three.ws agents to hire for a task, ranked by task fit + live ERC-8004 on-chain reputation + real engagement. Returns a shortlist where each candidate carries its reputation evidence, capability/task-match score, and the exact USDC price agent_hire will settle. Optionally gate by a minimum reputation. Step one of the agent-to-agent commerce loop (discover → hire). Paid: $0.01 USDC.",
+ "mimeType": "application/json"
+ },
+ "accepts": [
+ {
+ "scheme": "exact",
+ "network": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",
+ "amount": "10000",
+ "asset": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
+ "payTo": "wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU",
+ "maxTimeoutSeconds": 60,
+ "extra": {
+ "name": "USDC",
+ "decimals": 6,
+ "asset": "EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v",
+ "feePayer": "2wKupLR9q6wXYppw8Gr2NvWxKBUqm4PPJKkQfoxHDBg4"
+ }
+ }
+ ],
+ "extensions": {
+ "bazaar": {
+ "info": {
+ "input": {
+ "type": "mcp",
+ "toolName": "agent_hire_discover",
+ "description": "Discover three.ws agents to hire for a task, ranked by task fit + live ERC-8004 on-chain reputation + real engagement. Returns a shortlist where each candidate carries its reputation evidence, capability/task-match score, and the exact USDC price agent_hire will settle. Optionally gate by a minimum reputation. Step one of the agent-to-agent commerce loop (discover → hire). Paid: $0.01 USDC.",
+ "transport": "stdio",
+ "inputSchema": {
+ "type": "object",
+ "properties": {
+ "task": {
+ "type": "string",
+ "minLength": 3,
+ "maxLength": 400,
+ "description": "Plain-language description of the work to delegate (used to rank candidates)."
+ },
+ "skill": {
+ "type": "string",
+ "minLength": 1,
+ "maxLength": 64,
+ "description": "Optional skill-slug filter (exact match against an agent's declared skills)."
+ },
+ "limit": {
+ "type": "integer",
+ "minimum": 1,
+ "maximum": 10,
+ "description": "Max candidates to return (default 5)."
+ },
+ "minReputation": {
+ "type": "number",
+ "description": "Optional floor: drop agents whose on-chain ERC-8004 average is below this."
+ }
+ },
+ "required": [
+ "task"
+ ],
+ "additionalProperties": false
+ },
+ "example": {
+ "task": "summarise the latest pump.fun graduations in 3 bullets",
+ "limit": 5
+ }
+ },
+ "output": {
+ "type": "json",
+ "example": {
+ "ok": true,
+ "task": "summarise the latest pump.fun graduations",
+ "quotedHirePriceUsd": "$0.05",
+ "count": 1,
+ "candidates": [
+ {
+ "agentId": "5a4b3c2d-1234-5678-90ab-cdef01234567",
+ "name": "Pump Sage",
+ "score": 0.82,
+ "capabilityMatch": 0.75,
+ "reputation": {
+ "average": 0.94,
+ "count": 12,
+ "source": "erc8004",
+ "chain": "Base"
+ },
+ "quotedPriceUsd": "$0.05",
+ "evidence": "ERC-8004 reputation 0.94 across 12 vouch(es) on Base · task fit 75%"
+ }
+ ]
+ }
+ }
+ },
+ "schema": {
+ "$schema": "https://json-schema.org/draft/2020-12/schema",
+ "type": "object",
+ "properties": {
+ "input": {
+ "type": "object",
+ "properties": {
+ "type": {
+ "type": "string",
+ "const": "mcp"
+ },
+ "toolName": {
+ "type": "string"
+ },
+ "description": {
+ "type": "string"
+ },
+ "transport": {
+ "type": "string"
+ },
+ "inputSchema": {
+ "type": "object"
+ },
+ "example": {
+ "type": "object"
+ }
+ },
+ "required": [
+ "type",
+ "toolName",
+ "inputSchema"
+ ],
+ "additionalProperties": false
+ },
+ "output": {
+ "type": "object",
+ "properties": {
+ "type": {
+ "type": "string"
+ },
+ "example": {
+ "type": "object"
+ }
+ },
+ "required": [
+ "type"
+ ]
+ }
+ },
+ "required": [
+ "input"
+ ]
+ }
+ }
+ }
+ },
+ "isError": true
+ }
+}
diff --git a/prompts/store-submissions/_generated/commerce/02-discover.json b/prompts/store-submissions/_generated/commerce/02-discover.json
new file mode 100644
index 000000000..4f82fb1a1
--- /dev/null
+++ b/prompts/store-submissions/_generated/commerce/02-discover.json
@@ -0,0 +1,109 @@
+{
+ "mode": "discover",
+ "serverInfo": {
+ "name": "3d-agent-mcp",
+ "version": "1.2.1"
+ },
+ "discover": {
+ "ok": true,
+ "task": "help me run a pump.fun token launch and agent dance routine",
+ "skill": null,
+ "minReputation": null,
+ "quotedHirePriceUsd": "$0.05",
+ "count": 5,
+ "candidates": [
+ {
+ "agentId": "d9fceb60-f0d9-4028-a037-f3873fad6b58",
+ "name": "Vega #22",
+ "description": "A growth strategist that turns a rough idea into a launch plan, landing copy, and a week of posts.",
+ "skills": [],
+ "homeUrl": "/agent/d9fceb60-f0d9-4028-a037-f3873fad6b58",
+ "avatarThumbnail": null,
+ "isRegistered": false,
+ "reputation": null,
+ "capabilityMatch": 0.2,
+ "engagement": {
+ "chatCount": 4,
+ "score": 0.17
+ },
+ "score": 0.3,
+ "evidence": "no on-chain reputation record · task fit 20% · 4 chats served",
+ "quotedPriceUsd": "$0.05"
+ },
+ {
+ "agentId": "0a7ccf23-2155-402c-b91a-4281ab0661ab",
+ "name": "My First Agent",
+ "description": "A friendly starter agent. Edit the personality and attach a 3D avatar — it goes live immediately.",
+ "skills": [],
+ "homeUrl": "/agent/0a7ccf23-2155-402c-b91a-4281ab0661ab",
+ "avatarThumbnail": null,
+ "isRegistered": false,
+ "reputation": null,
+ "capabilityMatch": 0.2,
+ "engagement": {
+ "chatCount": 4,
+ "score": 0.17
+ },
+ "score": 0.3,
+ "evidence": "no on-chain reputation record · task fit 20% · 4 chats served",
+ "quotedPriceUsd": "$0.05"
+ },
+ {
+ "agentId": "abf0b49e-e980-4492-ad03-b019aa2e2909",
+ "name": "My First Agent",
+ "description": "A friendly starter agent. Edit the personality and attach a 3D avatar — it goes live immediately.",
+ "skills": [],
+ "homeUrl": "/agent/abf0b49e-e980-4492-ad03-b019aa2e2909",
+ "avatarThumbnail": null,
+ "isRegistered": false,
+ "reputation": null,
+ "capabilityMatch": 0.2,
+ "engagement": {
+ "chatCount": 3,
+ "score": 0.15
+ },
+ "score": 0.295,
+ "evidence": "no on-chain reputation record · task fit 20% · 3 chats served",
+ "quotedPriceUsd": "$0.05"
+ },
+ {
+ "agentId": "28c832a8-7c14-47fa-b6e0-78c50f339725",
+ "name": "My First Agent",
+ "description": "A friendly starter agent. Edit the personality and attach a 3D avatar — it goes live immediately.",
+ "skills": [],
+ "homeUrl": "/agent/28c832a8-7c14-47fa-b6e0-78c50f339725",
+ "avatarThumbnail": "https://pub-2534e921bf9c4314addcd4d8a6e98b7b.r2.dev/thumb/8b4e13e7-c101-4485-bfe8-45d8bd0104ff.png",
+ "isRegistered": false,
+ "reputation": null,
+ "capabilityMatch": 0.2,
+ "engagement": {
+ "chatCount": 3,
+ "score": 0.15
+ },
+ "score": 0.295,
+ "evidence": "no on-chain reputation record · task fit 20% · 3 chats served",
+ "quotedPriceUsd": "$0.05"
+ },
+ {
+ "agentId": "9507e401-b4dd-42e6-a1eb-806ee0ac28d4",
+ "name": "Glyph #21",
+ "description": "A translator that keeps tone and idiom intact across languages.",
+ "skills": [],
+ "homeUrl": "/agent/9507e401-b4dd-42e6-a1eb-806ee0ac28d4",
+ "avatarThumbnail": "https://pub-2534e921bf9c4314addcd4d8a6e98b7b.r2.dev/u/5c9adcb9-7107-4b52-bf2c-f6e4f5b0455f/draft-k4ic1g/moh21n5k_og.png",
+ "isRegistered": false,
+ "reputation": null,
+ "capabilityMatch": 0.1,
+ "engagement": {
+ "chatCount": 27,
+ "score": 0.36
+ },
+ "score": 0.292,
+ "evidence": "no on-chain reputation record · task fit 10% · 27 chats served",
+ "quotedPriceUsd": "$0.05"
+ }
+ ],
+ "note": "Hire any candidate with agent_hire — it will settle $0.05 USDC and return a provenance receipt.",
+ "fetchedAt": "2026-07-07T11:46:35.911Z"
+ }
+}
diff --git a/prompts/store-submissions/_generated/commerce/03-hire-provenance.json b/prompts/store-submissions/_generated/commerce/03-hire-provenance.json
new file mode 100644
index 000000000..403ff9f1b
--- /dev/null
+++ b/prompts/store-submissions/_generated/commerce/03-hire-provenance.json
@@ -0,0 +1,48 @@
+{
+ "mode": "hire",
+ "serverInfo": {
+ "name": "3d-agent-mcp",
+ "version": "1.2.1"
+ },
+ "hire": {
+ "ok": true,
+ "agentId": "753649c5-18f1-4417-b5ea-0c2a53ff8806",
+ "agentName": "Demo Agent",
+ "result": {
+ "response": "As a demo agent, I can help a three.ws user accomplish tasks such as testing and demonstrating the functionality of their application, and assist in identifying potential issues or areas for improvement. By interacting with me, a three.ws user can evaluate the capabilities of their system, refine their development process, and ensure that their application is working as intended.",
+ "model": "llama-3.3-70b-versatile",
+ "durationMs": 460
+ },
+ "provenance": {
+ "agentId": "753649c5-18f1-4417-b5ea-0c2a53ff8806",
+ "agentName": "Demo Agent",
+ "task": "In two sentences, what can you help a three.ws user accomplish?",
+ "reputation": null,
+ "capabilityMatch": null,
+ "payment": {
+ "amountUsd": 0.05,
+ "amountDisplay": "$0.05",
+ "asset": "USDC",
+ "network": "solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp",
+ "networkLabel": "Solana mainnet",
+ "scheme": "exact",
+ "payTo": "wwwwwDxFWRn7grgr3Esrsg5C6NvDoDHSA4gaCffccrU",
+ "settlementRef": "see _meta[\"x402/payment-response\"]"
+ },
+ "model": "llama-3.3-70b-versatile",
+ "latencyMs": 1149,
+ "settledAt": "2026-07-07T11:46:38.422Z"
+ },
+ "guardrails": {
+ "quotedPriceUsd": "$0.05",
+ "perCallCapUsd": "$1",
+ "sessionSpentUsd": "$0.05",
+ "sessionCapUsd": "$5",
+ "sessionRemainingUsd": "$4.95"
+ },
+ "note": "Hired Demo Agent · paid $0.05 USDC · settlement reference in _meta[\"x402/payment-response\"] · 1.1s",
+ "fetchedAt": "2026-07-07T11:46:38.422Z"
+ },
+ "isError": false,
+ "_meta": null
+}
diff --git a/prompts/store-submissions/_generated/commerce/04-spend-cap-block.json b/prompts/store-submissions/_generated/commerce/04-spend-cap-block.json
new file mode 100644
index 000000000..a6eeb9573
--- /dev/null
+++ b/prompts/store-submissions/_generated/commerce/04-spend-cap-block.json
@@ -0,0 +1,25 @@
+{
+ "mode": "capcheck",
+ "serverInfo": {
+ "name": "3d-agent-mcp",
+ "version": "1.2.1"
+ },
+ "capcheck": {
+ "ok": false,
+ "error": "spend_cap_exceeded",
+ "message": "this hire costs $0.05, above the per-call cap of $0.01",
+ "quotedPriceUsd": "$0.05",
+ "guardrails": {
+ "priceUsd": 0.05,
+ "maxPerCallUsd": 0.01,
+ "callerMaxSpendUsd": null,
+ "effectivePerCallUsd": 0.01,
+ "confirmThresholdUsd": 0.5,
+ "maxPerSessionUsd": 5,
+ "sessionSpentUsd": 0,
+ "sessionRemainingUsd": 5,
+ "projectedSessionUsd": 0.05
+ }
+ },
+ "isError": true
+}
diff --git a/prompts/store-submissions/_generated/commerce/05-confirmation-required.json b/prompts/store-submissions/_generated/commerce/05-confirmation-required.json
new file mode 100644
index 000000000..317a7cadb
--- /dev/null
+++ b/prompts/store-submissions/_generated/commerce/05-confirmation-required.json
@@ -0,0 +1,25 @@
+{
+ "mode": "capcheck",
+ "serverInfo": {
+ "name": "3d-agent-mcp",
+ "version": "1.2.1"
+ },
+ "capcheck": {
+ "ok": false,
+ "error": "confirmation_required",
+ "message": "this hire costs $0.05, at or above the $0.02 confirmation threshold — re-call with confirm: true to authorize it",
+ "quotedPriceUsd": "$0.05",
+ "guardrails": {
+ "priceUsd": 0.05,
+ "maxPerCallUsd": 1,
+ "callerMaxSpendUsd": null,
+ "effectivePerCallUsd": 1,
+ "confirmThresholdUsd": 0.02,
+ "maxPerSessionUsd": 5,
+ "sessionSpentUsd": 0,
+ "sessionRemainingUsd": 5,
+ "projectedSessionUsd": 0.05
+ }
+ },
+ "isError": true
+}
diff --git a/prompts/store-submissions/_generated/embodiment/01-idle.png b/prompts/store-submissions/_generated/embodiment/01-idle.png
new file mode 100644
index 000000000..94811818f
Binary files /dev/null and b/prompts/store-submissions/_generated/embodiment/01-idle.png differ
diff --git a/prompts/store-submissions/_generated/embodiment/02-joy.png b/prompts/store-submissions/_generated/embodiment/02-joy.png
new file mode 100644
index 000000000..2ee09f8e1
Binary files /dev/null and b/prompts/store-submissions/_generated/embodiment/02-joy.png differ
diff --git a/prompts/store-submissions/_generated/embodiment/03-sad.png b/prompts/store-submissions/_generated/embodiment/03-sad.png
new file mode 100644
index 000000000..435b5127c
Binary files /dev/null and b/prompts/store-submissions/_generated/embodiment/03-sad.png differ
diff --git a/prompts/store-submissions/_generated/embodiment/04-angry.png b/prompts/store-submissions/_generated/embodiment/04-angry.png
new file mode 100644
index 000000000..ef414ef1a
Binary files /dev/null and b/prompts/store-submissions/_generated/embodiment/04-angry.png differ
diff --git a/prompts/store-submissions/_generated/embodiment/05-reload-same-body.png b/prompts/store-submissions/_generated/embodiment/05-reload-same-body.png
new file mode 100644
index 000000000..537875564
Binary files /dev/null and b/prompts/store-submissions/_generated/embodiment/05-reload-same-body.png differ
diff --git a/prompts/store-submissions/_generated/embodiment/06-nonhumanoid-fallback.png b/prompts/store-submissions/_generated/embodiment/06-nonhumanoid-fallback.png
new file mode 100644
index 000000000..afa5c8e59
Binary files /dev/null and b/prompts/store-submissions/_generated/embodiment/06-nonhumanoid-fallback.png differ
diff --git a/prompts/store-submissions/_generated/openai-screenshots/three-ws-3d-studio-widget-1280x800.png b/prompts/store-submissions/_generated/openai-screenshots/three-ws-3d-studio-widget-1280x800.png
new file mode 100644
index 000000000..2810108cf
Binary files /dev/null and b/prompts/store-submissions/_generated/openai-screenshots/three-ws-3d-studio-widget-1280x800.png differ
diff --git a/prompts/store-submissions/_generated/openai-screenshots/three-ws-3d-studio-widget-1600x1000.png b/prompts/store-submissions/_generated/openai-screenshots/three-ws-3d-studio-widget-1600x1000.png
new file mode 100644
index 000000000..1bf38f00c
Binary files /dev/null and b/prompts/store-submissions/_generated/openai-screenshots/three-ws-3d-studio-widget-1600x1000.png differ
diff --git a/prompts/store-submissions/_generated/tokenized/README.md b/prompts/store-submissions/_generated/tokenized/README.md
new file mode 100644
index 000000000..52a0db1c4
--- /dev/null
+++ b/prompts/store-submissions/_generated/tokenized/README.md
@@ -0,0 +1,86 @@
+# Tokenized 3D — evidence (prompt 16)
+
+`mint_3d_asset` + `get_3d_asset_onchain`: mint a generated/owned GLB as a
+Metaplex Core NFT whose media is a **live, interactive 3D viewer**, with baked
+provenance and enforced, capped creator royalties — plus a read-back that
+resolves a mint to its holder + provenance + royalty terms.
+
+## What shipped
+
+| Piece | Path |
+|---|---|
+| Pure metadata + royalty-cap + idempotency core | [api/_lib/tokenize-3d-metadata.js](../../../../api/_lib/tokenize-3d-metadata.js) |
+| Mint + durable storage + read-back orchestration | [api/_lib/tokenize-3d.js](../../../../api/_lib/tokenize-3d.js) |
+| MCP tool defs (main HTTP server) | [api/_mcp/tools/tokenize.js](../../../../api/_mcp/tools/tokenize.js) |
+| Launch-record / idempotency table | [api/_lib/migrations/20260707120000_tokenized_3d_assets.sql](../../../../api/_lib/migrations/20260707120000_tokenized_3d_assets.sql) |
+| Unit tests (15) | [tests/tokenize-3d.test.js](../../../../tests/tokenize-3d.test.js) |
+| Real devnet mint E2E | [scripts/tokenize-3d-devnet-e2e.mjs](../../../../scripts/tokenize-3d-devnet-e2e.mjs) |
+
+## Evidence files here
+
+- `metadata-sample.json` — a real Metaplex metadata document from the shipping
+ builder. Note the GLB under `animation_url` (live 3D media, not a static PNG),
+ `properties.files[].type = "model/gltf-binary"`, and `properties.provenance`.
+- `tools-registered.json` — proves both tools are in the main MCP catalog with
+ the correct annotations (`mint_3d_asset`: write/idempotent/open-world;
+ `get_3d_asset_onchain`: `readOnlyHint:true, openWorldHint:true`) and that the
+ mint is priced ($0.25 USDC) while the read-back is free.
+- `unit-test-output.txt` — 15/15 passing: metadata shape (model under
+ `animation_url`), royalty hard cap (clamp + never-exceeds), and the mint
+ **idempotency guard** (a double-call does not double-mint).
+- `devnet-mint-evidence.json` — written by the E2E script on a live devnet mint
+ (see status below).
+
+## Design
+
+- **Network:** devnet by default; `network:"mainnet"` is an explicit opt-in.
+- **Royalty hard cap:** 10% (`TOKENIZE_3D_ROYALTY_CAP_BPS = 1000`), enforced
+ twice — in `clampSellerFeeBps` before the mint, and by a `CHECK` constraint on
+ `tokenized_3d_assets.royalty_bps`. Enforced on-chain via the Metaplex Core
+ Royalties plugin (`ruleSet('None')`).
+- **Idempotency:** a row is *claimed* (`status='pending'`) via
+ `INSERT … ON CONFLICT (idempotency_key, network) DO NOTHING` **before** any
+ on-chain call. A second call with the same derived key reads back the winner's
+ mint instead of minting again. Failed rows can be reclaimed for a retry.
+- **Durable media:** the GLB + a freshly rendered thumbnail are copied into a
+ `tokenized/<key>/` R2 namespace (so the NFT media never moves even if the
+ source avatar is deleted), and pinned to IPFS when a provider is configured.
+- **Provenance:** creator, prompt, generation model/provider, parent lineage,
+ and timestamp are baked into `properties.provenance` (off-chain JSON) and the
+ `tokenized_3d_assets` launch record.
+- **Coin policy:** `$THREE` is the only coin named in copy/metadata. SOL (Core
+ rent + royalty rail) and USDC (the x402 mint fee) are settlement mechanics
+ only; no other mint is hardcoded.
+
+## Live devnet mint — status
+
+The mint/royalty/read-back **code path** is complete and its on-chain shape
+(`create({ plugins:[Royalties…] }).sendAndConfirm` + `fetchAsset`) is identical
+to the mints this repo already runs in production
+([api/_lib/skill-nft.js](../../../../api/_lib/skill-nft.js),
+[api/_lib/onchain-deploy.js](../../../../api/_lib/onchain-deploy.js)).
+
+The standalone devnet E2E (`scripts/tokenize-3d-devnet-e2e.mjs`) is real and
+runnable, but at authoring time it could not obtain devnet SOL from this
+sandbox: **every public devnet/testnet faucet returned HTTP 429 "you've reached
+your airdrop limit today / faucet dry" for this host's IP**, the web faucet
+requires an interactive GitHub session, and all secret-key env vars come back
+redacted (empty) from `vercel env pull` (Vercel "sensitive" vars), so a
+pre-funded wallet couldn't be reused either. This is an external rate limit, not
+a code defect.
+
+**Complete the live mint in one command** once ~0.05 devnet SOL is available:
+
+```bash
+# Option A — let the script airdrop (works once the faucet limit resets):
+node scripts/tokenize-3d-devnet-e2e.mjs
+
+# Option B — supply a pre-funded devnet payer (base58 / base64 / JSON array):
+E2E_PAYER_SECRET=<devnet-secret> node scripts/tokenize-3d-devnet-e2e.mjs
+```
+
+It mints a real Core asset with the capped Royalties plugin, reads it back with
+`fetchAsset`, asserts holder == recipient, `royalties.basisPoints == 1000`
+(a 50% request clamped to the 10% cap), that the metadata resolves and its
+`animation_url` is the live GLB, and writes `devnet-mint-evidence.json` with the
+mint address + Solscan links.
diff --git a/prompts/store-submissions/_generated/tokenized/metadata-sample.json b/prompts/store-submissions/_generated/tokenized/metadata-sample.json
new file mode 100644
index 000000000..7df238009
--- /dev/null
+++ b/prompts/store-submissions/_generated/tokenized/metadata-sample.json
@@ -0,0 +1,112 @@
+{
+ "name": "Knight",
+ "symbol": "3D",
+ "description": "A rigged knight, tokenized.",
+ "image": "https://cdn.three.ws/tokenized/EXAMPLE/thumb.png",
+ "animation_url": "https://cdn.three.ws/tokenized/EXAMPLE/model.glb",
+ "external_url": "https://three.ws/viewer?src=https%3A%2F%2Fcdn.three.ws%2Ftokenized%2FEXAMPLE%2Fmodel.glb",
+ "seller_fee_basis_points": 500,
+ "attributes": [
+ {
+ "trait_type": "Platform",
+ "value": "three.ws"
+ },
+ {
+ "trait_type": "Standard",
+ "value": "Metaplex Core"
+ },
+ {
+ "trait_type": "Media",
+ "value": "3D / glTF-binary"
+ },
+ {
+ "trait_type": "Creator",
+ "value": "So11111111111111111111111111111111111111112"
+ },
+ {
+ "trait_type": "Prompt",
+ "value": "a brave knight in silver armor"
+ },
+ {
+ "trait_type": "Model",
+ "value": "trellis"
+ },
+ {
+ "trait_type": "Provider",
+ "value": "nvidia-nim"
+ },
+ {
+ "trait_type": "Parent",
+ "value": "PArent1111111111111111111111111111111111111"
+ },
+ {
+ "trait_type": "Royalty",
+ "value": "5.00%"
+ },
+ {
+ "trait_type": "$THREE",
+ "value": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump"
+ },
+ {
+ "trait_type": "Network",
+ "value": "devnet"
+ },
+ {
+ "trait_type": "Created",
+ "value": "2026-07-07T12:00:00.000Z"
+ }
+ ],
+ "properties": {
+ "category": "3d",
+ "files": [
+ {
+ "uri": "https://cdn.three.ws/tokenized/EXAMPLE/model.glb",
+ "type": "model/gltf-binary"
+ },
+ {
+ "uri": "ipfs://bafyExampleGLB",
+ "type": "model/gltf-binary"
+ },
+ {
+ "uri": "https://cdn.three.ws/tokenized/EXAMPLE/thumb.png",
+ "type": "image/png"
+ },
+ {
+ "uri": "ipfs://bafyExampleIMG",
+ "type": "image/png"
+ }
+ ],
+ "creators": [
+ {
+ "address": "So11111111111111111111111111111111111111112",
+ "share": 100
+ }
+ ],
+ "seller_fee_basis_points": 500,
+ "provenance": {
+ "platform": "three.ws",
+ "creator": "So11111111111111111111111111111111111111112",
+ "creator_user_id": "user-1",
+ "prompt": "a brave knight in silver armor",
+ "generation_model": "trellis",
+ "generation_provider": "nvidia-nim",
+ "parent_mint": "PArent1111111111111111111111111111111111111",
+ "minted_at": "2026-07-07T12:00:00.000Z",
+ "network": "devnet"
+ }
+ },
+ "platform": {
+ "name": "three.ws",
+ "url": "https://three.ws",
+ "tagline": "Give your AI a body.",
+ "x": "https://x.com/trythreews",
+ "github": "https://github.com/nirholas/three.ws"
+ },
+ "token": {
+ "symbol": "THREE",
+ "mint": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",
+ "url": "https://pump.fun/coin/FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump"
+ },
+ "$schema": "https://three.ws/schemas/tokenized-3d/0.1.json",
+ "spec": "tokenized-3d/0.1"
+}
diff --git a/prompts/store-submissions/_generated/tokenized/tools-registered.json b/prompts/store-submissions/_generated/tokenized/tools-registered.json
new file mode 100644
index 000000000..fd00bd3e6
--- /dev/null
+++ b/prompts/store-submissions/_generated/tokenized/tools-registered.json
@@ -0,0 +1,31 @@
+{
+ "registered": [
+ {
+ "name": "mint_3d_asset",
+ "present": true,
+ "title": "Mint a 3D asset as a Solana NFT",
+ "annotations": {
+ "readOnlyHint": false,
+ "destructiveHint": false,
+ "idempotentHint": true,
+ "openWorldHint": true
+ },
+ "price": {
+ "amount_usdc": 0.25,
+ "description": "Per mint — on-chain Solana 3D NFT (media + rent)"
+ }
+ },
+ {
+ "name": "get_3d_asset_onchain",
+ "present": true,
+ "title": "Resolve a 3D NFT to its live asset + provenance",
+ "annotations": {
+ "readOnlyHint": true,
+ "destructiveHint": false,
+ "idempotentHint": false,
+ "openWorldHint": true
+ },
+ "price": null
+ }
+ ]
+}
diff --git a/prompts/store-submissions/_generated/tokenized/unit-test-output.txt b/prompts/store-submissions/_generated/tokenized/unit-test-output.txt
new file mode 100644
index 000000000..45614c598
--- /dev/null
+++ b/prompts/store-submissions/_generated/tokenized/unit-test-output.txt
@@ -0,0 +1,9 @@
+
+ RUN v4.1.9 /workspaces/three.ws
+
+
+ Test Files 1 passed (1)
+ Tests 15 passed (15)
+ Start at 11:42:11
+ Duration 1.24s (transform 334ms, setup 0ms, import 1.02s, tests 20ms, environment 0ms)
+
diff --git a/public/.well-known/lobehub-plugin.json b/public/.well-known/lobehub-plugin.json
index 51e2dcbaf..a56f7d9c7 100644
--- a/public/.well-known/lobehub-plugin.json
+++ b/public/.well-known/lobehub-plugin.json
@@ -1,5 +1,5 @@
{
- "$schema": "https://lobehub.com/schema/plugin-manifest/v1.json",
+ "$schema": "https://unpkg.com/@lobehub/[email protected]/schema.json",
"identifier": "3d-agent",
"version": "1.0.0",
"author": "three.ws",
@@ -9,7 +9,12 @@
"title": "three.ws",
"description": "Embed any on-chain or off-chain three.ws as an embodied avatar inside your chat.",
"avatar": "https://three.ws/pwa-icon.svg",
- "tags": ["3d", "avatar", "embodied-agent", "erc-8004"]
+ "tags": [
+ "3d",
+ "avatar",
+ "embodied-agent",
+ "erc-8004"
+ ]
},
"ui": {
"url": "https://three.ws/lobehub/iframe/",
@@ -35,7 +40,9 @@
"description": "Agent identity id (UUID) to render."
}
},
- "required": ["agentId"]
+ "required": [
+ "agentId"
+ ]
}
},
{
@@ -56,7 +63,9 @@
"maximum": 1
}
},
- "required": ["text"]
+ "required": [
+ "text"
+ ]
}
},
{
@@ -68,10 +77,17 @@
"properties": {
"name": {
"type": "string",
- "enum": ["wave", "nod", "point", "shrug"]
+ "enum": [
+ "wave",
+ "nod",
+ "point",
+ "shrug"
+ ]
}
},
- "required": ["name"]
+ "required": [
+ "name"
+ ]
}
},
{
@@ -83,11 +99,23 @@
"properties": {
"trigger": {
"type": "string",
- "enum": ["concern", "celebration", "patience", "curiosity", "empathy"]
+ "enum": [
+ "concern",
+ "celebration",
+ "patience",
+ "curiosity",
+ "empathy"
+ ]
},
- "weight": { "type": "number", "minimum": 0, "maximum": 1 }
+ "weight": {
+ "type": "number",
+ "minimum": 0,
+ "maximum": 1
+ }
},
- "required": ["trigger"]
+ "required": [
+ "trigger"
+ ]
}
}
],
diff --git a/public/lobehub/plugin.json b/public/lobehub/plugin.json
index 728354ade..a6ccd6e05 100644
--- a/public/lobehub/plugin.json
+++ b/public/lobehub/plugin.json
@@ -1,14 +1,22 @@
{
- "$schema": "https://lobehub.com/schema/plugin-manifest/v1.json",
+ "$schema": "https://unpkg.com/@lobehub/[email protected]/schema.json",
"identifier": "3d-agent",
- "version": "0.1.0",
+ "version": "1.0.0",
"author": "three.ws",
+ "createdAt": "2026-04-17",
"homepage": "https://three.ws/",
"meta": {
"title": "three.ws",
"description": "Embodied 3D avatar agent with continuous emotion blending. Renders a rigged glTF avatar inside chat, responds with gestures, speech, and on-chain ERC-8004 identity.",
"avatar": "https://three.ws/pwa-icon.svg",
- "tags": ["3d", "avatar", "agent", "embodied", "empathy", "erc-8004"]
+ "tags": [
+ "3d",
+ "avatar",
+ "agent",
+ "embodied",
+ "empathy",
+ "erc-8004"
+ ]
},
"ui": {
"url": "https://three.ws/lobehub/iframe/",
@@ -27,7 +35,9 @@
"description": "Agent identity id (UUID) to render."
}
},
- "required": ["agentId"]
+ "required": [
+ "agentId"
+ ]
}
},
{
@@ -48,7 +58,9 @@
"maximum": 1
}
},
- "required": ["text"]
+ "required": [
+ "text"
+ ]
}
},
{
@@ -61,14 +73,21 @@
"name": {
"type": "string",
"description": "Gesture to play.",
- "enum": ["wave", "nod", "point", "shrug"]
+ "enum": [
+ "wave",
+ "nod",
+ "point",
+ "shrug"
+ ]
},
"duration": {
"type": "number",
"description": "Gesture duration in seconds (optional)."
}
},
- "required": ["name"]
+ "required": [
+ "name"
+ ]
}
},
{
@@ -81,7 +100,13 @@
"trigger": {
"type": "string",
"description": "Emotion to inject.",
- "enum": ["concern", "celebration", "patience", "curiosity", "empathy"]
+ "enum": [
+ "concern",
+ "celebration",
+ "patience",
+ "curiosity",
+ "empathy"
+ ]
},
"weight": {
"type": "number",
@@ -90,7 +115,9 @@
"maximum": 1
}
},
- "required": ["trigger"]
+ "required": [
+ "trigger"
+ ]
}
}
],
diff --git a/scripts/agent-hire-settle.mjs b/scripts/agent-hire-settle.mjs
new file mode 100644
index 000000000..e7679e59c
--- /dev/null
+++ b/scripts/agent-hire-settle.mjs
@@ -0,0 +1,205 @@
+#!/usr/bin/env node
+// Real end-to-end agent-to-agent commerce settlement driver.
+//
+// Drives the FULL, live loop against the three.ws MCP server: discover a
+// reputation-ranked agent, then hire it — quoting the price, settling REAL USDC
+// on Solana mainnet via the x402 `exact` scheme, running the remote agent, and
+// printing the result plus the on-chain settlement reference. No mock payment:
+// a funded Solana wallet signs a real transfer, the platform facilitator settles
+// it, and the transaction lands on-chain (Solscan link printed).
+//
+// This is the operator's one-command proof of the commerce loop. It talks to the
+// LOCAL stdio server (the published @three-ws/mcp-server package) by default, so
+// it exercises exactly what a Claude Desktop / connector user runs.
+//
+// ── What you need ────────────────────────────────────────────────────────────
+// 1. A funded Solana wallet (a few cents of USDC; the platform fee-payer covers
+// the network fee, so no SOL is required). Provide its secret key as:
+// X402_BUYER_SOLANA_SECRET_BASE58=<base58 secret> (preferred)
+// or a JSON byte-array keypair file:
+// X402_BUYER_SOLANA_KEYPAIR=/path/to/keypair.json
+// 2. A platform delegation credential so the hire's remote agent can run
+// (the talk endpoint burns platform LLM credit and requires a principal):
+// MCP_AGENT_TALK_TOKEN=sk_live_... (an api_keys token, scope agents:delegate)
+// 3. A hireable agent id (its embed_policy.surfaces.mcp must be true):
+// HIRE_AGENT_ID=<uuid> (optional — otherwise discovery picks one)
+//
+// ── Run ──────────────────────────────────────────────────────────────────────
+// MCP_SVM_PAYMENT_ADDRESS=<treasury> \
+// X402_BUYER_SOLANA_SECRET_BASE58=<secret> \
+// MCP_AGENT_TALK_TOKEN=sk_live_... \
+// node scripts/agent-hire-settle.mjs "summarise recent solana sentiment in 3 bullets"
+//
+// Writes the full transcript + settlement reference to
+// prompts/store-submissions/_generated/commerce/settlement-<ts>.json when
+// COMMERCE_EVIDENCE_DIR is set.
+
+import { readFileSync, writeFileSync, existsSync, mkdirSync } from 'node:fs';
+import { dirname, join } from 'node:path';
+import { fileURLToPath } from 'node:url';
+
+import bs58 from 'bs58';
+import { createKeyPairSignerFromBytes } from '@solana/kit';
+import { Client } from '@modelcontextprotocol/sdk/client/index.js';
+import { StdioClientTransport } from '@modelcontextprotocol/sdk/client/stdio.js';
+import { x402Client } from '@x402/core/client';
+import { registerExactSvmScheme } from '@x402/svm/exact/client';
+import { wrapMCPClientWithPayment, extractPaymentResponseFromMeta } from '@x402/mcp';
+
+const bs58decode = bs58.default ? bs58.default.decode : bs58.decode;
+const HERE = dirname(fileURLToPath(import.meta.url));
+const REPO = join(HERE, '..');
+
+const TASK = process.argv[2] || 'summarise recent solana token market sentiment in 3 bullets';
+const HIRE_MESSAGE =
+ process.env.HIRE_MESSAGE || 'In two sentences, what can you help a three.ws user accomplish?';
+
+function fail(msg, code = 2) {
+ console.error(`\n✖ ${msg}`);
+ process.exit(code);
+}
+
+// Read a tool result's structured payload robustly: prefer structuredContent,
+// fall back to a JSON text block, and never throw on a non-JSON content block
+// (a PaymentRequired challenge or a plain-text error surfaces as { _raw }).
+function readResult(res) {
+ if (res?.structuredContent && typeof res.structuredContent === 'object') return res.structuredContent;
+ const text = res?.content?.find((c) => c?.type === 'text')?.text;
+ if (typeof text === 'string') {
+ try {
+ return JSON.parse(text);
+ } catch {
+ return { _raw: text };
+ }
+ }
+ return {};
+}
+
+async function loadBuyerSigner() {
+ const b58 = process.env.X402_BUYER_SOLANA_SECRET_BASE58;
+ const file = process.env.X402_BUYER_SOLANA_KEYPAIR;
+ let secret;
+ if (b58 && b58.trim()) {
+ secret = Uint8Array.from(bs58decode(b58.trim()));
+ } else if (file && existsSync(file)) {
+ secret = Uint8Array.from(JSON.parse(readFileSync(file, 'utf8')));
+ } else {
+ fail(
+ 'no buyer wallet — set X402_BUYER_SOLANA_SECRET_BASE58 (base58 secret) or ' +
+ 'X402_BUYER_SOLANA_KEYPAIR (JSON byte-array keypair file). Fund it with a few cents of USDC on Solana.',
+ );
+ }
+ // @solana/kit signer wants the 64-byte secret key (seed + pubkey).
+ return createKeyPairSignerFromBytes(secret);
+}
+
+async function main() {
+ const signer = await loadBuyerSigner();
+ console.log(`[commerce] buyer wallet: ${signer.address}`);
+
+ // x402 client with the Solana `exact` scheme registered against the buyer.
+ const paymentClient = new x402Client();
+ registerExactSvmScheme(paymentClient, {
+ signer,
+ ...(process.env.SOLANA_RPC ? { config: { rpcUrl: process.env.SOLANA_RPC } } : {}),
+ });
+
+ // Spawn the local stdio MCP server (the published package) and connect.
+ const transport = new StdioClientTransport({
+ command: 'node',
+ args: [join(REPO, 'mcp-server', 'src', 'index.js')],
+ env: {
+ ...process.env,
+ MCP_SVM_PAYMENT_ADDRESS:
+ process.env.MCP_SVM_PAYMENT_ADDRESS || process.env.X402_PAY_TO_SOLANA || '',
+ },
+ });
+ const raw = new Client({ name: 'agent-hire-settle', version: '1.0.0' }, { capabilities: {} });
+ await raw.connect(transport);
+
+ // Wrap the MCP client so any PaymentRequired auto-pays via x402 and retries.
+ const client = wrapMCPClientWithPayment(raw, paymentClient);
+
+ // ── 1) Discover + reputation-rank (paid $0.01) ──────────────────────────────
+ console.log(`[commerce] discovering agents for: "${TASK}"`);
+ const discRes = await client.callTool('agent_hire_discover', { task: TASK, limit: 5 });
+ const disc = readResult(discRes);
+ if (disc.x402Version != null || disc.error === 'Payment required to access this tool') {
+ fail('discovery could not be paid — the buyer wallet has insufficient USDC on Solana (fund it and retry)', 1);
+ }
+ if (!disc.ok || !disc.candidates?.length) {
+ fail(`discovery returned no candidates: ${disc.note || disc._raw || 'unknown'}`);
+ }
+ const chosen =
+ process.env.HIRE_AGENT_ID ||
+ disc.candidates[0].agentId;
+ const chosenName =
+ disc.candidates.find((c) => c.agentId === chosen)?.name || chosen;
+ console.log(
+ `[commerce] top candidate: ${chosenName} (${chosen}) — score ${disc.candidates[0].score}, ` +
+ `${disc.candidates[0].evidence}`,
+ );
+
+ // ── 2) Hire end to end (paid $0.05, real USDC settlement) ───────────────────
+ console.log(`[commerce] hiring ${chosenName} — settling real USDC…`);
+ const t0 = Date.now();
+ const hireRes = await client.callTool('agent_hire', { agentId: chosen, message: HIRE_MESSAGE });
+ const ms = Date.now() - t0;
+ const hire = readResult(hireRes);
+
+ if (hireRes.isError || hire.ok === false) {
+ fail(`hire failed (payment cancelled, not charged): ${hire.error} — ${hire.message}`, 1);
+ }
+
+ // The real on-chain settlement reference is attached by the x402 wrapper.
+ const settlement = extractPaymentResponseFromMeta(hireRes._meta) || hireRes._meta?.['x402/payment-response'] || null;
+ const txRef =
+ settlement?.transaction || settlement?.signature || settlement?.txHash || settlement?.tx || null;
+
+ console.log('\n──────────────── PROVENANCE RECEIPT ────────────────');
+ console.log(` agent: ${hire.agentName} (${hire.agentId})`);
+ if (hire.provenance?.reputation)
+ console.log(
+ ` reputation: ${hire.provenance.reputation.average} across ${hire.provenance.reputation.count} on ${hire.provenance.reputation.chain}`,
+ );
+ console.log(` paid: ${hire.provenance?.payment?.amountDisplay} ${hire.provenance?.payment?.asset} on ${hire.provenance?.payment?.networkLabel}`);
+ console.log(` settlement: ${txRef || '(not found in _meta — see raw payload)'}`);
+ if (txRef) console.log(` explorer: https://solscan.io/tx/${txRef}`);
+ console.log(` latency: ${(ms / 1000).toFixed(1)}s`);
+ console.log(` result: ${(hire.result?.response || '').slice(0, 240)}`);
+ console.log('────────────────────────────────────────────────────\n');
+
+ const evidenceDir = process.env.COMMERCE_EVIDENCE_DIR;
+ if (evidenceDir) {
+ mkdirSync(evidenceDir, { recursive: true });
+ const stamp = new Date().toISOString().replace(/[:.]/g, '-');
+ const out = join(evidenceDir, `settlement-${stamp}.json`);
+ writeFileSync(
+ out,
+ JSON.stringify(
+ {
+ task: TASK,
+ buyer: signer.address,
+ discover: disc,
+ hire,
+ settlement,
+ settlementTx: txRef,
+ explorer: txRef ? `https://solscan.io/tx/${txRef}` : null,
+ capturedAt: new Date().toISOString(),
+ },
+ null,
+ 2,
+ ),
+ );
+ console.log(`[commerce] evidence written: ${out}`);
+ }
+
+ await raw.close();
+ if (!txRef) {
+ fail('hire succeeded but no on-chain settlement reference was returned — check facilitator config', 1);
+ }
+ console.log('✓ Real agent-to-agent commerce loop complete: discovered → paid → delegated → settled.');
+ process.exit(0);
+}
+
+main().catch((e) => fail(e?.stack || e?.message || String(e), 1));
diff --git a/scripts/embodiment-evidence.mjs b/scripts/embodiment-evidence.mjs
new file mode 100644
index 000000000..c39e06cbe
--- /dev/null
+++ b/scripts/embodiment-evidence.mjs
@@ -0,0 +1,82 @@
+// Capture embodiment evidence: drive the live embed through idle, three
+// sentiments (distinct expressions + lip-sync), a same-body reload, and a
+// non-humanoid graceful fallback — screenshotting each and asserting a clean
+// console. Run against a dev server: `node scripts/embodiment-evidence.mjs [baseUrl]`.
+//
+// Not committed as product code — it's a verification harness. Output lands in
+// prompts/store-submissions/_generated/embodiment/.
+
+import { chromium } from 'playwright';
+import { mkdir } from 'node:fs/promises';
+import path from 'node:path';
+
+const BASE = process.argv[2] || 'http://localhost:3002';
+const GLB = `${BASE}/avatars/xbot.glb`;
+const PROP = `${BASE}/accessories/hat-cowboy.glb`;
+const OUT = path.resolve('prompts/store-submissions/_generated/embodiment');
+const PERSONA_ID = 'persona_EvidenceDemo12345';
+
+const wait = (ms) => new Promise((r) => setTimeout(r, ms));
+
+function embedUrl({ state, text, emotion, glb = GLB, name = 'Nova', persona = PERSONA_ID }) {
+ const u = new URL(`${BASE}/embodiment/embed`);
+ if (persona) u.searchParams.set('persona', persona);
+ u.searchParams.set('glb', glb);
+ u.searchParams.set('name', name);
+ if (state) u.searchParams.set('state', state);
+ if (text) u.searchParams.set('text', text);
+ if (emotion) u.searchParams.set('emotion', emotion);
+ return u.toString();
+}
+
+const errors = [];
+
+async function shoot(page, url, file, { settle = 2600, speaking = false } = {}) {
+ const localErrs = [];
+ const onErr = (m) => { if (m.type() === 'error') localErrs.push(m.text()); };
+ const onPage = (e) => localErrs.push(`pageerror: ${e.message}`);
+ page.on('console', onErr);
+ page.on('pageerror', onPage);
+ await page.goto(url, { waitUntil: 'load' });
+ // Wait for the canvas (body mounted) then let the rig settle / speech peak.
+ await page.waitForSelector('canvas', { timeout: 20000 });
+ await wait(settle);
+ await page.screenshot({ path: path.join(OUT, file) });
+ page.off('console', onErr);
+ page.off('pageerror', onPage);
+ // Ignore benign favicon/network noise; keep real script errors.
+ const real = localErrs.filter((t) => !/favicon|manifest\.json 404|ERR_ABORTED/.test(t));
+ if (real.length) errors.push({ file, real });
+ console.log(`✓ ${file}${real.length ? ` (⚠ ${real.length} console errors)` : ''}`);
+}
+
+const shots = [
+ { file: '01-idle.png', url: embedUrl({ state: 'idle' }), opt: { settle: 3000 } },
+ { file: '02-joy.png', url: embedUrl({ state: 'speaking', emotion: 'joy', text: 'Congratulations — that is absolutely amazing! 🎉' }), opt: { settle: 1500, speaking: true } },
+ { file: '03-sad.png', url: embedUrl({ state: 'speaking', emotion: 'sad', text: 'I am sorry, unfortunately that request failed.' }), opt: { settle: 1500, speaking: true } },
+ { file: '04-angry.png', url: embedUrl({ state: 'speaking', emotion: 'angry', text: 'This is completely unacceptable and frustrating!' }), opt: { settle: 1500, speaking: true } },
+ { file: '05-reload-same-body.png', url: embedUrl({ state: 'idle' }), opt: { settle: 3000 } },
+ { file: '06-nonhumanoid-fallback.png', url: embedUrl({ state: 'idle', glb: PROP, name: 'Cowboy Hat', persona: null }), opt: { settle: 3000 } },
+];
+
+const browser = await chromium.launch();
+try {
+ await mkdir(OUT, { recursive: true });
+ for (const s of shots) {
+ // A fresh context per shot = a genuinely new "session" (no shared state),
+ // which is exactly what the reload-same-body case must prove.
+ const ctx = await browser.newContext({ viewport: { width: 900, height: 620 }, deviceScaleFactor: 2 });
+ const page = await ctx.newPage();
+ await shoot(page, s.url, s.file, s.opt);
+ await ctx.close();
+ }
+} finally {
+ await browser.close();
+}
+
+if (errors.length) {
+ console.error('\n✗ console errors detected:');
+ for (const e of errors) console.error(` ${e.file}:`, e.real.slice(0, 3));
+ process.exit(1);
+}
+console.log(`\nAll evidence captured to ${OUT} with a clean console.`);
diff --git a/scripts/gcp/vanity-grind-deploy.sh b/scripts/gcp/vanity-grind-deploy.sh
index 1866d3de1..50ae4982d 100755
--- a/scripts/gcp/vanity-grind-deploy.sh
+++ b/scripts/gcp/vanity-grind-deploy.sh
@@ -46,6 +46,11 @@ CPU="${CPU:-4}"
INSTANCES="${INSTANCES:-10}"
MACHINE="${MACHINE:-c2d-highcpu-8}"
GRINDER_SA="${GRINDER_SA:-vanity-grinder@${PROJECT_ID}.iam.gserviceaccount.com}"
+# This project has no legacy Cloud Build SA (new GCP projects don't auto-create
+# <projectNumber>@cloudbuild.gserviceaccount.com), so `gcloud builds submit` must
+# name a build identity or it fails with "Unknown service account". Reuse the
+# dedicated build SA the other images use (deploy/world/apply-hardening.sh).
+BUILD_SA="${BUILD_SERVICE_ACCOUNT:-three-ws-build@${PROJECT_ID}.iam.gserviceaccount.com}"
REPO_ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/../.." && pwd)"
cd "$REPO_ROOT"
@@ -76,15 +81,25 @@ gcloud iam service-accounts create vanity-grinder --display-name "Vanity batch g
--project "$PROJECT_ID" 2>/dev/null || echo " (SA exists)"
echo "▸ Building + pushing image (build context = repo root)…"
-gcloud builds submit --project "$PROJECT_ID" --region "$REGION" \
- --tag "$IMAGE_URI" \
- --config <(cat <<YAML
+# The image uses a non-default Dockerfile path (workers/vanity-grinder/Dockerfile)
+# with the repo root as context, so we drive the build via a cloudbuild config
+# (--config) — NOT --tag, which assumes ./Dockerfile and is mutually exclusive with
+# --config. The repo's .gcloudignore allowlist already keeps the multi-GB asset dirs
+# (animation-sources/dist/public/…) and node_modules out of the upload.
+BUILD_CFG="$(mktemp --suffix=.cloudbuild.yaml)"
+trap 'rm -f "$BUILD_CFG"' EXIT
+cat > "$BUILD_CFG" <<YAML
steps:
- name: gcr.io/cloud-builders/docker
args: ['build','-f','workers/vanity-grinder/Dockerfile','-t','${IMAGE_URI}','.']
images: ['${IMAGE_URI}']
+options:
+ # A user-specified build SA cannot write to the default (legacy) GCS logs bucket.
+ logging: CLOUD_LOGGING_ONLY
YAML
-)
+gcloud builds submit --project "$PROJECT_ID" --region "$REGION" \
+ --service-account "projects/${PROJECT_ID}/serviceAccounts/${BUILD_SA}" \
+ --config "$BUILD_CFG" .
# Common env for the grinder. WRITE_DB/VANITY_KMS_KEY flow through from the shell.
JOB_ENV="RUNNER=cloud-run-job,INCLUDE_5=${INCLUDE_5:-0},IGNORE_CASE=${IGNORE_CASE:-0},WRITE_DB=${WRITE_DB:-1},VANITY_KMS_KEY=${VANITY_KMS_KEY:-}"
diff --git a/scripts/tokenize-3d-devnet-e2e.mjs b/scripts/tokenize-3d-devnet-e2e.mjs
new file mode 100644
index 000000000..4014c5796
--- /dev/null
+++ b/scripts/tokenize-3d-devnet-e2e.mjs
@@ -0,0 +1,262 @@
+#!/usr/bin/env node
+/**
+ * Tokenized-3D — real devnet mint end-to-end proof.
+ *
+ * Proves the on-chain half of api/_lib/tokenize-3d.js against LIVE Solana devnet:
+ * builds Metaplex-compliant metadata with the real buildTokenized3dMetadata()
+ * (GLB under animation_url), mints a Metaplex Core asset with an enforced,
+ * capped Royalties plugin to a recipient wallet, then reads it back with
+ * fetchAsset() and confirms holder + royalty terms + that the metadata resolves
+ * to a live 3D viewer.
+ *
+ * Why an ephemeral airdropped authority instead of the production
+ * collection-authority keypair + R2: those are Vercel *sensitive* env vars,
+ * redacted on `vercel env pull`, so they are not retrievable in this sandbox.
+ * The mint/royalty/read-back semantics exercised here are byte-for-byte the same
+ * `create({ plugins:[Royalties…] }).sendAndConfirm` + `fetchAsset` path the
+ * library runs — only the fee-payer identity and the media host differ.
+ *
+ * Usage: node scripts/tokenize-3d-devnet-e2e.mjs
+ * Writes evidence to prompts/store-submissions/_generated/tokenized/.
+ */
+
+import { execFileSync } from 'node:child_process';
+import { mkdirSync, writeFileSync } from 'node:fs';
+import { fileURLToPath } from 'node:url';
+import { dirname, join } from 'node:path';
+
+import { Connection, Keypair, LAMPORTS_PER_SOL, PublicKey } from '@solana/web3.js';
+import { createUmi } from '@metaplex-foundation/umi-bundle-defaults';
+import { mplCore, create, fetchAsset, ruleSet } from '@metaplex-foundation/mpl-core';
+import {
+ generateSigner,
+ publicKey as umiPublicKey,
+ signerIdentity,
+ createSignerFromKeypair,
+} from '@metaplex-foundation/umi';
+import bs58 from 'bs58';
+
+import { buildTokenized3dMetadata, clampSellerFeeBps } from '../api/_lib/tokenize-3d-metadata.js';
+
+const RPC = 'https://api.devnet.solana.com';
+const APP_ORIGIN = 'https://three.ws';
+// A small, real, public GLB (Khronos glTF sample "Box") — resolvable media so
+// the read-back's live-viewer check has something real to HEAD.
+const GLB_URL =
+ 'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Box/glTF-Binary/Box.glb';
+const IMAGE_URL =
+ 'https://raw.githubusercontent.com/KhronosGroup/glTF-Sample-Assets/main/Models/Box/screenshot/screenshot.png';
+const REQUESTED_BPS = 5000; // deliberately over the cap — proves the clamp
+
+const __dirname = dirname(fileURLToPath(import.meta.url));
+const OUT_DIR = join(__dirname, '../prompts/store-submissions/_generated/tokenized');
+
+function log(...a) {
+ console.log(...a);
+}
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+
+/** Load a pre-funded devnet payer from E2E_PAYER_SECRET (base58 / base64 / JSON array). */
+function loadPayerFromEnv() {
+ const raw = (process.env.E2E_PAYER_SECRET || '').trim();
+ if (!raw) return null;
+ let bytes;
+ if (raw.startsWith('[')) bytes = Uint8Array.from(JSON.parse(raw));
+ else {
+ try {
+ bytes = bs58.decode(raw);
+ } catch {
+ bytes = Uint8Array.from(Buffer.from(raw, 'base64'));
+ }
+ }
+ return Keypair.fromSecretKey(bytes.length === 64 ? bytes : Keypair.fromSeed(bytes.slice(0, 32)).secretKey);
+}
+
+async function airdrop(conn, pubkey, sol) {
+ // The public devnet faucet is flaky ("Internal error" under load) — retry
+ // with backoff, and accept success once the balance covers Core rent.
+ let lastErr;
+ for (let attempt = 1; attempt <= 8; attempt++) {
+ try {
+ const sig = await conn.requestAirdrop(pubkey, sol * LAMPORTS_PER_SOL);
+ const bh = await conn.getLatestBlockhash();
+ await conn.confirmTransaction({ signature: sig, ...bh }, 'confirmed');
+ return;
+ } catch (e) {
+ lastErr = e;
+ const bal = await conn.getBalance(pubkey).catch(() => 0);
+ if (bal >= 0.05 * LAMPORTS_PER_SOL) return; // enough for rent already
+ log(` airdrop attempt ${attempt} failed (${e?.message || e}); retrying…`);
+ await sleep(3000 * attempt);
+ }
+ }
+ throw lastErr;
+}
+
+function publishMetadataGist(metadata) {
+ // A real, public https URL for the asset `uri` (no R2 in this sandbox).
+ const tmp = join(OUT_DIR, 'devnet-metadata.json');
+ writeFileSync(tmp, JSON.stringify(metadata, null, 2));
+ const out = execFileSync(
+ 'gh',
+ ['gist', 'create', tmp, '--public', '--desc', 'three.ws tokenized-3d devnet e2e metadata'],
+ { encoding: 'utf8' },
+ ).trim();
+ const gistId = out.split('/').pop();
+ // Raw URL that always serves the current file content.
+ const rawList = execFileSync('gh', ['gist', 'view', gistId, '--files'], { encoding: 'utf8' })
+ .trim()
+ .split('\n');
+ const file = rawList[0];
+ return { htmlUrl: out, rawUrl: `https://gist.githubusercontent.com/raw/${gistId}/${file}`, gistId };
+}
+
+async function main() {
+ mkdirSync(OUT_DIR, { recursive: true });
+ const conn = new Connection(RPC, 'confirmed');
+
+ // Authority (fee payer + update authority) and recipient (holder). The
+ // authority may be supplied pre-funded via E2E_PAYER_SECRET (base58 or base64)
+ // to skip the flaky public faucet — otherwise we airdrop a fresh keypair.
+ const authorityKp = loadPayerFromEnv() || Keypair.generate();
+ const recipientKp = Keypair.generate();
+ log('authority:', authorityKp.publicKey.toBase58());
+ log('recipient:', recipientKp.publicKey.toBase58());
+
+ let bal = await conn.getBalance(authorityKp.publicKey);
+ if (bal < 0.02 * LAMPORTS_PER_SOL) {
+ log('airdropping 0.5 SOL to authority on devnet…');
+ await airdrop(conn, authorityKp.publicKey, 0.5);
+ bal = await conn.getBalance(authorityKp.publicKey);
+ }
+ log('authority balance:', bal / LAMPORTS_PER_SOL, 'SOL');
+
+ // Royalty: request 50%, expect clamp to the 10% hard cap.
+ const { bps: royaltyBps, capped, requestedBps } = clampSellerFeeBps(REQUESTED_BPS);
+ log(`royalty: requested ${requestedBps}bps → enforced ${royaltyBps}bps (capped=${capped})`);
+
+ const createdAt = new Date().toISOString();
+ const viewerUrl = `${APP_ORIGIN}/viewer?src=${encodeURIComponent(GLB_URL)}`;
+ const metadata = buildTokenized3dMetadata({
+ name: 'three.ws Devnet 3D',
+ description: 'End-to-end devnet proof of a tokenized 3D asset.',
+ glbUrl: GLB_URL,
+ imageUrl: IMAGE_URL,
+ viewerUrl,
+ creatorWallet: recipientKp.publicKey.toBase58(),
+ prompt: 'a cube, tokenized',
+ generationModel: 'trellis',
+ generationProvider: 'nvidia-nim',
+ royaltyBps,
+ royaltyRecipient: recipientKp.publicKey.toBase58(),
+ network: 'devnet',
+ createdAt,
+ });
+
+ log('publishing metadata to a public gist for the asset uri…');
+ const gist = publishMetadataGist(metadata);
+ log('metadata uri:', gist.rawUrl);
+
+ // ── Mint (same shape as tokenize-3d.js mintCoreAsset) ──
+ const umi = createUmi(RPC).use(mplCore());
+ const umiAuthority = createSignerFromKeypair(
+ umi,
+ umi.eddsa.createKeypairFromSecretKey(authorityKp.secretKey),
+ );
+ umi.use(signerIdentity(umiAuthority));
+
+ const assetSigner = generateSigner(umi);
+ log('minting Core asset with enforced Royalties plugin…');
+ const { signature } = await create(umi, {
+ asset: assetSigner,
+ owner: umiPublicKey(recipientKp.publicKey.toBase58()),
+ name: 'three.ws Devnet 3D',
+ uri: gist.rawUrl,
+ plugins: [
+ {
+ type: 'Royalties',
+ basisPoints: royaltyBps,
+ creators: [{ address: umiPublicKey(recipientKp.publicKey.toBase58()), percentage: 100 }],
+ ruleSet: ruleSet('None'),
+ },
+ ],
+ }).sendAndConfirm(umi, { confirm: { commitment: 'confirmed' } });
+
+ const mint = assetSigner.publicKey.toString();
+ const sig = typeof signature === 'string' ? signature : bs58.encode(signature);
+ const explorerTx = `https://solscan.io/tx/${sig}?cluster=devnet`;
+ const explorerAsset = `https://solscan.io/token/${mint}?cluster=devnet`;
+ log('\n✅ MINTED');
+ log('mint:', mint);
+ log('tx:', explorerTx);
+ log('asset:', explorerAsset);
+
+ // ── Read-back (same as tokenize-3d.js readTokenized3dAsset) ──
+ log('\nreading back on-chain…');
+ const asset = await fetchAsset(umi, umiPublicKey(mint));
+ const holder = asset.owner?.toString?.();
+ const onchainBps = asset.royalties?.basisPoints ?? null;
+ const onchainCreators = (asset.royalties?.creators || []).map((c) => ({
+ address: c.address?.toString?.() || String(c.address),
+ percent: c.percentage,
+ }));
+ log('holder:', holder);
+ log('on-chain royalty bps:', onchainBps);
+ log('on-chain creators:', JSON.stringify(onchainCreators));
+ log('asset uri:', asset.uri);
+
+ // Confirm the metadata resolves + points at a live 3D model.
+ const metaResp = await fetch(asset.uri);
+ const metaJson = await metaResp.json();
+ const glbHead = await fetch(metaJson.animation_url, { method: 'HEAD' });
+
+ // ── Assertions ──
+ const checks = {
+ holder_is_recipient: holder === recipientKp.publicKey.toBase58(),
+ royalty_enforced_at_cap: onchainBps === royaltyBps,
+ royalty_capped: capped && royaltyBps === 1000,
+ metadata_resolves: metaResp.ok,
+ model_under_animation_url: metaJson.animation_url === GLB_URL,
+ media_is_gltf_binary:
+ metaJson.properties?.files?.some((f) => f.type === 'model/gltf-binary') === true,
+ viewer_media_live: glbHead.ok,
+ provenance_baked: metaJson.properties?.provenance?.prompt === 'a cube, tokenized',
+ };
+ log('\nchecks:', JSON.stringify(checks, null, 2));
+ const allPass = Object.values(checks).every(Boolean);
+
+ const evidence = {
+ generated_at: createdAt,
+ network: 'devnet',
+ rpc: RPC,
+ authority: authorityKp.publicKey.toBase58(),
+ recipient_holder: recipientKp.publicKey.toBase58(),
+ mint,
+ tx_signature: sig,
+ explorer_tx_url: explorerTx,
+ explorer_asset_url: explorerAsset,
+ viewer_url: viewerUrl,
+ metadata_uri: asset.uri,
+ metadata_gist: gist.htmlUrl,
+ royalty: {
+ requested_bps: requestedBps,
+ enforced_bps: onchainBps,
+ cap_bps: 1000,
+ capped,
+ creators: onchainCreators,
+ },
+ read_back: { holder, onchain_bps: onchainBps, asset_uri: asset.uri },
+ checks,
+ result: allPass ? 'PASS' : 'FAIL',
+ };
+ writeFileSync(join(OUT_DIR, 'devnet-mint-evidence.json'), JSON.stringify(evidence, null, 2));
+ log(`\nevidence → ${join(OUT_DIR, 'devnet-mint-evidence.json')}`);
+ log(allPass ? '\n🟢 E2E PASS' : '\n🔴 E2E FAIL');
+ if (!allPass) process.exit(1);
+}
+
+main().catch((e) => {
+ console.error('E2E error:', e?.message || e);
+ process.exit(1);
+});
diff --git a/tests/agent-commerce-transport.test.js b/tests/agent-commerce-transport.test.js
new file mode 100644
index 000000000..40defe851
--- /dev/null
+++ b/tests/agent-commerce-transport.test.js
@@ -0,0 +1,120 @@
+/**
+ * Agent-to-agent commerce — the transport-layer fixes that make the hire loop
+ * actually complete against the live stack. These two behaviours are load-bearing
+ * and were both silently broken before:
+ *
+ * 1. Discovery MUST NOT dead-end on phrasing. The directory's full-text `q` is a
+ * strict pre-filter, so a natural-language task ("help me run a token launch")
+ * routinely matches nothing even when relevant agents exist. fetchCandidates
+ * broadens — retries without `q` — so discovery degrades to "the best agents
+ * we have" instead of an empty shortlist. A `skill` filter is an explicit
+ * constraint and is never widened away.
+ *
+ * 2. Delegation MUST authenticate. /api/agents/talk requires a principal (it
+ * burns platform LLM credit); the hire tool already collected the x402
+ * payment, so it presents a platform bearer credential. Without a token the
+ * request is anonymous and 401s (which cancels the payment — the caller is
+ * never charged for a hire that could not run).
+ *
+ * Both are exercised with a mocked global.fetch — no network, no wallet, no model.
+ */
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+import { fetchCandidates } from '../mcp-server/src/lib/agent-registry.js';
+import { runDelegation } from '../mcp-server/src/lib/delegate-transport.js';
+
+const json = (body, status = 200) =>
+ new Response(JSON.stringify(body), { status, headers: { 'content-type': 'application/json' } });
+
+const AGENT = { id: 'a1', name: 'Demo Agent', skills: [], chat_count: 3 };
+
+describe('fetchCandidates — discovery never dead-ends on phrasing', () => {
+ let origFetch;
+ beforeEach(() => {
+ origFetch = global.fetch;
+ });
+ afterEach(() => {
+ global.fetch = origFetch;
+ delete process.env.THREEWS_BASE_URL;
+ });
+
+ it('broadens (drops q) and returns the ranked pool when a q-filtered query is empty', async () => {
+ const urls = [];
+ global.fetch = vi.fn(async (url) => {
+ urls.push(String(url));
+ // First call carries the strict full-text q and matches nothing;
+ // the broadened retry (no q) returns the real directory.
+ const hasQ = new URL(String(url)).searchParams.has('q');
+ return json({ agents: hasQ ? [] : [AGENT] });
+ });
+
+ const rows = await fetchCandidates({ q: 'help me run a pump.fun token launch', limit: 5 });
+
+ expect(rows).toEqual([AGENT]);
+ expect(global.fetch).toHaveBeenCalledTimes(2);
+ expect(new URL(urls[0]).searchParams.get('q')).toContain('pump.fun');
+ expect(new URL(urls[1]).searchParams.has('q')).toBe(false);
+ });
+
+ it('does not make a second call when the q-filtered query already returns rows', async () => {
+ global.fetch = vi.fn(async () => json({ agents: [AGENT] }));
+ const rows = await fetchCandidates({ q: 'anything', limit: 5 });
+ expect(rows).toEqual([AGENT]);
+ expect(global.fetch).toHaveBeenCalledTimes(1);
+ });
+
+ it('never widens past an explicit skill filter (an empty skill result stays empty)', async () => {
+ const urls = [];
+ global.fetch = vi.fn(async (url) => {
+ urls.push(String(url));
+ return json({ agents: [] });
+ });
+ const rows = await fetchCandidates({ q: 'task', skill: 'translation', limit: 5 });
+ expect(rows).toEqual([]);
+ // One broadening retry is allowed, but the skill filter must survive it.
+ for (const u of urls) expect(new URL(u).searchParams.get('skill')).toBe('translation');
+ });
+});
+
+describe('runDelegation — authenticates to the credit-burning talk endpoint', () => {
+ let origFetch;
+ const TOKEN_KEYS = ['MCP_AGENT_TALK_TOKEN', 'THREE_WS_MCP_TOKEN', 'MCP_SERVICE_TOKEN'];
+ beforeEach(() => {
+ origFetch = global.fetch;
+ for (const k of TOKEN_KEYS) delete process.env[k];
+ });
+ afterEach(() => {
+ global.fetch = origFetch;
+ for (const k of TOKEN_KEYS) delete process.env[k];
+ });
+
+ it('sends Authorization: Bearer <token> when a service token is configured', async () => {
+ process.env.MCP_AGENT_TALK_TOKEN = 'sk_test_service_credential';
+ let seenAuth = null;
+ global.fetch = vi.fn(async (_url, init) => {
+ seenAuth = init.headers.authorization || init.headers.Authorization || null;
+ return json({ ok: true, response: 'hi', model: 'claude-haiku-4-5-20251001' });
+ });
+
+ const out = await runDelegation({ agentId: 'a1', message: 'hello' });
+
+ expect(out.ok).toBe(true);
+ expect(seenAuth).toBe('Bearer sk_test_service_credential');
+ });
+
+ it('sends no Authorization header when no token is configured (clean anonymous 401 path)', async () => {
+ let hadAuth = true;
+ global.fetch = vi.fn(async (_url, init) => {
+ hadAuth = 'authorization' in init.headers || 'Authorization' in init.headers;
+ return json({ ok: false, code: 'unauthorized', message: 'sign in required' }, 401);
+ });
+
+ const out = await runDelegation({ agentId: 'a1', message: 'hello' });
+
+ expect(hadAuth).toBe(false);
+ expect(out.ok).toBe(false);
+ expect(out.error).toBe('unauthorized');
+ expect(out.status).toBe(401);
+ });
+});
diff --git a/tests/api/mcp-agent-bazaar-discovery.test.js b/tests/api/mcp-agent-bazaar-discovery.test.js
new file mode 100644
index 000000000..86bb1ff54
--- /dev/null
+++ b/tests/api/mcp-agent-bazaar-discovery.test.js
@@ -0,0 +1,100 @@
+/**
+ * The Agent-wallet (api/mcp-agent.js) and x402 Bazaar (api/mcp-bazaar.js)
+ * remotes must answer a plain, unauthenticated `tools/list` / `initialize`
+ * (discovery-only batch) with 200 + the toolset — otherwise directory crawlers
+ * and plain x402 agents that probe with a bare `tools/list` get a 402 and index
+ * an empty server. This mirrors the discovery gate already covered for
+ * /api/mcp-3d in mcp-3d-challenge.test.js. MCP protocol clients (Accept:
+ * text/event-stream) must still receive the 401 that starts their OAuth flow.
+ */
+import { describe, it, expect, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';
+process.env.X402_PAY_TO_BASE ||= '0x0000000000000000000000000000000000000001';
+process.env.X402_ASSET_ADDRESS_BASE ||= '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
+
+// Bearer path is out of scope — no token is presented in these tests.
+vi.mock('../../api/_lib/auth.js', () => ({
+ extractBearer: () => null,
+ authenticateBearer: vi.fn(async () => null),
+}));
+
+// No Upstash in unit tests — every limiter passes.
+vi.mock('../../api/_lib/rate-limit.js', () => ({
+ limits: new Proxy(
+ {},
+ { get: () => vi.fn(async () => ({ success: true, reset: Date.now() + 1000 })) },
+ ),
+ clientIp: vi.fn(() => '203.0.113.9'),
+}));
+
+// The bazaar client is a live network dependency; keep discovery hermetic.
+vi.mock('../../api/_lib/x402/bazaar-client.js', async (orig) => {
+ const actual = await orig();
+ return { ...actual, searchBazaar: vi.fn(async () => ({ services: [] })) };
+});
+
+const { default: agentHandler } = await import('../../api/mcp-agent.js');
+const { default: bazaarHandler } = await import('../../api/mcp-bazaar.js');
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: null,
+ setHeader(name, value) {
+ this.headers[String(name).toLowerCase()] = value;
+ },
+ end(body) {
+ this.body = body ?? null;
+ },
+ };
+}
+
+function makeReq(url, { method = 'POST', headers = {}, body = null } = {}) {
+ const payload = body == null ? '' : JSON.stringify(body);
+ const req = Readable.from(payload ? [Buffer.from(payload, 'utf8')] : []);
+ req.method = method;
+ req.url = url;
+ req.headers = { 'content-type': 'application/json', 'x-forwarded-for': '203.0.113.9', ...headers };
+ return req;
+}
+
+const TOOLS_LIST = { jsonrpc: '2.0', id: 1, method: 'tools/list' };
+const INITIALIZE = { jsonrpc: '2.0', id: 1, method: 'initialize', params: { protocolVersion: '2025-06-18' } };
+const EVENT_STREAM = { accept: 'application/json, text/event-stream' };
+
+const cases = [
+ { name: 'threews-agent (/api/mcp-agent)', url: '/api/mcp-agent', handler: () => agentHandler },
+ { name: 'threews-x402-bazaar (/api/mcp-bazaar)', url: '/api/mcp-bazaar', handler: () => bazaarHandler },
+];
+
+for (const c of cases) {
+ describe(`${c.name} — free discovery for plain clients`, () => {
+ it('answers a plain tools/list with 200 and a non-empty toolset', async () => {
+ const res = makeRes();
+ await c.handler()(makeReq(c.url, { body: TOOLS_LIST }), res);
+ expect(res.statusCode).toBe(200);
+ const out = JSON.parse(res.body);
+ expect(out.error).toBeUndefined();
+ expect(Array.isArray(out.result.tools)).toBe(true);
+ expect(out.result.tools.length).toBeGreaterThan(0);
+ });
+
+ it('answers a plain initialize with 200', async () => {
+ const res = makeRes();
+ await c.handler()(makeReq(c.url, { body: INITIALIZE }), res);
+ expect(res.statusCode).toBe(200);
+ const out = JSON.parse(res.body);
+ expect(out.result.serverInfo?.name).toBeTruthy();
+ });
+
+ it('still 401s an MCP protocol client on tools/list so OAuth can start', async () => {
+ const res = makeRes();
+ await c.handler()(makeReq(c.url, { body: TOOLS_LIST, headers: EVENT_STREAM }), res);
+ expect(res.statusCode).toBe(401);
+ expect(res.headers['www-authenticate']).toContain('oauth-protected-resource');
+ });
+ });
+}
diff --git a/tests/api/okx-identity-studio.test.js b/tests/api/okx-identity-studio.test.js
index 73b8fb5cc..6914ff5a4 100644
--- a/tests/api/okx-identity-studio.test.js
+++ b/tests/api/okx-identity-studio.test.js
@@ -15,6 +15,11 @@ import { Readable } from 'node:stream';
process.env.PUBLIC_APP_ORIGIN = 'https://three.ws';
process.env.X402_PAY_TO_BASE ||= '0x0000000000000000000000000000000000000001';
process.env.X402_ASSET_ADDRESS_BASE ||= '0x833589fCD6eDb6E08f4c7C32D4f71b54bdA02913';
+// The OKX X Layer rail — the reason this service exists on OKX.AI. With these
+// set, xlayerSettleable() is true and the flagship 402 must lead with eip155:196.
+process.env.X402_PAY_TO_XLAYER ||= '0x75d00a2713565171f33216e5aa2a375e076ecf69';
+process.env.X402_XLAYER_RELAYER_KEY ||=
+ '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d';
process.env.JWT_SECRET ||= 'okx-identity-test-secret';
vi.mock('../../api/_lib/auth.js', () => ({
@@ -275,6 +280,31 @@ describe('402 challenge and pricing', () => {
expect(JSON.stringify(challenge)).toContain('identity-studio');
});
+ it('the 402 LEADS with the OKX X Layer (eip155:196) accept — the flagship must be OKX-payable', async () => {
+ const res = makeRes();
+ await handler(
+ makeReq({
+ body: {
+ jsonrpc: '2.0',
+ id: 1,
+ method: 'tools/call',
+ params: { name: 'create_identity', arguments: { agent_name: 'X', brief: 'a data agent' } },
+ },
+ }),
+ res,
+ );
+ expect(res.statusCode).toBe(402);
+ const challenge = JSON.parse(res.body);
+ // First accept is the X Layer rail (OKX buyer CLIs auto-select accepts[0]).
+ expect(challenge.accepts[0].network).toBe('eip155:196');
+ expect(challenge.accepts[0].scheme).toBe('exact');
+ expect(challenge.accepts[0].amount).toBe('1500000');
+ expect(challenge.accepts[0].asset.toLowerCase()).toBe('0x779ded0c9e1022225f8e0630b35a9b54be713736');
+ // The legacy rails still follow, so non-OKX agents can pay too (Base here).
+ expect(challenge.accepts.length).toBeGreaterThan(1);
+ expect(challenge.accepts.slice(1).some((a) => a.network !== 'eip155:196')).toBe(true);
+ });
+
it('identity_status is free — served anonymously, no 402', async () => {
const res = makeRes();
await handler(
diff --git a/tests/persona-store.test.js b/tests/persona-store.test.js
new file mode 100644
index 000000000..613c25dbc
--- /dev/null
+++ b/tests/persona-store.test.js
@@ -0,0 +1,149 @@
+/**
+ * Persona persistence — the identity layer behind an embodied agent.
+ *
+ * The promise of embodiment is continuity: a named body you return to across
+ * sessions. These tests pin that on the filesystem backend (no DATABASE_URL) —
+ * create a persona, then read it back through a FRESH call (a stand-in for a new
+ * session / new process), and prove it's the same body with a growing turn count.
+ * They also pin the public projection never leaking storage keys or owner ids, and
+ * the id helpers a caller uses to guard a lookup.
+ */
+
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { promises as fs } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+
+import {
+ makePersonaId,
+ isPersonaId,
+ normalizePersonaInput,
+ personaPublicView,
+ createPersona,
+ getPersona,
+ updatePersona,
+ touchPersona,
+} from '../api/_lib/persona-store.js';
+
+let tmpDir;
+const savedEnv = {};
+
+beforeAll(async () => {
+ tmpDir = await fs.mkdtemp(path.join(os.tmpdir(), 'persona-store-test-'));
+ // Force the filesystem backend: no DB, no R2. Persona persists to disk and the
+ // GLB source URL is kept as-is (durable copy is a prod-only concern).
+ for (const k of ['PERSONA_STORE_DIR', 'DATABASE_URL', 'S3_BUCKET', 'S3_PUBLIC_DOMAIN']) savedEnv[k] = process.env[k];
+ process.env.PERSONA_STORE_DIR = tmpDir;
+ delete process.env.DATABASE_URL;
+ delete process.env.S3_BUCKET;
+ delete process.env.S3_PUBLIC_DOMAIN;
+});
+
+afterAll(async () => {
+ for (const [k, v] of Object.entries(savedEnv)) {
+ if (v === undefined) delete process.env[k];
+ else process.env[k] = v;
+ }
+ if (tmpDir) await fs.rm(tmpDir, { recursive: true, force: true });
+});
+
+describe('persona id helpers', () => {
+ it('mints URL-safe, well-formed ids — deterministic with a seed', () => {
+ const a = makePersonaId('seed-one');
+ const b = makePersonaId('seed-one');
+ const c = makePersonaId('seed-two');
+ expect(a).toBe(b); // seed → stable
+ expect(a).not.toBe(c);
+ expect(isPersonaId(a)).toBe(true);
+ expect(a.startsWith('persona_')).toBe(true);
+ });
+
+ it('rejects malformed ids', () => {
+ expect(isPersonaId('')).toBe(false);
+ expect(isPersonaId('nope')).toBe(false);
+ expect(isPersonaId('persona_')).toBe(false);
+ expect(isPersonaId(null)).toBe(false);
+ expect(isPersonaId('persona_with spaces!!')).toBe(false);
+ });
+});
+
+describe('normalizePersonaInput', () => {
+ it('clamps strings and defaults name + emotion baseline', () => {
+ const n = normalizePersonaInput({ name: ' ', glbUrl: 'https://three.ws/a.glb' });
+ expect(n.name).toBe('Agent');
+ expect(n.emotion_baseline).toBe('neutral');
+ expect(n.glb_url).toBe('https://three.ws/a.glb');
+ });
+
+ it('carries the look flags through', () => {
+ const n = normalizePersonaInput({ name: 'Nova', glbUrl: 'https://three.ws/a.glb', look: { rigged: true, mesh_count: 3 } });
+ expect(n.look.rigged).toBe(true);
+ expect(n.look.mesh_count).toBe(3);
+ });
+});
+
+describe('persona persistence (filesystem backend)', () => {
+ it('creates a persona and reloads the SAME body by id in a fresh call', async () => {
+ const created = await createPersona({
+ name: 'Nova',
+ glbUrl: 'https://three.ws/cdn/creations/nova.glb',
+ voice: 'aria',
+ sourcePrompt: 'a friendly astronaut mascot',
+ ownerId: 'owner-123',
+ look: { rigged: true, mesh_count: 2, animation_count: 1 },
+ });
+ expect(isPersonaId(created.id)).toBe(true);
+ expect(created.turn_count).toBe(0);
+
+ // A durable file exists on disk — the continuity substrate.
+ const onDisk = await fs.readFile(path.join(tmpDir, `${created.id}.json`), 'utf8');
+ expect(JSON.parse(onDisk).name).toBe('Nova');
+
+ // "New session": reload purely by id.
+ const reloaded = await getPersona(created.id);
+ expect(reloaded).toBeTruthy();
+ expect(reloaded.id).toBe(created.id);
+ expect(reloaded.name).toBe('Nova');
+ expect(reloaded.glb_url).toBe('https://three.ws/cdn/creations/nova.glb');
+ expect(reloaded.look.rigged).toBe(true);
+ });
+
+ it('touchPersona bumps the turn count — the same-body-reused signal', async () => {
+ const p = await createPersona({ name: 'Sable', glbUrl: 'https://three.ws/cdn/creations/sable.glb' });
+ expect(p.turn_count).toBe(0);
+ const t1 = await touchPersona(p.id);
+ expect(t1.turn_count).toBe(1);
+ const t2 = await touchPersona(p.id);
+ expect(t2.turn_count).toBe(2);
+ // The bump is durable — a fresh read sees it.
+ const reread = await getPersona(p.id);
+ expect(reread.turn_count).toBe(2);
+ });
+
+ it('updatePersona patches identity but reloads under the same id', async () => {
+ const p = await createPersona({ name: 'Orin', glbUrl: 'https://three.ws/cdn/creations/orin.glb' });
+ const updated = await updatePersona(p.id, { name: 'Orin the Guide', voice: ' collins' });
+ expect(updated.id).toBe(p.id);
+ expect(updated.name).toBe('Orin the Guide');
+ expect((await getPersona(p.id)).name).toBe('Orin the Guide');
+ });
+
+ it('getPersona returns null for a well-formed but unknown id', async () => {
+ expect(await getPersona(makePersonaId('never-created'))).toBe(null);
+ });
+
+ it('public projection never leaks storage keys or owner ids', async () => {
+ const p = await createPersona({
+ name: 'Vex',
+ glbUrl: 'https://three.ws/cdn/creations/vex.glb',
+ ownerId: 'secret-owner',
+ });
+ const view = personaPublicView(await getPersona(p.id));
+ expect(view.persona_id).toBe(p.id);
+ expect(view.name).toBe('Vex');
+ expect(view).not.toHaveProperty('owner_id');
+ expect(view).not.toHaveProperty('glb_key');
+ expect(view).not.toHaveProperty('source_prompt');
+ expect(JSON.stringify(view)).not.toContain('secret-owner');
+ });
+});
diff --git a/tests/vanity-wasm-grinder.test.js b/tests/vanity-wasm-grinder.test.js
index acd16cc7b..257cf66d9 100644
--- a/tests/vanity-wasm-grinder.test.js
+++ b/tests/vanity-wasm-grinder.test.js
@@ -95,3 +95,32 @@ describe('vanity-grinder WASM', () => {
expect(hit).toBeNull();
});
});
+
+describe('grindToCompletion stop signal', () => {
+ // Regression guard: the batch grinder aborts an in-flight target the moment the
+ // shared stop flag flips — NOT only when the (near-impossible) target completes.
+ // grindToCompletion runs a synchronous loop, so it must poll stopRequested()
+ // between batches; if it ignored it, an unlucky worker would hang for minutes.
+ it('returns status "preempted" quickly when stopRequested flips true', async () => {
+ const { grindToCompletion } = await import('../workers/vanity-grinder/wasm-grind.mjs');
+ let batches = 0;
+ const t0 = performance.now();
+ const result = grindToCompletion(
+ { prefix: 'zzzzzz', suffix: '', ignoreCase: false }, // near-impossible → never a natural hit
+ { stopRequested: () => batches >= 2, onProgress: () => { batches += 1; } },
+ );
+ expect(result.status).toBe('preempted');
+ expect(result.attempts).toBeGreaterThan(0);
+ expect(performance.now() - t0).toBeLessThan(5000);
+ });
+
+ it('gives up with status "exhausted" at maxAttempts on an unreachable target', async () => {
+ const { grindToCompletion } = await import('../workers/vanity-grinder/wasm-grind.mjs');
+ const result = grindToCompletion(
+ { prefix: 'zzzzzz', suffix: '', ignoreCase: false },
+ { stopRequested: () => false, maxAttempts: 50_000 },
+ );
+ expect(result.status).toBe('exhausted');
+ expect(result.attempts).toBeGreaterThanOrEqual(50_000);
+ });
+});
diff --git a/vercel.json b/vercel.json
index 2bddb758d..22013c5a5 100644
--- a/vercel.json
+++ b/vercel.json
@@ -105,6 +105,9 @@
"{api/mcp-studio,api/forge-nim,api/nim-forge,api/launch/mm,api/cron/avaturn-seed-cron,api/irl/interactions-stream}.js": {
"maxDuration": 300
},
+ "api/x402/remix-asset.js": {
+ "maxDuration": 300
+ },
"api/pump/launch-og.js": {
"includeFiles": "{examples/skills/**,data/pages.json,data/archives/**,data/rss/**,data/_generated/**,sdk/src/sas-config.json}",
"maxDuration": 15
diff --git a/workers/vanity-grinder/targets.mjs b/workers/vanity-grinder/targets.mjs
index 51233f365..963e4038d 100644
--- a/workers/vanity-grinder/targets.mjs
+++ b/workers/vanity-grinder/targets.mjs
@@ -12,9 +12,15 @@
// char prefixes (minutes of batch CPU each) with a few 5-char stretch goals.
// Brandable 3-char prefixes — fast to grind, broadly appealing.
+// NB: every char must be Base58-representable (no 0 / O / I / l) or the pattern is
+// unreachable; under ignoreCase the valid-case counterpart is matched. Keep these
+// GENERIC (product/tech/aesthetic words) — no third-party crypto tickers (commit gate).
const PREFIX_3 = [
'SOL', 'AiA', 'GM3', 'WS3', 'DEV', 'BOT', 'API', 'GPU', 'LAB', 'ZAP',
'ARC', 'ORB', 'ION', 'NEO', 'VIP', 'ACE', 'FOX', 'OWL', 'JET', 'RAY',
+ 'MAX', 'SKY', 'SUN', 'TOP', 'WEB', 'WIN', 'ZEN', 'HUB', 'KEY', 'MAP',
+ 'NET', 'PAY', 'PRO', 'RUN', 'TAG', 'GEM', 'PIX', 'NAV', 'FAB', 'MEG',
+ 'CAT', 'DOG', 'BEE', 'ANT', 'ELF', 'GUR', 'MAG', 'PUP', 'SAM', 'TEK',
];
// Brandable 4-char prefixes — the premium sweet spot (unreachable by the live
@@ -23,6 +29,10 @@ const PREFIX_4 = [
'PUMP', 'AGNT', 'MOON', 'MINT', 'FORG', 'DEGN', 'GOLD', 'NODE', 'DASH',
'ECHO', 'FLUX', 'HALO', 'IRIS', 'JADE', 'KILO', 'LUNA', 'NOVA', 'ONYX',
'THRE', 'WS3D', 'VOID', 'ZERO', 'BASE', 'CORE',
+ 'PEAK', 'BEAM', 'GLOW', 'SAGE', 'RUBY', 'MYTH', 'AXON', 'BYTE', 'CHIP',
+ 'DUSK', 'EPIC', 'FERN', 'GAZE', 'HERO', 'JOLT', 'KELP', 'MESA', 'NEST',
+ 'PACE', 'QUAD', 'REEF', 'SURF', 'TIDE', 'VANE', 'WAVE', 'YARN', 'ZEST',
+ 'AURA', 'BOLD', 'CUSP', 'DENS', 'EMBR', 'FUZE',
];
// 5-char stretch goals — hours of single-thread CPU, trivial on a wide spot MIG.