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: Implement health-aware lane selection and persona management

udvk1c04307cc510
diff --git a/.agents/.claude-plugin/plugin.json b/.agents/.claude-plugin/plugin.json
index 57e525150..0fbea566b 100644
--- a/.agents/.claude-plugin/plugin.json
+++ b/.agents/.claude-plugin/plugin.json
@@ -7,5 +7,16 @@
},
"homepage": "https://three.ws",
"license": "Apache-2.0",
- "repository": "https://github.com/nirholas/three.ws"
+ "repository": "https://github.com/nirholas/three.ws",
+ "keywords": [
+ "wallet",
+ "x402",
+ "usdc",
+ "payments",
+ "trade",
+ "base",
+ "solana",
+ "polygon"
+ ],
+ "category": "payments"
}
diff --git a/api/_lib/cache.js b/api/_lib/cache.js
index 7b6cf6669..ce89b3921 100644
--- a/api/_lib/cache.js
+++ b/api/_lib/cache.js
@@ -211,7 +211,13 @@ export async function cacheWrap(key, ttlSeconds, fn) {
if (hit !== null && hit !== undefined) return hit;
const value = await fn();
if (value !== null && value !== undefined) {
- await cacheSet(key, value, ttlSeconds);
+ // Don't block the response on the write-back. The value is already in hand;
+ // the cache is an optimization, not part of the result. Awaiting here put a
+ // degraded Upstash (writes timing out at REDIS_CMD_TIMEOUT_MS) directly on
+ // the request's critical path — up to 3s of dead latency per miss for a SET
+ // that then falls back to memory anyway. cacheSet swallows its own errors
+ // (never rejects), so fire-and-forget is safe; the .catch is belt-and-braces.
+ cacheSet(key, value, ttlSeconds).catch(() => {});
}
return value;
}
diff --git a/api/_lib/forge-lane-health.js b/api/_lib/forge-lane-health.js
new file mode 100644
index 000000000..8a0de2e12
--- /dev/null
+++ b/api/_lib/forge-lane-health.js
@@ -0,0 +1,148 @@
+// Lightweight liveness/warmth for the self-host GPU lanes — the signal the
+// health-aware router consults so a cold or down worker is skipped BEFORE submit.
+//
+// forge-health.js already runs a heavy, everything-at-once health report (every
+// backend + the limiter + the world + LLM providers, 60s cache) for the status
+// dashboard. The router needs something cheaper and tighter: just "can our own
+// GPU workers serve a generation right now, and are they warm?" — answered from
+// a short per-instance cache so the hot generation path pays no probe latency in
+// the common case.
+//
+// Two independent signals fold into each lane's status:
+// 1. A recent submit failure recorded a cooldown in the SHARED cache
+// (provider-health.js) — cross-instance memory that a lane just failed, so
+// every instance skips it until the window expires. This is authoritative:
+// a cooled lane is reported `down` without spending a probe.
+// 2. A cheap authenticated GET against the worker root. Cloud Run answers
+// anything <500 the moment a container is up and routable; unreachable /
+// timeout / 5xx means a submit would fail. Round-trip latency doubles as a
+// warmth signal — a scale-to-zero container that just spun up answers slowly.
+//
+// Only self-host (provider === 'gcp') lanes are probed; the free external lanes
+// (NVIDIA NIM, HuggingFace) carry their own circuit breakers in the handler and
+// are reported `unknown` here unless a cooldown marks them down, so the router
+// never blocks on telemetry it doesn't have.
+//
+// Everything is best-effort and fail-open: a probe error or cache miss degrades
+// to `unknown`, which the router treats as usable — exactly the pre-health
+// behaviour.
+
+import { BACKENDS, isSelfHostBackend } from './forge-tiers.js';
+import { providersInCooldown, markProviderCooldown } from './provider-health.js';
+
+// Self-host worker URLs are env-gated; the URL env is the lane's first requiresEnv
+// entry, the bearer is the shared GCP_RECONSTRUCTION_KEY (second entry).
+function readEnv(name) {
+ if (typeof process !== 'undefined' && process.env?.[name]) return process.env[name];
+ return null;
+}
+
+// Cooldown key for a lane's recent-failure breaker. Distinct namespace from the
+// LLM/NIM keys so a self-host worker outage can't collide with another lane's.
+export function laneCooldownKey(backendId) {
+ return `forge-lane:${backendId}`;
+}
+
+// Record that a self-host lane just failed at submit, so subsequent requests on
+// any instance skip it until the window expires. Fire-and-forget; never throws.
+const LANE_COOLDOWN_SECONDS = 90;
+export async function markLaneUnhealthy(backendId, seconds = LANE_COOLDOWN_SECONDS) {
+ if (!backendId) return;
+ await markProviderCooldown(laneCooldownKey(backendId), seconds).catch(() => {});
+}
+
+const PROBE_TIMEOUT_MS = 2_500;
+// A reachable worker that answers within this is warm; slower means it is most
+// likely a scale-to-zero container spinning up, so the lane is reported cold and
+// the caller widens the ETA by the lane's cold-start budget.
+const WARM_LATENCY_MS = 1_200;
+// Per-instance snapshot cache — short enough that a worker coming back is picked
+// up within a poll cycle, long enough that a burst of generations shares one probe.
+const SNAPSHOT_TTL_MS = 20_000;
+
+let snapshotCache = null; // { at, byId }
+
+// Probe one self-host worker: authenticated GET against its root. Returns a status
+// record. The URL/key being absent is reported `unknown` (env-gating already
+// keeps an unconfigured lane out of routing) rather than `down`.
+async function probeSelfHostLane(backendId) {
+ const meta = BACKENDS[backendId];
+ const urlEnv = meta?.requiresEnv?.[0];
+ const url = urlEnv ? readEnv(urlEnv) : null;
+ const key = readEnv('GCP_RECONSTRUCTION_KEY');
+ if (!url || !key) return { id: backendId, status: 'unknown', warm: false };
+
+ const started = Date.now();
+ let res;
+ try {
+ res = await fetch(url, {
+ headers: { authorization: `Bearer ${key}` },
+ signal: AbortSignal.timeout(PROBE_TIMEOUT_MS),
+ });
+ } catch {
+ return { id: backendId, status: 'down', warm: false };
+ }
+ const latencyMs = Date.now() - started;
+ if (res.status >= 500) return { id: backendId, status: 'down', warm: false, latencyMs };
+ // <500 (200/401/404/…) means the container is up and routable — a generation
+ // would reach the worker. Latency tells us whether it is warm.
+ return { id: backendId, status: 'ok', warm: latencyMs <= WARM_LATENCY_MS, latencyMs };
+}
+
+// Health snapshot for a set of candidate lane ids. Self-host lanes are probed
+// (cooldown short-circuits the probe); other lanes are reported from cooldown
+// state only. Cached per instance for SNAPSHOT_TTL_MS so a burst of generations
+// shares one probe round and the hot path usually pays nothing.
+//
+// Returns { byId: { [id]: { status, warm, latencyMs? } }, statusMap: { [id]: status } }.
+// `statusMap` is the shape resolveBackendIdWithHealth() consumes directly.
+export async function laneHealthSnapshot(candidateIds = [], { force = false } = {}) {
+ const ids = [...new Set(candidateIds)].filter((id) => BACKENDS[id]);
+ if (!ids.length) return { byId: {}, statusMap: {} };
+
+ if (!force && snapshotCache && Date.now() - snapshotCache.at < SNAPSHOT_TTL_MS) {
+ // Serve cached entries; probe only ids we haven't seen this window.
+ const missing = ids.filter((id) => !(id in snapshotCache.byId));
+ if (!missing.length) return project(ids, snapshotCache.byId);
+ const fresh = await probeMany(missing);
+ snapshotCache = { at: snapshotCache.at, byId: { ...snapshotCache.byId, ...fresh } };
+ return project(ids, snapshotCache.byId);
+ }
+
+ const byId = await probeMany(ids);
+ snapshotCache = { at: Date.now(), byId };
+ return project(ids, byId);
+}
+
+async function probeMany(ids) {
+ // One shared cooldown read covers every candidate (the cache layer coalesces).
+ const cooling = await providersInCooldown(ids.map(laneCooldownKey)).catch(() => new Map());
+ const entries = await Promise.all(
+ ids.map(async (id) => {
+ // A cooled lane is authoritatively down — skip the probe entirely.
+ if (cooling.has(laneCooldownKey(id))) return [id, { id, status: 'down', warm: false, cooled: true }];
+ if (isSelfHostBackend(id)) return [id, await probeSelfHostLane(id)];
+ // External free lane (NVIDIA/HF): no cheap warmth probe here (they have
+ // their own breakers in the handler) — report unknown so the router never
+ // blocks on it.
+ return [id, { id, status: 'unknown', warm: false }];
+ }),
+ );
+ return Object.fromEntries(entries);
+}
+
+function project(ids, byId) {
+ const out = {};
+ const statusMap = {};
+ for (const id of ids) {
+ const rec = byId[id] || { id, status: 'unknown', warm: false };
+ out[id] = rec;
+ statusMap[id] = rec.status;
+ }
+ return { byId: out, statusMap };
+}
+
+// Test hook — the snapshot is cached per instance; tests need a clean slate.
+export function resetLaneHealthCache() {
+ snapshotCache = null;
+}
diff --git a/api/_lib/persona-store.js b/api/_lib/persona-store.js
new file mode 100644
index 000000000..c789a7f05
--- /dev/null
+++ b/api/_lib/persona-store.js
@@ -0,0 +1,340 @@
+/**
+ * Persistent agent personas — the identity layer behind an embodied agent.
+ *
+ * A persona is a NAMED, durable body: a rigged GLB the agent reuses turn after
+ * turn and session after session, plus the small bag of identity that makes it
+ * itself (display name, look notes, voice, an emotional baseline, the prompt that
+ * forged it). Where save_avatar persists a model into a signed-in user's library,
+ * a persona is addressable by an unguessable id ALONE — so an embodiment component
+ * embedded in ChatGPT/Claude can mint one anonymously and return to the exact same
+ * body later by id, with no account required. The id IS the capability.
+ *
+ * Storage, real and tiered:
+ * • Production: a Postgres `agent_personas` row (created lazily, see ensureSchema)
+ * plus a durable R2 copy of the GLB so the body outlives the provider URL.
+ * • Local/dev/test (no DATABASE_URL): a JSON record on disk under a data dir, so
+ * "reload the same persona id in a new process and get the same body" actually
+ * works on a laptop with zero cloud config. Same record shape either way.
+ *
+ * Nothing here touches tokens, wallets, or payments — a persona is a body and a
+ * name. The public projection (personaPublicView) strips storage keys and owner
+ * ids so a tool response never leaks internal identifiers.
+ */
+
+import { createHash, randomBytes } from 'node:crypto';
+import { promises as fs } from 'node:fs';
+import os from 'node:os';
+import path from 'node:path';
+import { sql } from './db.js';
+import { putObject, copyObject, publicUrl } from './r2.js';
+
+const dbConfigured = () => !!process.env.DATABASE_URL;
+const r2Configured = () => !!(process.env.S3_BUCKET && process.env.S3_PUBLIC_DOMAIN);
+
+// ── pure helpers (no backend — unit-testable on their own) ────────────────────
+
+const ID_PREFIX = 'persona_';
+
+/**
+ * Mint a stable, URL-safe, unguessable persona id. Deterministic when a `seed` is
+ * supplied (for tests / reproducible fixtures), random otherwise.
+ * @param {string} [seed]
+ * @returns {string}
+ */
+export function makePersonaId(seed) {
+ const bytes = seed
+ ? createHash('sha256').update(String(seed)).digest().subarray(0, 15)
+ : randomBytes(15);
+ return ID_PREFIX + bytes.toString('base64url');
+}
+
+/** True if a string is a well-formed persona id (cheap guard before a lookup). */
+export function isPersonaId(v) {
+ return typeof v === 'string' && /^persona_[A-Za-z0-9_-]{16,32}$/.test(v);
+}
+
+/**
+ * Normalize raw create input into the canonical persona record fields. Pure: no
+ * I/O. Clamps/sanitizes user-supplied strings so neither backend stores garbage.
+ * @param {object} input
+ * @returns {object}
+ */
+export function normalizePersonaInput(input = {}) {
+ const clamp = (v, n) => (v == null ? null : String(v).trim().slice(0, n) || null);
+ const look = input.look && typeof input.look === 'object' ? input.look : {};
+ return {
+ name: clamp(input.name, 80) || 'Agent',
+ glb_url: clamp(input.glbUrl ?? input.glb_url, 2048),
+ glb_key: clamp(input.glbKey ?? input.glb_key, 1024),
+ thumbnail_url: clamp(input.thumbnailUrl ?? input.thumbnail_url, 2048),
+ voice: clamp(input.voice, 64),
+ emotion_baseline: clamp(input.emotionBaseline ?? input.emotion_baseline, 24) || 'neutral',
+ source_prompt: clamp(input.sourcePrompt ?? input.source_prompt, 1000),
+ owner_id: clamp(input.ownerId ?? input.owner_id, 128),
+ look: {
+ rigged: look.rigged ?? null,
+ has_visemes: look.has_visemes ?? look.hasVisemes ?? null,
+ mesh_count: Number.isFinite(look.mesh_count) ? look.mesh_count : null,
+ animation_count: Number.isFinite(look.animation_count) ? look.animation_count : null,
+ style: clamp(look.style, 120),
+ },
+ };
+}
+
+/**
+ * The safe, outward projection of a persona — what a tool response or the
+ * embodiment component is allowed to see. Drops storage keys and owner ids;
+ * keeps only what's needed to render and reload the body.
+ * @param {object} rec
+ */
+export function personaPublicView(rec) {
+ if (!rec) return null;
+ return {
+ persona_id: rec.id,
+ name: rec.name,
+ glb_url: rec.glb_url,
+ thumbnail_url: rec.thumbnail_url || null,
+ voice: rec.voice || null,
+ emotion_baseline: rec.emotion_baseline || 'neutral',
+ look: rec.look || {},
+ turn_count: rec.turn_count || 0,
+ created_at: rec.created_at || null,
+ last_seen_at: rec.last_seen_at || null,
+ };
+}
+
+// ── durable GLB copy ──────────────────────────────────────────────────────────
+
+/**
+ * Copy a forged GLB into our own durable storage so the persona's body survives
+ * the provider's delivery URL expiring. Returns { glbUrl, glbKey }. When R2 isn't
+ * configured (local dev) the source URL is kept as-is — the persona still persists,
+ * it just references the original asset.
+ *
+ * @param {string} sourceUrl public https GLB URL (or a same-origin /asset path)
+ * @param {string} personaId
+ * @param {Buffer|null} [buffer] pre-fetched bytes (skip a re-download)
+ */
+export async function persistPersonaGlb(sourceUrl, personaId, buffer = null) {
+ if (!r2Configured()) return { glbUrl: sourceUrl, glbKey: null };
+ const key = `personas/${personaId}.glb`;
+ try {
+ if (buffer) {
+ await putObject({ key, body: buffer, contentType: 'model/gltf-binary', metadata: { kind: 'persona', persona_id: personaId } });
+ } else if (/^https?:\/\//i.test(sourceUrl)) {
+ // Fetch + put (copyObject only works for keys already in our bucket).
+ const resp = await fetch(sourceUrl);
+ if (!resp.ok) throw new Error(`fetch ${resp.status}`);
+ const body = Buffer.from(await resp.arrayBuffer());
+ await putObject({ key, body, contentType: 'model/gltf-binary', metadata: { kind: 'persona', persona_id: personaId } });
+ } else {
+ return { glbUrl: sourceUrl, glbKey: null };
+ }
+ return { glbUrl: publicUrl(key), glbKey: key };
+ } catch {
+ // Durable copy failed — keep the source URL rather than losing the persona.
+ return { glbUrl: sourceUrl, glbKey: null };
+ }
+}
+
+// ── Postgres backend ──────────────────────────────────────────────────────────
+
+let _schemaReady = null;
+async function ensureSchema() {
+ if (_schemaReady) return _schemaReady;
+ _schemaReady = sql`
+ create table if not exists agent_personas (
+ id text primary key,
+ owner_id text,
+ name text not null,
+ glb_url text not null,
+ glb_key text,
+ thumbnail_url text,
+ voice text,
+ emotion_baseline text default 'neutral',
+ look jsonb not null default '{}'::jsonb,
+ source_prompt text,
+ turn_count integer not null default 0,
+ created_at timestamptz not null default now(),
+ updated_at timestamptz not null default now(),
+ last_seen_at timestamptz not null default now()
+ )
+ `.then(() => true);
+ return _schemaReady;
+}
+
+function rowToRecord(row) {
+ if (!row) return null;
+ return {
+ id: row.id,
+ owner_id: row.owner_id,
+ name: row.name,
+ glb_url: row.glb_url,
+ glb_key: row.glb_key,
+ thumbnail_url: row.thumbnail_url,
+ voice: row.voice,
+ emotion_baseline: row.emotion_baseline || 'neutral',
+ look: typeof row.look === 'string' ? JSON.parse(row.look) : row.look || {},
+ source_prompt: row.source_prompt,
+ turn_count: row.turn_count || 0,
+ created_at: row.created_at,
+ updated_at: row.updated_at,
+ last_seen_at: row.last_seen_at,
+ };
+}
+
+// ── filesystem backend (local/dev/test fallback) ──────────────────────────────
+
+function storeDir() {
+ return process.env.PERSONA_STORE_DIR || path.join(process.cwd(), '.data', 'personas');
+}
+async function fsDir() {
+ const dir = storeDir();
+ try {
+ await fs.mkdir(dir, { recursive: true });
+ return dir;
+ } catch {
+ // cwd is read-only (serverless) — fall back to the OS temp dir. Ephemeral,
+ // but it keeps the path working; production uses Postgres, not this.
+ const tmp = path.join(os.tmpdir(), 'threews-personas');
+ await fs.mkdir(tmp, { recursive: true });
+ return tmp;
+ }
+}
+const fsFile = (dir, id) => path.join(dir, `${id}.json`);
+
+async function fsWrite(rec) {
+ const dir = await fsDir();
+ await fs.writeFile(fsFile(dir, rec.id), JSON.stringify(rec, null, 2), 'utf8');
+ return rec;
+}
+async function fsRead(id) {
+ const dir = await fsDir();
+ try {
+ return JSON.parse(await fs.readFile(fsFile(dir, id), 'utf8'));
+ } catch {
+ return null;
+ }
+}
+
+// ── public API ────────────────────────────────────────────────────────────────
+
+/**
+ * Create and persist a new persona. The GLB is copied into durable storage first
+ * (when configured) so the body outlives the provider URL.
+ *
+ * @param {object} input { name, glbUrl, glbKey?, thumbnailUrl?, voice?, emotionBaseline?, sourcePrompt?, ownerId?, look? }
+ * @returns {Promise<object>} the stored record
+ */
+export async function createPersona(input) {
+ const norm = normalizePersonaInput(input);
+ if (!norm.glb_url) throw new Error('createPersona requires a glbUrl');
+ const id = makePersonaId(input.idSeed);
+
+ // Durable-copy the body unless the caller already handed us a stored key.
+ let glbUrl = norm.glb_url;
+ let glbKey = norm.glb_key;
+ if (!glbKey) {
+ const persisted = await persistPersonaGlb(norm.glb_url, id, input.glbBuffer || null);
+ glbUrl = persisted.glbUrl;
+ glbKey = persisted.glbKey;
+ }
+
+ const record = {
+ id,
+ owner_id: norm.owner_id,
+ name: norm.name,
+ glb_url: glbUrl,
+ glb_key: glbKey,
+ thumbnail_url: norm.thumbnail_url,
+ voice: norm.voice,
+ emotion_baseline: norm.emotion_baseline,
+ look: norm.look,
+ source_prompt: norm.source_prompt,
+ turn_count: 0,
+ created_at: new Date().toISOString(),
+ updated_at: new Date().toISOString(),
+ last_seen_at: new Date().toISOString(),
+ };
+
+ if (dbConfigured()) {
+ await ensureSchema();
+ const [row] = await sql`
+ insert into agent_personas (id, owner_id, name, glb_url, glb_key, thumbnail_url, voice, emotion_baseline, look, source_prompt)
+ values (${record.id}, ${record.owner_id}, ${record.name}, ${record.glb_url}, ${record.glb_key},
+ ${record.thumbnail_url}, ${record.voice}, ${record.emotion_baseline},
+ ${JSON.stringify(record.look)}::jsonb, ${record.source_prompt})
+ returning *`;
+ return rowToRecord(row);
+ }
+ return fsWrite(record);
+}
+
+/**
+ * Load a persona by id. The id is the capability, so no ownership check is
+ * required to read — that is what lets a fresh session reload the same body.
+ * @param {string} id
+ * @returns {Promise<object|null>}
+ */
+export async function getPersona(id) {
+ if (!isPersonaId(id)) return null;
+ if (dbConfigured()) {
+ await ensureSchema();
+ const [row] = await sql`select * from agent_personas where id = ${id} limit 1`;
+ return rowToRecord(row);
+ }
+ return fsRead(id);
+}
+
+/**
+ * Patch a persona's mutable identity (name, look, voice, thumbnail). Storage keys
+ * and the owner are immutable here.
+ * @param {string} id
+ * @param {object} patch
+ * @returns {Promise<object|null>}
+ */
+export async function updatePersona(id, patch = {}) {
+ const cur = await getPersona(id);
+ if (!cur) return null;
+ const next = {
+ ...cur,
+ name: patch.name != null ? String(patch.name).trim().slice(0, 80) : cur.name,
+ voice: patch.voice != null ? String(patch.voice).trim().slice(0, 64) : cur.voice,
+ thumbnail_url: patch.thumbnailUrl != null ? String(patch.thumbnailUrl).slice(0, 2048) : cur.thumbnail_url,
+ emotion_baseline: patch.emotionBaseline != null ? String(patch.emotionBaseline).slice(0, 24) : cur.emotion_baseline,
+ look: patch.look && typeof patch.look === 'object' ? { ...cur.look, ...patch.look } : cur.look,
+ updated_at: new Date().toISOString(),
+ };
+ if (dbConfigured()) {
+ await ensureSchema();
+ const [row] = await sql`
+ update agent_personas set
+ name = ${next.name}, voice = ${next.voice}, thumbnail_url = ${next.thumbnail_url},
+ emotion_baseline = ${next.emotion_baseline}, look = ${JSON.stringify(next.look)}::jsonb,
+ updated_at = now()
+ where id = ${id} returning *`;
+ return rowToRecord(row);
+ }
+ return fsWrite(next);
+}
+
+/**
+ * Record that the persona spoke a turn — bumps turn_count and last_seen, the
+ * continuity signal that proves the same body is being reused across a session.
+ * @param {string} id
+ * @returns {Promise<object|null>}
+ */
+export async function touchPersona(id) {
+ if (dbConfigured()) {
+ await ensureSchema();
+ const [row] = await sql`
+ update agent_personas set turn_count = turn_count + 1, last_seen_at = now()
+ where id = ${id} returning *`;
+ return rowToRecord(row);
+ }
+ const cur = await fsRead(id);
+ if (!cur) return null;
+ cur.turn_count = (cur.turn_count || 0) + 1;
+ cur.last_seen_at = new Date().toISOString();
+ return fsWrite(cur);
+}
diff --git a/api/_mcp3d/tools/studio.js b/api/_mcp3d/tools/studio.js
index ed13eb946..146c74907 100644
--- a/api/_mcp3d/tools/studio.js
+++ b/api/_mcp3d/tools/studio.js
@@ -41,6 +41,14 @@ import { createAvatar, storageKeyFor } from '../../_lib/avatars.js';
import { putObject } from '../../_lib/r2.js';
import { isValidGlbHeader, inspectGlb } from '../../_lib/glb-inspect.js';
import { env } from '../../_lib/env.js';
+import {
+ createPersona,
+ getPersona,
+ touchPersona,
+ personaPublicView,
+ isPersonaId,
+} from '../../_lib/persona-store.js';
+import { expressionForText, expressionFor } from '../../../src/embodiment/emotion.js';
import { PRESETS, PRESET_GROUPS } from '../../../src/pose-presets.js';
import {
renderModelViewerHtml,
@@ -177,6 +185,70 @@ function viewerArtifact({ glbUrl, name, options = {} }) {
};
}
+// The Apps SDK template URL the embodiment component is served from. A persona
+// tool result references this so a host (ChatGPT/Claude) renders the LIVING body
+// inline — the same hosted page the local demo harness drives.
+const EMBODIMENT_EMBED = `${env.APP_ORIGIN}/embodiment/embed`;
+
+function buildEmbedUrl({ persona, state, text, emotion, intensity, gesture }) {
+ const u = new URL(EMBODIMENT_EMBED);
+ u.searchParams.set('persona', persona.persona_id);
+ u.searchParams.set('glb', persona.glb_url);
+ if (persona.name) u.searchParams.set('name', persona.name);
+ if (state) u.searchParams.set('state', state);
+ if (text) u.searchParams.set('text', text.slice(0, 600));
+ if (emotion) u.searchParams.set('emotion', emotion);
+ if (intensity != null) u.searchParams.set('intensity', String(intensity));
+ if (gesture) u.searchParams.set('gesture', gesture);
+ return u.toString();
+}
+
+// Render the embodied persona as an inline, sandboxed artifact: a self-contained
+// HTML document that mounts the hosted embodiment component (the live, rigged body
+// that lip-syncs + emotes) and passes the turn's speak/emotion payload. Mirrors the
+// viewerArtifact contract; adds the `_meta` openai/outputTemplate key so Apps SDK
+// hosts that prefer a registered template can use the same embed URL.
+function embodimentArtifact({ persona, state = 'idle', text = '', emotion = 'neutral', intensity = 0, gesture = null }) {
+ const embedUrl = buildEmbedUrl({ persona, state, text, emotion, intensity, gesture });
+ const safe = (s) => String(s).replace(/[&<>"]/g, (c) => ({ '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '&quot;' })[c]);
+ const html =
+ `<!doctype html><html lang="en"><head><meta charset="utf-8">` +
+ `<meta name="viewport" content="width=device-width,initial-scale=1">` +
+ `<title>${safe(persona.name || 'Agent')} — live</title>` +
+ `<style>html,body{margin:0;height:100%;background:transparent}` +
+ `.wrap{position:relative;width:100%;height:480px;border-radius:16px;overflow:hidden;` +
+ `background:radial-gradient(120% 120% at 50% 0%,#1a1a24 0%,#0c0c12 70%)}` +
+ `iframe{width:100%;height:100%;border:0;display:block}` +
+ `.fb{position:absolute;inset:auto 0 0 0;padding:8px 12px;font:600 12px system-ui;color:#cbd5e1;text-align:center}` +
+ `.fb a{color:#a78bfa}</style></head><body>` +
+ `<div class="wrap"><iframe title="${safe(persona.name || 'Agent')} live avatar" ` +
+ `src="${safe(embedUrl)}" allow="autoplay" sandbox="allow-scripts allow-same-origin allow-popups"></iframe>` +
+ `<noscript class="fb">Open <a href="${safe(embedUrl)}">${safe(persona.name || 'this agent')}</a> in a browser.</noscript>` +
+ `</div></body></html>`;
+ return {
+ type: 'resource',
+ resource: {
+ uri: embedUrl,
+ mimeType: 'text/html',
+ text: html,
+ _meta: { 'openai/outputTemplate': embedUrl },
+ },
+ };
+}
+
+// Annotations for the persona lifecycle tools. create mints a new body (write,
+// non-destructive). get is a pure read. say is a render directive that also bumps
+// the persona's turn counter — a write, never destructive.
+const PERSONA_CREATE_ANNOTATIONS = {
+ readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: true,
+};
+const PERSONA_READ_ANNOTATIONS = {
+ readOnlyHint: true, destructiveHint: false, idempotentHint: true, openWorldHint: false,
+};
+const PERSONA_SAY_ANNOTATIONS = {
+ readOnlyHint: false, destructiveHint: false, idempotentHint: false, openWorldHint: false,
+};
+
// ── Quality tier + generation path/engine (shared by text_to_3d/image_to_3d) ──
// Mirrors the /api/forge axes: `path` ("image" vs "geometry"), `tier`
// (draft/standard/high poly budget), and `backend` — exposed as the white-labeled
@@ -1846,4 +1918,227 @@ export const toolDefs = [
};
},
},
+ {
+ name: 'create_agent_persona',
+ title: 'Mint a persistent, living agent persona from a rigged GLB',
+ annotations: PERSONA_CREATE_ANNOTATIONS,
+ description:
+ 'Turn a generated GLB into a NAMED, persistent agent body — a "persona" the agent reuses across turns and across sessions. The mesh is copied into durable storage so the body survives the provider URL expiring, then registered under a stable persona_id. The returned text/html resource renders the LIVING body inline: it idles between turns, and persona_say makes it lip-sync and emote a reply. The persona_id is the capability — keep it and pass it to get_agent_persona or persona_say later to bring the exact same body back. No sign-in required.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ glb_url: {
+ type: 'string',
+ format: 'uri',
+ description: 'Public https URL of the rigged GLB to embody (e.g. from generation_status).',
+ },
+ name: {
+ type: 'string',
+ minLength: 1,
+ maxLength: 80,
+ description: 'A display name for the persona, 1–80 characters.',
+ },
+ voice: {
+ type: 'string',
+ maxLength: 64,
+ description: 'Optional voice id/name to speak with (used for TTS-driven lip-sync when available).',
+ },
+ source_prompt: {
+ type: 'string',
+ maxLength: 1000,
+ description: 'Optional: the prompt that generated this body, kept as provenance.',
+ },
+ },
+ required: ['glb_url', 'name'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ await enforce(limits.mcp3dGenerate, auth);
+ if (!(await isPublicHttpsUrl(args.glb_url))) {
+ return {
+ content: [{ type: 'text', text: 'Error: glb_url must be a public https URL.' }],
+ isError: true,
+ };
+ }
+ const buf = await fetchGlbBuffer(args.glb_url);
+ const info = isValidGlbHeader(buf) ? inspectGlb(buf) : null;
+ if (!info) {
+ return {
+ content: [
+ { type: 'text', text: 'Error: that URL did not return a valid GLB (binary glTF). Pass a .glb model URL.' },
+ ],
+ isError: true,
+ };
+ }
+
+ const record = await createPersona({
+ name: args.name,
+ glbUrl: args.glb_url,
+ glbBuffer: buf,
+ voice: args.voice ?? null,
+ sourcePrompt: args.source_prompt ?? null,
+ ownerId: auth.userId ?? null,
+ look: {
+ rigged: info.isRigged ?? null,
+ mesh_count: info.meshCount ?? null,
+ animation_count: info.animationCount ?? null,
+ },
+ });
+ const persona = personaPublicView(record);
+
+ return {
+ content: [
+ {
+ type: 'text',
+ text:
+ `Minted "${persona.name}" as a living persona.\n` +
+ `Persona ID: ${persona.persona_id}\n` +
+ (persona.look?.rigged ? 'Rig: humanoid — full body animation + lip-sync.\n' : 'Rig: static/non-humanoid — will fall back to the default rig gracefully.\n') +
+ 'Display the attached text/html resource to see the body. ' +
+ 'Call persona_say with this persona_id to make it speak a reply, or get_agent_persona to bring it back in a future session.',
+ },
+ embodimentArtifact({ persona, state: 'idle' }),
+ ],
+ structuredContent: { ...persona, status: 'created' },
+ };
+ },
+ },
+ {
+ name: 'get_agent_persona',
+ title: 'Reload a persisted persona by id (continuity across sessions)',
+ annotations: PERSONA_READ_ANNOTATIONS,
+ description:
+ 'Bring back a previously minted persona by its persona_id — the SAME body and identity, in a fresh session. Returns the persona name, its GLB, accumulated turn count, and the inline living-body artifact. Use this at the start of a conversation when the user returns to a named agent.',
+ inputSchema: {
+ type: 'object',
+ properties: {
+ persona_id: {
+ type: 'string',
+ minLength: 8,
+ maxLength: 64,
+ description: 'The persona_id returned by create_agent_persona.',
+ },
+ },
+ required: ['persona_id'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ await enforce(limits.mcp3dRead || limits.mcp3dGenerate, auth);
+ if (!isPersonaId(args.persona_id)) {
+ return {
+ content: [{ type: 'text', text: 'Error: that is not a valid persona_id.' }],
+ structuredContent: { status: 'invalid_id' },
+ isError: true,
+ };
+ }
+ const record = await getPersona(args.persona_id);
+ if (!record) {
+ return {
+ content: [{ type: 'text', text: 'No persona found for that id. Mint one with create_agent_persona.' }],
+ structuredContent: { status: 'not_found' },
+ isError: true,
+ };
+ }
+ const persona = personaPublicView(record);
+ return {
+ content: [
+ {
+ type: 'text',
+ text:
+ `Welcome back, ${persona.name}.\n` +
+ `Persona ID: ${persona.persona_id}\n` +
+ `Turns spoken so far: ${persona.turn_count}.\n` +
+ 'Display the attached text/html resource to see the body; call persona_say to make it speak.',
+ },
+ embodimentArtifact({ persona, state: 'idle' }),
+ ],
+ structuredContent: { ...persona, status: 'loaded' },
+ };
+ },
+ },
+ {
+ name: 'persona_say',
+ title: 'Speak a reply through a persona — lip-sync + emotion + gesture',
+ annotations: PERSONA_SAY_ANNOTATIONS,
+ description:
+ "Make a persona PERFORM a reply: the body lip-syncs the text and shows the matching expression and body gesture. Pass the persona_id and the exact text the agent is saying this turn; the emotion is detected from the text automatically (or override it). The returned text/html resource animates the body for this turn — display it alongside the spoken reply. This is the turn-by-turn embodiment hook.",
+ inputSchema: {
+ type: 'object',
+ properties: {
+ persona_id: {
+ type: 'string',
+ minLength: 8,
+ maxLength: 64,
+ description: 'The persona to speak through.',
+ },
+ text: {
+ type: 'string',
+ minLength: 1,
+ maxLength: 2000,
+ description: 'The reply text the agent is saying this turn — drives lip-sync and emotion.',
+ },
+ emotion: {
+ type: 'string',
+ enum: ['neutral', 'joy', 'sad', 'angry', 'surprised', 'thinking'],
+ description: 'Optional explicit emotion override; omit to auto-detect from the text.',
+ },
+ },
+ required: ['persona_id', 'text'],
+ additionalProperties: false,
+ },
+ async handler(args, auth) {
+ await enforce(limits.mcp3dGenerate, auth);
+ if (!isPersonaId(args.persona_id)) {
+ return {
+ content: [{ type: 'text', text: 'Error: that is not a valid persona_id.' }],
+ structuredContent: { status: 'invalid_id' },
+ isError: true,
+ };
+ }
+ const record = await getPersona(args.persona_id);
+ if (!record) {
+ return {
+ content: [{ type: 'text', text: 'No persona found for that id. Mint one with create_agent_persona.' }],
+ structuredContent: { status: 'not_found' },
+ isError: true,
+ };
+ }
+ const expr = args.emotion
+ ? { ...expressionFor(args.emotion, 0.85), scores: {} }
+ : expressionForText(args.text);
+ const updated = await touchPersona(args.persona_id);
+ const persona = personaPublicView(updated || record);
+
+ return {
+ content: [
+ {
+ type: 'text',
+ text:
+ `${persona.name} says it with a ${expr.emotion} expression` +
+ (expr.gesture ? ` and a ${expr.gesture} gesture` : '') +
+ `. Display the attached text/html resource — the body lip-syncs the reply and emotes.`,
+ },
+ embodimentArtifact({
+ persona,
+ state: 'speaking',
+ text: args.text,
+ emotion: expr.emotion,
+ intensity: expr.intensity,
+ gesture: expr.gesture,
+ }),
+ ],
+ structuredContent: {
+ persona_id: persona.persona_id,
+ name: persona.name,
+ glb_url: persona.glb_url,
+ text: args.text,
+ emotion: expr.emotion,
+ intensity: expr.intensity,
+ gesture: expr.gesture,
+ turn_count: persona.turn_count,
+ status: 'spoken',
+ },
+ };
+ },
+ },
];
diff --git a/api/agent-delegate.js b/api/agent-delegate.js
index d57412dda..df5f11177 100644
--- a/api/agent-delegate.js
+++ b/api/agent-delegate.js
@@ -48,6 +48,9 @@ export default wrap(async (req, res) => {
'llm_unavailable',
'agent delegation is not available right now',
);
- return error(res, 502, 'upstream_error', `LLM call failed: ${err.message}`);
+ // An LLM/provider error can embed keyed RPC/provider URLs — keep it out of
+ // the client response; the detail is logged server-side for triage.
+ console.error('[agent-delegate] LLM call failed:', err?.message || err);
+ return error(res, 502, 'upstream_error', 'Agent delegation failed temporarily. Try again shortly.');
}
});
diff --git a/api/agent-wallet-bridge.js b/api/agent-wallet-bridge.js
index 037515831..a7ef040e6 100644
--- a/api/agent-wallet-bridge.js
+++ b/api/agent-wallet-bridge.js
@@ -295,7 +295,10 @@ export default wrap(async (req, res) => {
resource: challenge.resource || null,
}));
} catch (err) {
- error(res, 502, 'quote_failed', err.message);
+ // Don't echo upstream endpoint URLs / response bodies to the caller —
+ // fetch402 errors embed both. Log server-side, return a stable message.
+ console.error('[agent-wallet-bridge] quote_failed:', err?.message || err);
+ error(res, 502, 'quote_failed', 'Unable to retrieve a payment quote right now. Try again shortly.');
}
return;
}
diff --git a/api/artifact.js b/api/artifact.js
index c17c48ed4..50a3e847a 100644
--- a/api/artifact.js
+++ b/api/artifact.js
@@ -261,7 +261,10 @@ export default wrap(async (req, res) => {
try {
result = await loadModelArtifactConfig(safeUrl, opts);
} catch (err) {
- return error(res, 502, 'upstream_error', err.message || 'model fetch failed');
+ // Upstream fetch/parse errors can carry internal URLs and paths — log
+ // the detail server-side and return a stable, non-revealing message.
+ console.error('[artifact] loadModelArtifactConfig failed:', err?.message || err);
+ return error(res, 502, 'upstream_error', 'Could not load the model configuration.');
}
}
diff --git a/api/forge.js b/api/forge.js
index e61d16386..f89687c02 100644
--- a/api/forge.js
+++ b/api/forge.js
@@ -44,11 +44,16 @@ import {
BACKENDS,
resolveTier,
resolveBackendId,
+ resolveBackendIdWithHealth,
+ freeLaneCandidates,
+ isSelfHostBackend,
+ coldStartSecondsFor,
estimateEtaSeconds,
estimateCredits,
preferFreeReconstruct,
buildCatalog,
} from './_lib/forge-tiers.js';
+import { laneHealthSnapshot, markLaneUnhealthy } from './_lib/forge-lane-health.js';
import { resolveProviderKey } from './_lib/forge-provider-key.js';
import { validateForgeImage } from './_lib/forge-image-validate.js';
import { encodeJobToken, decodeJobToken } from './_lib/forge-job-token.js';
@@ -542,6 +547,48 @@ async function startJob(req, res) {
}
}
+ // Health-aware lane selection: when the caller didn't name a backend, consult a
+ // cheap, cached liveness snapshot of the free lanes and skip any our probe (or a
+ // recent submit failure) marks down — so a cold or unreachable self-host worker
+ // is routed AROUND before submit, not failed-over after. Only the platform free
+ // lanes (image/sketch) are candidates; geometry is BYOK and unaffected. Pure
+ // best-effort: any snapshot error leaves the env-resolved backendId in place, so
+ // a deployment with no telemetry behaves exactly as before. The snapshot is also
+ // reused below to decide an honest cold-start ETA without a second probe.
+ if (!backendExplicit && (path === 'image' || path === 'sketch')) {
+ try {
+ const candidates = freeLaneCandidates(path, tier.id, isImageMode);
+ if (candidates.length) {
+ const snap = await laneHealthSnapshot(candidates);
+ const healthAware = resolveBackendIdWithHealth({
+ path,
+ tier,
+ userImages: isImageMode,
+ health: snap.statusMap,
+ });
+ if (BACKENDS[healthAware]) backendId = healthAware;
+ }
+ } catch (err) {
+ console.warn(`[forge] lane-health routing skipped: ${err?.message || err}`);
+ }
+ }
+
+ // Honest cold-start signal for a chosen self-host lane: true only when the
+ // liveness probe reached the worker but it answered slowly (a scale-to-zero
+ // container spinning up). Reuses the cached snapshot, so the common path pays no
+ // extra probe. Used to widen the ETA + flag `cold_start` in the response — never
+ // to fabricate progress; the client's real polling still drives actual status.
+ const coldStartFor = async (id) => {
+ if (!isSelfHostBackend(id) || !coldStartSecondsFor(id)) return false;
+ try {
+ const snap = await laneHealthSnapshot([id]);
+ const rec = snap.byId[id];
+ return Boolean(rec && rec.status === 'ok' && rec.warm === false);
+ } catch {
+ return false;
+ }
+ };
+
// $THREE hold-to-access gate (Token Utility v1) — the High tier (200k poly +
// PBR, textured) is the platform's premium quality tier. It now runs on a
// free-for-us engine (HuggingFace Hunyuan3D) like every other tier, so this is
@@ -851,6 +898,22 @@ async function startJob(req, res) {
'Sketch-to-3D is not configured on this deployment (GCP_TRIPOSG_URL is not set).',
});
}
+ // The sketch model is conditioned on the drawing — no other lane can
+ // serve it, so there is nothing to fail over to. Cool the worker so the
+ // next request skips it while it recovers, and return a designed,
+ // retryable state instead of a raw provider error.
+ if (isUpstreamUnavailable(err)) {
+ await markLaneUnhealthy('triposg');
+ console.warn(`[forge] self-host sketch lane unavailable: ${err?.message || err}`);
+ res.setHeader('retry-after', '20');
+ return json(res, 503, {
+ error: 'generation_unavailable',
+ backend: backendId,
+ message:
+ 'The sketch-to-3D worker is warming up or briefly unavailable. Try again in a moment.',
+ retry_after: 20,
+ });
+ }
throw err;
}
@@ -873,6 +936,7 @@ async function startJob(req, res) {
path,
});
+ const sketchCold = await coldStartFor(backendId);
return json(res, 200, {
job_id: token,
creation_id: creationId,
@@ -884,7 +948,8 @@ async function startJob(req, res) {
prompt,
preview_image_url: sketchUrl,
reference_image_urls: [sketchUrl],
- eta_seconds: estimateEtaSeconds({ backendId, tier }),
+ cold_start: sketchCold,
+ eta_seconds: estimateEtaSeconds({ backendId, tier, cold: sketchCold }),
estimated_credits: estimateCredits({ backendId, path, tier }),
});
}
@@ -1175,6 +1240,7 @@ async function startJob(req, res) {
}
let job;
+ let selfHostTrellisFailed = false;
try {
job = await gcp.submit({
mode: 'trellis',
@@ -1190,44 +1256,78 @@ async function startJob(req, res) {
'Self-hosted TRELLIS is not configured on this deployment (MODEL_TRELLIS_URL is not set).',
});
}
- throw err;
+ // A genuine config/input fault surfaces as-is. An upstream blip (the
+ // worker is cold, restarting, throttled, or briefly unreachable) must
+ // not fail a request another lane can serve: cool this lane so the next
+ // request skips it, then fail over below to our other self-host worker
+ // (Hunyuan3D) or the standing reconstruct chain (which free-firsts to HF
+ // and only then the paid lane). We already hold the reference views, so
+ // the next lane reconstructs from exactly the same input.
+ if (!isUpstreamUnavailable(err)) throw err;
+ await markLaneUnhealthy('trellis_selfhost');
+ console.warn(
+ `[forge] self-host TRELLIS lane unavailable (${err?.providerStatus || err?.code}); failing over to the next image lane`,
+ );
+ selfHostTrellisFailed = true;
}
- // Wrap the gcp job envelope in a forge token so polling routes back to the
- // gcp provider -- same idiom as the sketch and Hunyuan3D lanes.
- const token = encodeJobToken({ provider: 'gcp', kind: null, taskId: job.extJobId });
- const clientKey = clientKeyFrom(req);
- const creationId = await createCreation({
- clientKey,
- ipHash: hashIp(ip),
- prompt: prompt || (isImageMode ? 'image-to-3d' : ''),
- aspect: isImageMode ? null : aspect,
- previewImageUrl: referenceImageUrl,
- replicateJobId: job.extJobId,
- textToImageModel: isImageMode ? null : textToImageModel,
- viewsRequested: views.length,
- viewsUsed: job.viewsUsed ?? views.length,
- multiview: views.length > 1,
- backend: backendId,
- tier: tier.id,
- path,
- });
+ if (!selfHostTrellisFailed) {
+ // Wrap the gcp job envelope in a forge token so polling routes back to the
+ // gcp provider -- same idiom as the sketch and Hunyuan3D lanes.
+ const token = encodeJobToken({ provider: 'gcp', kind: null, taskId: job.extJobId });
+ const clientKey = clientKeyFrom(req);
+ const creationId = await createCreation({
+ clientKey,
+ ipHash: hashIp(ip),
+ prompt: prompt || (isImageMode ? 'image-to-3d' : ''),
+ aspect: isImageMode ? null : aspect,
+ previewImageUrl: referenceImageUrl,
+ replicateJobId: job.extJobId,
+ textToImageModel: isImageMode ? null : textToImageModel,
+ viewsRequested: views.length,
+ viewsUsed: job.viewsUsed ?? views.length,
+ multiview: views.length > 1,
+ backend: backendId,
+ tier: tier.id,
+ path,
+ });
- return json(res, 200, {
- job_id: token,
- creation_id: creationId,
- status: 'queued',
- mode: isImageMode ? 'image_to_3d' : 'text_to_3d',
- path,
- tier: tier.id,
- backend: backendId,
- prompt: prompt || null,
- preview_image_url: referenceImageUrl,
- reference_image_urls: isImageMode ? [imageUrls[0]] : [referenceImageUrl],
- text_to_image_model: isImageMode ? null : textToImageModel,
- eta_seconds: estimateEtaSeconds({ backendId, tier }),
- estimated_credits: estimateCredits({ backendId, path, tier }),
- });
+ const cold = await coldStartFor(backendId);
+ return json(res, 200, {
+ job_id: token,
+ creation_id: creationId,
+ status: 'queued',
+ mode: isImageMode ? 'image_to_3d' : 'text_to_3d',
+ path,
+ tier: tier.id,
+ backend: backendId,
+ prompt: prompt || null,
+ preview_image_url: referenceImageUrl,
+ reference_image_urls: isImageMode ? [imageUrls[0]] : [referenceImageUrl],
+ text_to_image_model: isImageMode ? null : textToImageModel,
+ cold_start: cold,
+ eta_seconds: estimateEtaSeconds({ backendId, tier, cold }),
+ estimated_credits: estimateCredits({ backendId, path, tier }),
+ });
+ }
+
+ // Fail over from the down self-host TRELLIS worker. Prefer our other
+ // self-host GPU lane (Hunyuan3D) when it's wired; otherwise hand off to the
+ // standing reconstruct chain (backend 'trellis'), which free-firsts to the
+ // HuggingFace Spaces lane and only then the paid Replicate account. Falls
+ // through (no return) into the lane blocks below; provenance reports the
+ // lane that actually runs, so the failover is never silent.
+ if (process.env.GCP_HUNYUAN3D_URL && process.env.GCP_RECONSTRUCTION_KEY) {
+ backendId = 'hunyuan3d';
+ provider = createGcpProvider({ reconstructUrl: process.env.GCP_HUNYUAN3D_URL });
+ } else {
+ backendId = 'trellis';
+ try {
+ provider = createRegenProvider();
+ } catch {
+ provider = undefined;
+ }
+ }
}
if (backendId === 'huggingface') {
@@ -1296,6 +1396,17 @@ async function startJob(req, res) {
let job;
try {
+ // A self-host failover landed here with no paid provider configured (no
+ // REPLICATE_API_TOKEN) and the free HF lane above didn't serve the request
+ // — there is no reconstruct lane left. Raise it as upstream-unavailable so
+ // the catch below runs the remaining free fallbacks (Hunyuan3D → HF) and,
+ // if those are gone too, surfaces a designed unavailable state.
+ if (!provider) {
+ throw Object.assign(new Error('no reconstruct lane configured'), {
+ code: 'provider_unreachable',
+ status: 502,
+ });
+ }
// Per-provider submit throttle: shed platform Replicate bursts to the free
// lane BEFORE they hit the account quota and turn into fleet-wide 429s. Only
// the platform-keyed default lane is capped — BYOK lanes spend the caller's
@@ -1431,6 +1542,10 @@ async function startJob(req, res) {
// GPU pipeline. First writer wins; best-effort (no-op without Redis).
await registerInFlight(requestHash, jobHandle);
+ // Honest cold-start: only a self-host worker reached cold widens the ETA
+ // (a paid/external lane returns false). Covers the Hunyuan3D self-host
+ // fallback this block serves after a self-host TRELLIS failover.
+ const cold = await coldStartFor(backendId);
return json(res, 200, {
job_id: jobHandle,
creation_id: creationId,
@@ -1446,7 +1561,8 @@ async function startJob(req, res) {
views_used: viewsUsed,
multiview,
text_to_image_model: textToImageModel,
- eta_seconds: estimateEtaSeconds({ backendId, tier }),
+ cold_start: cold,
+ eta_seconds: estimateEtaSeconds({ backendId, tier, cold }),
estimated_credits: estimateCredits({ backendId, path, tier }),
});
} catch (err) {
diff --git a/api/x402/crypto-intel.js b/api/x402/crypto-intel.js
index 0e31dbdd5..b665cdf8e 100644
--- a/api/x402/crypto-intel.js
+++ b/api/x402/crypto-intel.js
@@ -33,7 +33,7 @@ const INPUT_SCHEMA = {
properties: {
topic: {
type: 'string',
- description: 'Token ticker or CoinGecko id: btc, sol, eth, doge, …',
+ description: 'Token ticker or CoinGecko id: btc, sol, eth, xrp, …',
default: 'sol',
},
},
diff --git a/docs/roadmap/_generated/02/gate-before.txt b/docs/roadmap/_generated/02/gate-before.txt
index 0e210b4e3..d21c825a1 100644
--- a/docs/roadmap/_generated/02/gate-before.txt
+++ b/docs/roadmap/_generated/02/gate-before.txt
@@ -28,3 +28,5 @@ stderr | tests/auto-rig-completion.test.js > 6a — cron recovers an open job fr
× issues a MeterUsage command with the product code, dimension, and idempotency allocation 2255ms
❯ tests/build-asset-paths.test.js (5 tests | 1 failed) 56ms
× serves /style.css from dist root 53ms
+ ❯ tests/api/agent-memory.test.js (22 tests | 1 failed) 148ms
+ × truncates content longer than 10,000 characters 18ms
diff --git a/docs/roadmap/_generated/03/gate-before.txt b/docs/roadmap/_generated/03/gate-before.txt
index c3e1c7573..5e34d529f 100644
--- a/docs/roadmap/_generated/03/gate-before.txt
+++ b/docs/roadmap/_generated/03/gate-before.txt
@@ -28,3 +28,5 @@ stderr | tests/auto-rig-completion.test.js > 6a — cron recovers an open job fr
× issues a MeterUsage command with the product code, dimension, and idempotency allocation 2515ms
❯ tests/build-asset-paths.test.js (5 tests | 1 failed) 71ms
× serves /style.css from dist root 49ms
+ ❯ tests/api/agent-memory.test.js (22 tests | 1 failed) 201ms
+ × truncates content longer than 10,000 characters 52ms
diff --git a/docs/roadmap/_generated/04/gate-before.txt b/docs/roadmap/_generated/04/gate-before.txt
index fe6e2cd9f..b568cb661 100644
--- a/docs/roadmap/_generated/04/gate-before.txt
+++ b/docs/roadmap/_generated/04/gate-before.txt
@@ -13,3 +13,47 @@ EXIT:0
RUN v4.1.7 /workspaces/three.ws
+
+ Test Files 7 passed (7)
+ Tests 79 passed (79)
+ Start at 22:23:19
+ Duration 174.24s (transform 21.71s, setup 0ms, import 246.15s, tests 2.59s, environment 1ms)
+
+[test-gate] ✓ all critical-path tests passed
+EXIT:0
+=== audit:routes ===
+
+> [email protected] audit:routes
+> node scripts/verify-routes.mjs
+
+Route verify — 231 catalog pages, 908 main routes, 1 post-filesystem routes.
+ modeled dist files: 1431 · canonical-covered: 231 · literal page routes checked for shadows: 377
+ filesystem boundary (handle:filesystem) present: yes
+
+✓ static checks pass: every catalog page reachable, unknown paths → designed 404, no shadowed page routes.
+EXIT:0
+=== audit:handlers ===
+
+> [email protected] audit:handlers
+> node scripts/audit-empty-handlers.mjs
+
+✓ audit-empty-handlers: all API handlers export a body (1186 checked)
+EXIT:0
+=== audit:mcp ===
+
+> [email protected] audit:mcp
+> node scripts/audit-mcp-manifests.mjs
+
+[audit:mcp] server-studio.json: description is 186 chars (registry max is 100)
+[audit:mcp] 1 violation(s) across 15 manifests
+EXIT:1
+=== audit:pages ===
+
+> [email protected] audit:pages
+> node scripts/audit-page-index.mjs
+
+Route audit: 122 auditable page routes, 231 documented in pages.json.
+✓ Every auditable page route is documented.
+
+ℹ 5 manifest page(s) have no `added` date (omitted from /changelog). Fine for legacy pages; add dates as you touch them.
+EXIT:0
diff --git a/docs/roadmap/_generated/07/gate-before.txt b/docs/roadmap/_generated/07/gate-before.txt
index 2f39b5242..3c5d69569 100644
--- a/docs/roadmap/_generated/07/gate-before.txt
+++ b/docs/roadmap/_generated/07/gate-before.txt
@@ -30,3 +30,11 @@ Route verify — 231 catalog pages, 908 main routes, 1 post-filesystem routes.
> [email protected] audit:handlers
> node scripts/audit-empty-handlers.mjs
+✓ audit-empty-handlers: all API handlers export a body (1185 checked)
+
+> [email protected] audit:mcp
+> node scripts/audit-mcp-manifests.mjs
+
+[audit:mcp] server-studio.json: description is 186 chars (registry max is 100)
+[audit:mcp] 1 violation(s) across 15 manifests
+EXIT:1
diff --git a/marketplace/plugins/three-ws-3d/.claude-plugin/plugin.json b/marketplace/plugins/three-ws-3d/.claude-plugin/plugin.json
new file mode 100644
index 000000000..bafec913b
--- /dev/null
+++ b/marketplace/plugins/three-ws-3d/.claude-plugin/plugin.json
@@ -0,0 +1,49 @@
+{
+ "name": "three-ws-3d",
+ "description": "three.ws 3D Forge — generate textured 3D models and rigged, animation-ready avatars from text or images. Free text→3D (NVIDIA NIM / TRELLIS) plus the paid mesh, avatar, and auto-rig lanes, scene composition, and live avatar embeds, all wired over the three.ws MCP servers.",
+ "version": "1.0.0",
+ "author": {
+ "name": "nirholas"
+ },
+ "homepage": "https://three.ws/forge",
+ "license": "Apache-2.0",
+ "repository": "https://github.com/nirholas/three.ws",
+ "keywords": [
+ "3d",
+ "forge",
+ "avatar",
+ "glb",
+ "text-to-3d",
+ "image-to-3d",
+ "rigging",
+ "trellis",
+ "mcp"
+ ],
+ "category": "creative",
+ "mcpServers": {
+ "3d-agent": {
+ "command": "npx",
+ "args": [
+ "-y",
+ "@three-ws/mcp-server"
+ ],
+ "env": {
+ "MCP_SVM_PAYMENT_ADDRESS": "${MCP_SVM_PAYMENT_ADDRESS}"
+ }
+ },
+ "scene": {
+ "command": "npx",
+ "args": [
+ "-y",
+ "@three-ws/scene-mcp"
+ ]
+ },
+ "avatar": {
+ "command": "npx",
+ "args": [
+ "-y",
+ "@three-ws/avatar-mcp"
+ ]
+ }
+ }
+}
diff --git a/marketplace/plugins/three-ws-3d/skills/auto-rig/SKILL.md b/marketplace/plugins/three-ws-3d/skills/auto-rig/SKILL.md
new file mode 100644
index 000000000..73c942e45
--- /dev/null
+++ b/marketplace/plugins/three-ws-3d/skills/auto-rig/SKILL.md
@@ -0,0 +1,53 @@
+---
+name: auto-rig
+description: Make a 3D model animation-ready — add a humanoid skeleton and skin weights to an existing GLB, or generate a rigged avatar from text/images in one call. Use when you or the user want to rig a mesh, auto-rig a GLB, make a model animatable, get a character that plays idle/walk animations, or go from prompt straight to a rigged avatar. Covers "rig this GLB", "make it animatable", "text to rigged avatar". Paid lane ($0.20 / $0.45 USDC via x402).
+---
+
+# Auto-Rig — skeleton + skin weights for animation
+
+Two paths, depending on whether you already have a mesh.
+
+## Tools
+
+Both on the three.ws MCP server (`@three-ws/mcp-server`).
+
+### `rig_mesh` — rig an existing GLB ($0.20 USDC)
+
+Auto-rig a static GLB: adds a humanoid skeleton and per-vertex skin weights via the three.ws rig pipeline (VAST-AI UniRig by default).
+
+| Param | Required | Notes |
+| --- | --- | --- |
+| `glb_url` | yes | http(s) URL to the static GLB to rig — e.g. the `glbUrl` returned by `forge-3d` (`forge_free`), `mesh-forge`, or `text-to-avatar`. |
+
+Returns the **rigged** `glbUrl` and a three.ws pose-studio link (`https://three.ws/forge?action=rig...`) where the model plays the canonical idle/walk clip library.
+
+### `forge_avatar` — text/image → rigged avatar in one call ($0.45 USDC)
+
+Chains the whole pipeline: Granite prompt director → FLUX + TRELLIS/Hunyuan3D mesh → UniRig auto-rig, so the model loads straight into the pose studio.
+
+| Param | Required | Notes |
+| --- | --- | --- |
+| `prompt` | one of prompt/images | A single humanoid character, e.g. `"a friendly cartoon astronaut in a glossy white suit"`. |
+| `image_url` / `image_urls` | one of prompt/images | Single image, or 1–4 angles (front/back/left/right) for higher-fidelity reconstruction. |
+| `direct` | no | Run the Granite prompt-director stage (text mode). Default `true`. |
+| `aspect_ratio` | no | Reference aspect ratio (text mode). Default `3:4` (portrait — best for a full-body figure). |
+| `allow_non_humanoid` | no | Off by default. A clearly non-humanoid subject (furniture, vehicle, quadruped) is **rejected without charge**. Set `true` only to force-rig a non-character. |
+
+Returns the rigged `glbUrl`, the intermediate mesh URL, a pose-studio link, the directed prompt, and per-stage timing. **You are not charged if no rigged avatar is produced.**
+
+## Which to use
+
+- Already have a GLB (from `forge-3d`, `mesh-forge`, `text-to-avatar`, or the user's own file) → `rig_mesh` ($0.20).
+- Starting from just a prompt or photos and want it rigged → `forge_avatar` ($0.45, generation + rig bundled).
+
+## How to run
+
+1. Pick the tool by whether a GLB already exists.
+2. Call it. Both are PAID over x402 — on a `PaymentRequired` result, surface the price and funding path; do not retry blindly.
+3. For `forge_avatar`, if the humanoid gate rejects a non-character prompt (no charge), suggest `mesh-forge` or `forge-3d` for that object instead.
+4. Return the rigged `glbUrl` and the pose-studio link so the user can preview the idle/walk animation.
+
+## Notes
+
+- Rigged output drives the three.ws canonical clip library — any humanoid skeleton is retargeted (no curated rig allowlist).
+- x402 settlement is in USDC; `$THREE` is the platform's only token.
diff --git a/marketplace/plugins/three-ws-3d/skills/forge-3d/SKILL.md b/marketplace/plugins/three-ws-3d/skills/forge-3d/SKILL.md
new file mode 100644
index 000000000..88dfcc8c1
--- /dev/null
+++ b/marketplace/plugins/three-ws-3d/skills/forge-3d/SKILL.md
@@ -0,0 +1,43 @@
+---
+name: forge-3d
+description: Generate a textured 3D GLB model from a text prompt for FREE — no payment, API key, or wallet. Use when you or the user want to make a 3D model, mesh, object, prop, or character from a description, draft a 3D asset, or get a downloadable GLB from text. Covers "make a 3D model of...", "forge a mesh", "text to 3D", "generate a GLB".
+---
+
+# Forge 3D — free text → 3D
+
+Turn a sentence into a textured, downloadable 3D model at zero cost. This is the same free engine the [three.ws/forge](https://three.ws/forge) web page uses for prompt drafts.
+
+## Tool
+
+`forge_free` (three.ws MCP server, `@three-ws/mcp-server`).
+
+- **Lane:** FREE. No x402 payment, no API key, no wallet, no `$THREE` required.
+- **Backend:** the three.ws `POST /api/forge` pipeline on the free NVIDIA NIM lane (Microsoft TRELLIS text→3D preview).
+- **Mode:** text only. NVIDIA's hosted TRELLIS preview does not accept uploaded photos — for image or multi-view → 3D, use the `mesh-forge` skill instead.
+
+## Inputs
+
+| Param | Required | Notes |
+| --- | --- | --- |
+| `prompt` | yes | 3–1000 chars. Describe one object or character. TRELLIS conditions on ~77 characters, so lead with the subject plus its key materials and colors, e.g. `"a friendly round robot mascot, glossy white plastic"`. |
+| `tier` | no | `draft` (fast, default), `standard` (balanced), or `high` (densest mesh). All three are free — higher tiers only cost more time. |
+
+## Outputs
+
+The tool returns:
+
+- `glbUrl` — a durable URL to the generated `.glb` file (download or load directly into any glTF viewer / Three.js scene).
+- `viewerUrl` — a three.ws viewer link, `https://three.ws/viewer?src=<glbUrl>`, that renders the model in the browser.
+- the quality `tier` used and the backend that produced it.
+
+## How to run
+
+1. Read the user's description. Pick `tier` (`draft` unless they ask for higher fidelity).
+2. Call `forge_free` with `{ prompt, tier }`.
+3. Return the `glbUrl` (for download) and the `viewerUrl` (clickable preview) to the user. Mention the tier used.
+4. To make the result animation-ready, feed `glbUrl` to the `auto-rig` skill (`rig_mesh`).
+
+## Notes
+
+- One object/character per prompt produces the cleanest mesh. For a full scene of multiple placed objects, use the `scene` server's `compose_scene` instead.
+- Free tier is real generation, not a placeholder — generation takes from a few seconds (`draft`) up to a couple of minutes (`high`). Report the wait honestly; never fake progress.
diff --git a/marketplace/plugins/three-ws-3d/skills/mesh-forge/SKILL.md b/marketplace/plugins/three-ws-3d/skills/mesh-forge/SKILL.md
new file mode 100644
index 000000000..23254fc4f
--- /dev/null
+++ b/marketplace/plugins/three-ws-3d/skills/mesh-forge/SKILL.md
@@ -0,0 +1,45 @@
+---
+name: mesh-forge
+description: Generate a high-fidelity textured 3D GLB from a text prompt, a single reference image, or 2–4 multi-view photos of the same object. Use when you or the user want image-to-3D, multi-view reconstruction, a Granite-directed text-to-3D mesh, or a higher-quality mesh than the free draft lane. Covers "image to 3D", "reconstruct this object", "make a 3D model from these photos". Paid lane ($0.25 USDC via x402).
+---
+
+# Mesh Forge — directed text/image/multi-view → 3D
+
+The full-fidelity mesh lane: a chain of specialist models (IBM Granite prompt director → FLUX reference render → Microsoft TRELLIS / Tencent Hunyuan3D reconstruction), or direct reconstruction from your own photos.
+
+## Tool
+
+`mesh_forge` (three.ws MCP server, `@three-ws/mcp-server`).
+
+- **Lane:** PAID — **$0.25 USDC** per call over x402. Returns `PaymentRequired` if no payment payload is attached.
+- **Modes:**
+ - **Text:** Granite rewrites your prompt into an optimized 3D spec, FLUX renders a reference, TRELLIS/Hunyuan3D build the mesh.
+ - **Image:** pass `image_url` to reconstruct a single reference image directly (prompt-director + text-to-image stages skipped).
+ - **Multi-view:** pass `image_urls` (1–4 angles, e.g. front/back/left/right) and the backend fuses them — no hallucinated back of the object.
+
+## Inputs
+
+| Param | Required | Notes |
+| --- | --- | --- |
+| `prompt` | text mode | 3–1000 chars describing one object, e.g. `"a worn leather armchair"`. Optional when an image is supplied (then used as guidance). |
+| `image_url` | image mode | http(s) URL to a single reference image. |
+| `image_urls` | multi-view | 1–4 http(s) URLs of the same object from different angles. Takes precedence over `image_url`. |
+| `direct` | no | Run the Granite prompt-director stage (text mode). Default `true`. |
+| `aspect_ratio` | no | Reference image aspect ratio for text mode: `1:1` (default), `4:3`, `3:4`, `16:9`, `9:16`. |
+
+## Outputs
+
+- `glbUrl` — the generated mesh `.glb`.
+- `viewerUrl` — `https://three.ws/viewer?src=<glbUrl>`.
+- how many views were fused, which backend handled it, the directed prompt (text mode), and timing.
+
+## How to run
+
+1. Choose the mode from the user's input (text / single image / multi-view). Prefer multi-view when several angles of one object are available — it gives the cleanest geometry.
+2. Call `mesh_forge`. On `PaymentRequired`, surface the $0.25 USDC price and funding path rather than retrying.
+3. Return `glbUrl` + `viewerUrl`. Feed `glbUrl` to `auto-rig` (`rig_mesh`) for an animation-ready model.
+
+## Notes
+
+- For a free, text-only draft, use `forge-3d` (`forge_free`) instead — no payment.
+- One object per call. For multi-object placed scenes, use the `scene` server's `compose_scene`.
diff --git a/marketplace/plugins/three-ws-3d/skills/text-to-avatar/SKILL.md b/marketplace/plugins/three-ws-3d/skills/text-to-avatar/SKILL.md
new file mode 100644
index 000000000..269bfcb83
--- /dev/null
+++ b/marketplace/plugins/three-ws-3d/skills/text-to-avatar/SKILL.md
@@ -0,0 +1,47 @@
+---
+name: text-to-avatar
+description: Generate a textured 3D GLB avatar from a text prompt or reference image(s). Use when you or the user want an avatar, a 3D character, a person/figure model, or image-to-3D reconstruction of a character. Covers "make me an avatar", "turn this photo into a 3D character", "generate a 3D person". Paid lane ($0.15 USDC via x402).
+---
+
+# Text → Avatar
+
+Generate a high-quality textured 3D avatar from a description or one to four reference photos.
+
+## Tool
+
+`text_to_avatar` (three.ws MCP server, `@three-ws/mcp-server`).
+
+- **Lane:** PAID — **$0.15 USDC** per call, settled automatically over x402. Requires a funded wallet on the MCP transport (the `MCP_SVM_PAYMENT_ADDRESS` the plugin wires). If no payment payload is attached, the tool returns a `PaymentRequired` structured result describing what to pay.
+- **Backend:** Replicate (Hunyuan-3D 3.1 by default), polled synchronously until a GLB is produced or the timeout fires.
+
+## When to use this vs. the alternatives
+
+- **Free draft, text only:** use `forge-3d` (`forge_free`) — no payment.
+- **Static avatar, prompt or photo, best texture:** this skill (`text_to_avatar`).
+- **One-call rigged avatar ready to animate:** use `auto-rig` (`forge_avatar`) — it generates *and* rigs in a single call.
+
+## Inputs
+
+| Param | Required | Notes |
+| --- | --- | --- |
+| `prompt` | one of prompt/images | Natural-language description of the avatar (≤1000 chars). |
+| `images` | one of prompt/images | 1–4 reference image URLs. When provided, the model does image-to-3D reconstruction. |
+| `texture` | no | Request PBR textures when supported (default `true`). |
+| `seed` | no | Integer seed for reproducible output. |
+
+## Outputs
+
+- `glbUrl` — the generated avatar `.glb`.
+- the source prompt/images, the picked model version, the Replicate prediction id, and timing metadata.
+- Render or share it live with the `avatar` server's inline-render / embed-iframe tools, or open `https://three.ws/viewer?src=<glbUrl>`.
+
+## How to run
+
+1. Decide text vs image mode from the user's request. Gather `prompt` and/or `images` (public http(s) URLs).
+2. Call `text_to_avatar`. If it returns `PaymentRequired`, surface the price ($0.15 USDC) and how to fund — do not retry blindly.
+3. Return `glbUrl` plus a viewer/embed link. Offer to rig it (`auto-rig` → `rig_mesh`) so it can play the canonical idle/walk animations.
+
+## Notes
+
+- The result is a static mesh. Rigging is a separate step (`rig_mesh`) — or use `forge_avatar` to generate-and-rig in one call.
+- The only token this platform uses for payment accounting is `$THREE`; the x402 settlement itself is in USDC.
diff --git a/marketplace/plugins/three-ws-developer/.claude-plugin/plugin.json b/marketplace/plugins/three-ws-developer/.claude-plugin/plugin.json
index 32d0878c8..cc9bc9f1d 100644
--- a/marketplace/plugins/three-ws-developer/.claude-plugin/plugin.json
+++ b/marketplace/plugins/three-ws-developer/.claude-plugin/plugin.json
@@ -19,5 +19,13 @@
}
}
},
- "repository": "https://github.com/nirholas/three.ws"
+ "repository": "https://github.com/nirholas/three.ws",
+ "keywords": [
+ "developer",
+ "scaffold",
+ "mcp",
+ "tools",
+ "agent"
+ ],
+ "category": "developer-tools"
}
diff --git a/mcp-server/src/lib/agent-registry.js b/mcp-server/src/lib/agent-registry.js
new file mode 100644
index 000000000..e67d7121c
--- /dev/null
+++ b/mcp-server/src/lib/agent-registry.js
@@ -0,0 +1,214 @@
+// three.ws agent-registry read client used by the commerce discovery tool.
+//
+// Reads the live public agent directory (GET /api/agents/public) — real agents,
+// real skills, real engagement counts — and exposes a ranking helper that folds
+// task/skill fit, engagement, and (when present) on-chain ERC-8004 reputation
+// into a single fitness score. No mock data: every candidate comes from the
+// live directory; reputation is read straight from the canonical registries.
+
+import { resilientFetch } from './resilient-fetch.js';
+import { makeEvmProvider } from './evm-rpc.js';
+import { readReputationAggregate, resolveChain } from './erc8004.js';
+
+function baseUrl() {
+ const v = process.env.THREEWS_BASE_URL;
+ return v && v.trim() ? v.trim().replace(/\/+$/, '') : 'https://three.ws';
+}
+
+/**
+ * Fetch candidate agents from the live three.ws public directory.
+ *
+ * @param {object} opts
+ * @param {string} [opts.q] — full-text query (task keywords)
+ * @param {string} [opts.skill] — skill-slug filter
+ * @param {number} [opts.limit] — max rows (clamped 1..48)
+ * @returns {Promise<object[]>} raw agent rows from /api/agents/public
+ */
+export async function fetchCandidates({ q, skill, limit = 24 } = {}) {
+ const url = new URL(`${baseUrl()}/api/agents/public`);
+ if (q) url.searchParams.set('q', String(q).slice(0, 100));
+ if (skill) url.searchParams.set('skill', String(skill).toLowerCase());
+ url.searchParams.set('limit', String(Math.min(48, Math.max(1, limit))));
+ url.searchParams.set('sort', 'popular');
+
+ const res = await resilientFetch(
+ url.toString(),
+ { headers: { accept: 'application/json' } },
+ { timeoutMs: 12_000, retries: 2, label: 'agent-registry' },
+ );
+ if (!res.ok) {
+ throw new Error(`agent directory returned ${res.status}`);
+ }
+ const data = await res.json().catch(() => null);
+ const agents = Array.isArray(data?.agents) ? data.agents : [];
+ return agents;
+}
+
+// Token-overlap relevance between the task text and an agent's name + skills +
+// description. Cheap, deterministic, and good enough to order a shortlist; the
+// registry's full-text search already did the heavy filtering.
+function relevanceScore(task, agent) {
+ const taskTokens = tokenize(task);
+ if (taskTokens.size === 0) return 0;
+ const hay = tokenize(
+ [agent.name, agent.description, ...(Array.isArray(agent.skills) ? agent.skills : [])]
+ .filter(Boolean)
+ .join(' '),
+ );
+ if (hay.size === 0) return 0;
+ let hits = 0;
+ for (const t of taskTokens) if (hay.has(t)) hits += 1;
+ return hits / taskTokens.size;
+}
+
+function tokenize(s) {
+ return new Set(
+ String(s || '')
+ .toLowerCase()
+ .split(/[^a-z0-9]+/)
+ .filter((w) => w.length > 2),
+ );
+}
+
+// Squash an unbounded engagement count into 0..1 so it can't dominate the
+// composite score. log10 keeps a 10× busier agent meaningfully — but not
+// linearly — ahead.
+function engagementScore(chatCount) {
+ const n = Number(chatCount) || 0;
+ if (n <= 0) return 0;
+ return Math.min(1, Math.log10(n + 1) / 4); // ~10k chats → 1.0
+}
+
+/**
+ * Read live ERC-8004 reputation for one agent that exposes an on-chain identity.
+ * Returns null when the agent has no erc8004 id or the read fails (reputation is
+ * enrichment — a single RPC blip must never sink the whole discovery call).
+ *
+ * @param {object} agent — directory row (may carry erc8004_agent_id + chain_id)
+ * @returns {Promise<{average:number|null, count:number, source:string, chain:string, erc8004AgentId:string}|null>}
+ */
+export async function readAgentReputation(agent) {
+ const erc8004Id = agent?.erc8004_agent_id;
+ if (erc8004Id == null || String(erc8004Id).trim() === '') return null;
+ let chain;
+ try {
+ chain = resolveChain(agent.chain_id ?? agent.chainId ?? undefined);
+ } catch {
+ chain = resolveChain(undefined);
+ }
+ try {
+ const overrides = [process.env[`MCP_AGENT_REP_RPC_${chain.id}`]].filter(Boolean);
+ const provider = makeEvmProvider(chain.id, { overrides, timeoutMs: 8_000 });
+ const agg = await readReputationAggregate(provider, BigInt(String(erc8004Id)));
+ return {
+ average: agg.average,
+ count: Number(agg.count) || 0,
+ averageX100: agg.averageX100,
+ totalStakeWei: agg.totalStakeWei,
+ source: 'erc8004',
+ chain: chain.name,
+ chainId: chain.id,
+ erc8004AgentId: String(erc8004Id),
+ };
+ } catch {
+ return null;
+ }
+}
+
+// Map an ERC-8004 average (the registry scores feedback −100..+100, stored ÷100
+// so the average lands in roughly −1..+1 for normalized feedback, but can range
+// wider) into a 0..1 reputation factor for the composite. Unrated agents get a
+// neutral baseline so they're not auto-buried — discovery still surfaces them,
+// just below comparably-fit rated peers.
+function reputationFactor(reputation) {
+ if (!reputation || reputation.average == null || reputation.count <= 0) return 0.5;
+ // Clamp the average into [-1, 1] then shift to [0, 1].
+ const clamped = Math.max(-1, Math.min(1, reputation.average));
+ return (clamped + 1) / 2;
+}
+
+/**
+ * Rank candidate agents for a task, enriching each with live reputation, and
+ * return a sorted shortlist with the evidence behind each score.
+ *
+ * Composite weighting (sums to 1): relevance .45, reputation .35, engagement .20.
+ * Reputation is read in parallel and bounded; failures degrade to a neutral
+ * factor rather than dropping the candidate.
+ *
+ * @param {object} opts
+ * @param {string} opts.task
+ * @param {object[]} opts.candidates — rows from fetchCandidates()
+ * @param {number} [opts.limit=5]
+ * @param {number} [opts.minReputation] — drop rated agents below this average
+ * @returns {Promise<object[]>}
+ */
+export async function rankCandidates({ task, candidates, limit = 5, minReputation } = {}) {
+ const rows = Array.isArray(candidates) ? candidates : [];
+
+ // Read reputation for every candidate concurrently (bounded inside
+ // readAgentReputation). Promise.all is safe — each resolves to a value or
+ // null, never rejects.
+ const reputations = await Promise.all(rows.map((a) => readAgentReputation(a)));
+
+ const scored = rows.map((agent, i) => {
+ const reputation = reputations[i];
+ const relevance = relevanceScore(task, agent);
+ const engagement = engagementScore(agent.chat_count);
+ const repFactor = reputationFactor(reputation);
+ const score = 0.45 * relevance + 0.35 * repFactor + 0.2 * engagement;
+ return {
+ agentId: agent.id,
+ name: agent.name,
+ description: agent.description || null,
+ skills: Array.isArray(agent.skills) ? agent.skills : [],
+ homeUrl: agent.home_url || null,
+ avatarThumbnail: agent.avatar_thumbnail || null,
+ isRegistered: !!agent.is_registered,
+ reputation: reputation
+ ? {
+ average: reputation.average,
+ count: reputation.count,
+ source: reputation.source,
+ chain: reputation.chain,
+ erc8004AgentId: reputation.erc8004AgentId,
+ }
+ : null,
+ capabilityMatch: Math.round(relevance * 100) / 100,
+ engagement: { chatCount: Number(agent.chat_count) || 0, score: Math.round(engagement * 100) / 100 },
+ score: Math.round(score * 1000) / 1000,
+ evidence: buildEvidence({ relevance, reputation, engagement, agent }),
+ };
+ });
+
+ const gated =
+ Number.isFinite(minReputation) && minReputation != null
+ ? scored.filter(
+ (c) =>
+ // Keep unrated agents (no on-chain rep to gate on) and rated
+ // agents that clear the floor.
+ c.reputation == null ||
+ c.reputation.average == null ||
+ c.reputation.average >= minReputation,
+ )
+ : scored;
+
+ gated.sort((a, b) => b.score - a.score);
+ return gated.slice(0, Math.max(1, Math.min(10, limit)));
+}
+
+function buildEvidence({ relevance, reputation, engagement, agent }) {
+ const parts = [];
+ if (reputation && reputation.average != null && reputation.count > 0) {
+ parts.push(
+ `ERC-8004 reputation ${reputation.average.toFixed(2)} across ${reputation.count} vouch(es) on ${reputation.chain}`,
+ );
+ } else if (reputation) {
+ parts.push(`on-chain ERC-8004 identity #${reputation.erc8004AgentId} (no vouches yet)`);
+ } else {
+ parts.push('no on-chain reputation record');
+ }
+ parts.push(`task fit ${(relevance * 100).toFixed(0)}%`);
+ const chats = Number(agent.chat_count) || 0;
+ if (chats > 0) parts.push(`${chats.toLocaleString('en-US')} chats served`);
+ return parts.join(' · ');
+}
diff --git a/mcp-server/src/tools/_humanoid.js b/mcp-server/src/tools/_humanoid.js
index e2479314e..dde7b579f 100644
--- a/mcp-server/src/tools/_humanoid.js
+++ b/mcp-server/src/tools/_humanoid.js
@@ -413,6 +413,17 @@ export function classifyHumanoidPrompt(prompt) {
};
}
+ // Pure punctuation/digits ("!!!", "12345") name no subject at all, so the
+ // "proceed on ambiguity" default below must not apply — there is nothing to rig.
+ if (!/[a-z]/.test(text)) {
+ return {
+ humanoid: false,
+ confidence: 'low',
+ reason: 'prompt has no descriptive words to identify a character',
+ signals: { humanoid: [], nonHumanoid: [] },
+ };
+ }
+
const pos = countMatches(text, HUMANOID_TERMS);
const neg = countMatches(text, NON_HUMANOID_TERMS);
const signals = { humanoid: pos.hits, nonHumanoid: neg.hits };
diff --git a/mcp-server/src/tools/_studio-core.js b/mcp-server/src/tools/_studio-core.js
index b3f265e2c..4f937aaff 100644
--- a/mcp-server/src/tools/_studio-core.js
+++ b/mcp-server/src/tools/_studio-core.js
@@ -49,6 +49,25 @@ const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
const VALID_TIER = new Set(['draft', 'standard', 'high']);
const VALID_ASPECT = new Set(['1:1', '4:3', '3:4', '16:9', '9:16']);
+// Probe that a generated asset URL is actually fetchable before returning it as
+// a success: a degraded lane can hand back an already-expired temp URL, and a
+// 404 link reads as breakage downstream. A 1-byte ranged GET is used because
+// gradio file routes frequently reject HEAD. Best-effort — any error counts as
+// unreachable.
+async function isUrlReachable(url) {
+ if (!url) return false;
+ try {
+ const r = await fetch(url, {
+ method: 'GET',
+ headers: { range: 'bytes=0-0' },
+ signal: AbortSignal.timeout(15_000),
+ });
+ return r.ok || r.status === 206;
+ } catch {
+ return false;
+ }
+}
+
// ---------------------------------------------------------------------------
// /api/forge client — submit + poll, shared by forge_free / mesh_forge /
// forge_avatar. The three callers differ only in: which backend/path they pin,
@@ -256,57 +275,118 @@ export async function runForgeFree({ prompt, tier }) {
const tierId = VALID_TIER.has(tier) ? tier : 'draft';
const base = apiBaseFrom(['FORGE_FREE_API_BASE']);
const startedAt = Date.now();
+ // The free lane's happy path is the durable NVIDIA NIM (R2-persisted) result.
+ // When NIM is cold it degrades to a HuggingFace Space whose gradio /tmp URL
+ // expires within seconds — a non-durable result that can be DEAD on arrival.
+ // Prefer a durable result via a bounded retry, verify any non-durable URL is
+ // actually reachable before returning it, and never hand back a confirmed-dead
+ // link as success. This is what keeps the free smoke-test reliable for a
+ // reviewer even during a NIM outage. Raise FORGE_FREE_ATTEMPTS to trade
+ // latency for a better shot at landing the durable lane.
+ const maxAttempts = Math.max(1, Math.min(4, Number(env('FORGE_FREE_ATTEMPTS', '2')) || 2));
+
+ let liveFallback = null; // first reachable-but-non-durable result, used only if no durable one appears
+ let lastError = null;
+
+ for (let attempt = 1; attempt <= maxAttempts; attempt++) {
+ let gen;
+ try {
+ gen = await forgeFreeOnce({ base, prompt: trimmed, tierId });
+ } catch (err) {
+ lastError = err;
+ continue; // provider/timeout error — retry while attempts remain
+ }
+ // Durable — the reliable, R2-persisted result. Return immediately.
+ if (gen.data.durable && gen.data.glb_url) {
+ return shapeForgeFree({
+ data: gen.data,
+ prompt: trimmed,
+ tierId,
+ jobId: gen.jobId,
+ base,
+ startedAt,
+ attempts: attempt,
+ });
+ }
+ // Non-durable — only trust it if the ephemeral URL is actually fetchable
+ // right now. Keep the first reachable one, but keep trying for a durable
+ // result while attempts remain.
+ if (gen.data.glb_url && !liveFallback && (await isUrlReachable(gen.data.glb_url))) {
+ liveFallback = { data: gen.data, jobId: gen.jobId };
+ }
+ }
- let job;
- try {
- // Pin the free NVIDIA NIM (TRELLIS) lane so the happy path is always the
- // zero-cost engine; path:"image" is the only path NVIDIA serves. NVCF can
- // finish inside the generous submit window, so accept a synchronous done.
- job = await submitForge({
+ // No durable result — fall back to a verified-reachable non-durable one.
+ if (liveFallback) {
+ return shapeForgeFree({
+ data: liveFallback.data,
+ prompt: trimmed,
+ tierId,
+ jobId: liveFallback.jobId,
base,
- payload: { prompt: trimmed, tier: tierId, backend: 'nvidia', path: 'image' },
- submitTimeoutMs: 90_000,
- allowSyncDone: true,
+ startedAt,
+ attempts: maxAttempts,
});
- } catch (err) {
- return coreError(err.code || 'provider_error', err.message, {
- ...(err.retryAfter ? { retryAfter: err.retryAfter } : {}),
+ }
+
+ // Nothing usable across all attempts — return a clear, actionable error
+ // instead of a dead "success".
+ if (lastError) {
+ return coreError(lastError.code || 'provider_error', lastError.message, {
+ ...(lastError.extra || {}),
+ ...(lastError.retryAfter ? { retryAfter: lastError.retryAfter } : {}),
+ attempts: maxAttempts,
+ durationMs: Date.now() - startedAt,
});
}
+ return coreError(
+ 'lane_degraded',
+ 'The free 3D lane produced a result but its URL was unreachable — the durable NVIDIA NIM path is ' +
+ 'momentarily cold and the fallback provider URL expired before it could be used. Please try again shortly.',
+ { attempts: maxAttempts, durationMs: Date.now() - startedAt },
+ );
+}
+
+// One forge_free generation attempt: submit to the pinned free NVIDIA NIM lane,
+// then (when queued) poll to a terminal state. Returns { data, jobId } or throws
+// a coded error (with optional `.extra`/`.retryAfter`) the retry loop acts on.
+async function forgeFreeOnce({ base, prompt, tierId }) {
+ const job = await submitForge({
+ base,
+ // Pin the free NVIDIA NIM (TRELLIS) lane so the happy path is always the
+ // zero-cost engine; path:"image" is the only path NVIDIA serves. NVCF can
+ // finish inside the generous submit window, so accept a synchronous done.
+ payload: { prompt, tier: tierId, backend: 'nvidia', path: 'image' },
+ submitTimeoutMs: 90_000,
+ allowSyncDone: true,
+ });
if (job.status === 'done' && job.glb_url) {
- return shapeForgeFree({ data: job, prompt: trimmed, tierId, jobId: null, base, startedAt });
+ return { data: job, jobId: null };
}
const timeoutMs = Number(env('FORGE_FREE_TIMEOUT_MS', '180000'));
const intervalMs = Number(env('FORGE_FREE_POLL_MS', '3000'));
- let final;
- try {
- final = await pollForge(job.job_id, { base, timeoutMs, intervalMs });
- } catch (err) {
- return coreError(err.code || 'provider_error', err.message, {
- jobId: job.job_id,
- creationId: job.creation_id ?? null,
- durationMs: Date.now() - startedAt,
- });
- }
+ const final = await pollForge(job.job_id, { base, timeoutMs, intervalMs });
if (final._timedOut) {
- return coreError('timeout', `generation did not finish within ${timeoutMs}ms`, {
+ const e = new Error(`generation did not finish within ${timeoutMs}ms`);
+ e.code = 'timeout';
+ e.extra = {
jobId: job.job_id,
creationId: job.creation_id ?? null,
status: final.status || 'running',
resumeUrl: `${base}/api/forge?job=${job.job_id}`,
- durationMs: Date.now() - startedAt,
- });
+ };
+ throw e;
}
-
- return shapeForgeFree({ data: final, prompt: trimmed, tierId, jobId: job.job_id, base, startedAt });
+ return { data: final, jobId: job.job_id };
}
-function shapeForgeFree({ data, prompt, tierId, jobId, base, startedAt }) {
+function shapeForgeFree({ data, prompt, tierId, jobId, base, startedAt, attempts }) {
const glbUrl = data.glb_url;
- return {
+ const durable = Boolean(data.durable);
+ const result = {
ok: true,
free: true,
cost: '$0.00',
@@ -316,12 +396,24 @@ function shapeForgeFree({ data, prompt, tierId, jobId, base, startedAt }) {
prompt,
tier: tierId,
backend: data.backend ?? null,
+ durable,
jobId,
creationId: data.creation_id ?? null,
- durable: Boolean(data.durable),
+ attempts,
durationMs: Date.now() - startedAt,
fetchedAt: new Date().toISOString(),
};
+ // A non-durable URL is an ephemeral provider temp file (the free lane degraded
+ // off the durable NVIDIA NIM path). We only return it after verifying it is
+ // reachable, but it can still expire soon — flag it so a stale link later is
+ // never read as breakage, and so the caller views/downloads it promptly.
+ if (!durable) {
+ result.verifiedReachable = true;
+ result.warning =
+ 'Served from an ephemeral provider URL (the free lane degraded off the durable NVIDIA NIM path). ' +
+ 'It is reachable now but may expire soon — open or download it promptly, or call again for a durable result.';
+ }
+ return result;
}
// ---------------------------------------------------------------------------
diff --git a/pump-fun-skills/.claude-plugin/plugin.json b/pump-fun-skills/.claude-plugin/plugin.json
index c73d54ff0..f10b83942 100644
--- a/pump-fun-skills/.claude-plugin/plugin.json
+++ b/pump-fun-skills/.claude-plugin/plugin.json
@@ -8,5 +8,14 @@
"homepage": "https://pump.fun",
"license": "Apache-2.0",
"skills": "./",
- "repository": "https://github.com/nirholas/three.ws"
+ "repository": "https://github.com/nirholas/three.ws",
+ "keywords": [
+ "pump.fun",
+ "solana",
+ "trading",
+ "defi",
+ "tokens",
+ "swap"
+ ],
+ "category": "trading"
}
diff --git a/src/agent-exchange.js b/src/agent-exchange.js
index e9778baed..d64ab9fde 100644
--- a/src/agent-exchange.js
+++ b/src/agent-exchange.js
@@ -17,7 +17,6 @@ const TOPICS = [
{ id: 'sol', label: '◎ SOL' },
{ id: 'btc', label: '₿ BTC' },
{ id: 'eth', label: '⟠ ETH' },
- { id: 'doge', label: '🐕 DOGE' },
{ id: 'bnb', label: '⬡ BNB' },
];
diff --git a/src/erc8004/deploy-button.js b/src/erc8004/deploy-button.js
index 198ff1c5f..35de02c5a 100644
--- a/src/erc8004/deploy-button.js
+++ b/src/erc8004/deploy-button.js
@@ -401,7 +401,7 @@ export class DeployButton {
'Your Solana wallet is not linked to this account. Sign in with your Solana wallet first.',
{
label: 'Open wallet sign-in',
- handler: () => (window.location.href = '/login.html'),
+ handler: () => (window.location.href = '/login'),
},
);
return;
@@ -411,7 +411,7 @@ export class DeployButton {
`${err.message || 'Paid plan required'} — upgrade to use 5+ character vanity prefixes.`,
{
label: 'View plans',
- handler: () => (window.location.href = '/pricing.html'),
+ handler: () => (window.location.href = '/pricing'),
},
);
return;
diff --git a/tests/mcp-tool-contract.test.js b/tests/mcp-tool-contract.test.js
new file mode 100644
index 000000000..a04f5dc21
--- /dev/null
+++ b/tests/mcp-tool-contract.test.js
@@ -0,0 +1,94 @@
+// Golden contract tripwire for the hosted MCP tool catalogs.
+//
+// The MCP servers ARE the product surface we submit to the Claude Connectors
+// Directory and the OpenAI App Directory. A reviewer calls every tool and checks
+// its title + annotations; an accidental change to a tool's name, title,
+// annotations, or input schema can silently break a live listing. This test
+// freezes each catalog's PUBLIC contract (handlers already stripped by the
+// catalog's own map) into a committed snapshot, and enforces two store-review
+// invariants that are easy to regress:
+//
+// 1. Every tool has a non-empty `title` (both directories require it).
+// 2. Every tool sets `annotations.destructiveHint` EXPLICITLY — the MCP spec
+// defaults it to TRUE when omitted, which would mislabel a safe tool as
+// destructive in the client UI.
+//
+// Snapshots live in tests/__snapshots__/mcp-tool-contract.test.js.snap. When you
+// intentionally change a tool's contract, re-run with `-u` and review the diff —
+// that diff is exactly what a store reviewer would see change.
+
+import { describe, it, expect } from 'vitest';
+
+// Each hosted server exposes TOOL_CATALOG: the tools/list schema array with the
+// internal `scope`/`handler` fields already removed.
+import { TOOL_CATALOG as MAIN } from '../api/_mcp/catalog.js';
+import { TOOL_CATALOG as STUDIO3D } from '../api/_mcp3d/catalog.js';
+import { TOOL_CATALOG as AGENT } from '../api/_mcpagent/catalog.js';
+import { TOOL_CATALOG as BAZAAR } from '../api/_mcpbazaar/catalog.js';
+import { TOOL_CATALOG as IBM } from '../api/_mcpibm/catalog.js';
+
+const SERVERS = {
+ '_mcp': MAIN,
+ '_mcp3d': STUDIO3D,
+ '_mcpagent': AGENT,
+ '_mcpbazaar': BAZAAR,
+ '_mcpibm': IBM,
+};
+
+// Reduce a tool to its review-relevant contract. Description is intentionally
+// excluded: copy edits to descriptions are routine and should not fail the gate,
+// whereas name/title/annotations/inputSchema are the machine + reviewer contract.
+function contractOf(tool) {
+ return {
+ name: tool.name,
+ title: tool.title ?? null,
+ annotations: tool.annotations ?? null,
+ inputSchema: tool.inputSchema ?? null,
+ };
+}
+
+function catalogContract(catalog) {
+ return [...catalog]
+ .map(contractOf)
+ .sort((a, b) => String(a.name).localeCompare(String(b.name)));
+}
+
+describe('hosted MCP tool catalogs', () => {
+ for (const [server, catalog] of Object.entries(SERVERS)) {
+ describe(server, () => {
+ it('exposes a non-empty tool catalog', () => {
+ expect(Array.isArray(catalog)).toBe(true);
+ expect(catalog.length).toBeGreaterThan(0);
+ });
+
+ it('every tool has a non-empty title', () => {
+ for (const tool of catalog) {
+ expect(
+ typeof tool.title === 'string' && tool.title.trim().length > 0,
+ `tool "${tool.name}" in ${server} is missing a title`,
+ ).toBe(true);
+ }
+ });
+
+ it('every tool sets destructiveHint explicitly (MCP defaults it to true)', () => {
+ for (const tool of catalog) {
+ const a = tool.annotations;
+ expect(a, `tool "${tool.name}" in ${server} has no annotations`).toBeTruthy();
+ expect(
+ typeof a.destructiveHint === 'boolean',
+ `tool "${tool.name}" in ${server} must set annotations.destructiveHint explicitly`,
+ ).toBe(true);
+ }
+ });
+
+ it('tool names are unique within the server', () => {
+ const names = catalog.map((t) => t.name);
+ expect(new Set(names).size).toBe(names.length);
+ });
+
+ it('matches the frozen public contract snapshot', () => {
+ expect(catalogContract(catalog)).toMatchSnapshot();
+ });
+ });
+ }
+});