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(mcp,agents,profile): getting-started tool, public agent memories, replicate provider, profile wiring

nirholasd3ecc402601d
diff --git a/api/_lib/mcp-dispatch.js b/api/_lib/mcp-dispatch.js
index e8b9cce75..19a08fd8a 100644
--- a/api/_lib/mcp-dispatch.js
+++ b/api/_lib/mcp-dispatch.js
@@ -9,6 +9,21 @@ import { sanitizeToolError } from './mcp-error-sanitize.js';
export const PROTOCOL_VERSION = '2025-06-18';
+// Peek the single called tool from a (possibly batched) JSON-RPC body. Used by
+// the HTTP endpoints to (a) price the x402 challenge per tool and (b) decide
+// whether a request targets a public/free tool. Only a request calling exactly
+// ONE tool is reported; mixed batches and non-tools/call messages (initialize,
+// tools/list, ping) yield { toolName: null } so they take the default path.
+export function peekCalledTool(body) {
+ const batch = Array.isArray(body) ? body : [body];
+ const calls = batch.filter((m) => m && m.method === 'tools/call');
+ if (calls.length === 1) {
+ const name = calls[0]?.params?.name;
+ return { toolName: typeof name === 'string' ? name : null };
+ }
+ return { toolName: null };
+}
+
function ok(id, result) {
return { jsonrpc: '2.0', id, result };
}
diff --git a/api/_lib/mcp-getting-started.js b/api/_lib/mcp-getting-started.js
new file mode 100644
index 000000000..eb09d33aa
--- /dev/null
+++ b/api/_lib/mcp-getting-started.js
@@ -0,0 +1,120 @@
+// Shared free "getting_started" MCP tool — the one public, no-payment entry
+// point every hosted three.ws MCP server exposes so any client (including
+// non-x402 hosts and unauthenticated discovery probes) can learn what the
+// server does before connecting or paying.
+//
+// The tool carries NO `scope` and NO price, so it passes the dispatcher's scope
+// check and is served by the anonymous "free" principal. The HTTP endpoints gate
+// the no-auth bypass on this exact tool name (isPublicTool) — never on merely
+// being unpriced — so scoped tools stay locked.
+
+export const GETTING_STARTED_TOOL = 'getting_started';
+
+// First sentence of a tool description — a compact one-liner for the overview.
+function firstSentence(text = '') {
+ const t = String(text).trim().replace(/\s+/g, ' ');
+ const m = t.match(/^.*?[.!?](\s|$)/);
+ return (m ? m[0] : t).trim();
+}
+
+/**
+ * Build the free getting_started toolDef for a server.
+ *
+ * @param {object} cfg
+ * @param {string} cfg.server Human server name (e.g. "three.ws 3D Studio").
+ * @param {string} cfg.tagline One-line description of what the server does.
+ * @param {Array} cfg.tools The server's other toolDefs ({ name, description }).
+ * @param {Function} [cfg.priceFor] Optional (name) → { amount_usdc } for priced tools.
+ * @param {string[]} [cfg.access] How to access/pay for the server (ordered notes).
+ * @param {object} [cfg.links] Named links (homepage, docs, source, …).
+ * @returns {object} toolDef: { name, title, description, inputSchema, handler }
+ */
+export function buildGettingStartedTool({ server, tagline, tools = [], priceFor, access = [], links = {} }) {
+ const toolSummaries = tools
+ .filter((t) => t && t.name && t.name !== GETTING_STARTED_TOOL)
+ .map((t) => {
+ const price = priceFor ? priceFor(t.name) : null;
+ return {
+ name: t.name,
+ summary: firstSentence(t.description),
+ ...(price && price.amount_usdc > 0 ? { price: `$${price.amount_usdc}/call` } : {}),
+ };
+ });
+
+ const description =
+ `FREE — start here. Returns an overview of the ${server} MCP server: every tool and what it ` +
+ `does, how to access it, and useful links. No payment or account required. Call this first to orient.`;
+
+ const inputSchema = {
+ type: 'object',
+ additionalProperties: false,
+ properties: {
+ section: {
+ type: 'string',
+ enum: ['overview', 'tools', 'access', 'links'],
+ default: 'overview',
+ description:
+ 'Which part to return. Defaults to "overview" (everything). Use "tools", "access", or "links" to focus.',
+ },
+ },
+ };
+
+ function buildPayload(section) {
+ const full = {
+ ok: true,
+ server,
+ tagline,
+ tools: toolSummaries,
+ access,
+ links,
+ next_step:
+ 'Pick a tool from `tools` and call it. ' +
+ (access[0] || 'This getting_started tool is free; other tools may require a connection or payment.'),
+ };
+ if (section === 'tools') return { ok: true, server, tools: toolSummaries };
+ if (section === 'access') return { ok: true, server, access };
+ if (section === 'links') return { ok: true, server, links };
+ return full;
+ }
+
+ function renderText(p) {
+ if (!p.tagline) return JSON.stringify(p, null, 2);
+ return [
+ `# ${p.server} — Getting Started`,
+ '',
+ p.tagline,
+ '',
+ '## Tools (this getting_started tool is free)',
+ ...p.tools.map(
+ (t) => `- ${t.name}${t.price ? ` — ${t.price}` : ''} — ${t.summary}`,
+ ),
+ ...(p.access.length ? ['', '## Access', ...p.access.map((a) => `- ${a}`)] : []),
+ ...(Object.keys(p.links).length
+ ? ['', '## Links', ...Object.entries(p.links).map(([k, v]) => `- ${k}: ${v}`)]
+ : []),
+ '',
+ `Next: ${p.next_step}`,
+ ].join('\n');
+ }
+
+ return {
+ name: GETTING_STARTED_TOOL,
+ title: 'Getting Started (free)',
+ description,
+ // Deliberately no `scope` — callable by the anonymous free principal.
+ inputSchema,
+ async handler(args = {}) {
+ const payload = buildPayload(args?.section || 'overview');
+ return {
+ content: [{ type: 'text', text: renderText(payload) }],
+ structuredContent: payload,
+ };
+ },
+ };
+}
+
+// Strict public-tool predicate for the HTTP no-auth bypass. Only the
+// getting_started tool qualifies — being unpriced is NOT sufficient.
+export function isPublicTool(name) {
+ return name === GETTING_STARTED_TOOL;
+}
diff --git a/api/_lib/migrations/20260608030000_agent_memories_public.sql b/api/_lib/migrations/20260608030000_agent_memories_public.sql
new file mode 100644
index 000000000..9231681f4
--- /dev/null
+++ b/api/_lib/migrations/20260608030000_agent_memories_public.sql
@@ -0,0 +1,14 @@
+-- Opt-in public memories for user profiles.
+-- Memories are owner-only by default (api/agent-memory.js and the
+-- /api/agents/:id/memories handler only ever return rows to the owner).
+-- `is_public` lets an owner deliberately surface a memory on their public
+-- profile at /u/<username>. Default false so nothing leaks without an
+-- explicit toggle.
+
+alter table agent_memories add column if not exists is_public boolean not null default false;
+
+-- Read path for the public profile: public, non-expired memories for an agent,
+-- newest first.
+create index if not exists agent_memories_public
+ on agent_memories(agent_id, created_at desc)
+ where is_public = true and expires_at is null;
diff --git a/api/_lib/schema.sql b/api/_lib/schema.sql
index bb0d411ca..72beb606c 100644
--- a/api/_lib/schema.sql
+++ b/api/_lib/schema.sql
@@ -463,6 +463,17 @@ create index if not exists agent_memories_agent_type
on agent_memories(agent_id, type, created_at desc)
where expires_at is null;
+-- Memories are owner-only by default. `is_public` is an explicit opt-in that
+-- lets an owner surface a memory on their public profile (/u/<username>).
+-- Default false so nothing is ever exposed without a deliberate toggle.
+alter table agent_memories add column if not exists is_public boolean not null default false;
+
+-- Partial index for the public-profile read path: public, non-expired memories
+-- for a given agent, newest first.
+create index if not exists agent_memories_public
+ on agent_memories(agent_id, created_at desc)
+ where is_public = true and expires_at is null;
+
do $$ begin
create trigger agent_memories_set_updated_at before update on agent_memories
for each row execute function set_updated_at();
diff --git a/api/_mcp/auth.js b/api/_mcp/auth.js
index 9c8f93538..0c76c93e6 100644
--- a/api/_mcp/auth.js
+++ b/api/_mcp/auth.js
@@ -67,7 +67,7 @@ export function sendJsonRpcError(res, id, code, message, data) {
export async function authenticateRequest(
req,
res,
- { x402Amount, resourcePath = '/api/mcp', challenge } = {},
+ { x402Amount, resourcePath = '/api/mcp', challenge, allowFree = false } = {},
) {
const bearer = extractBearer(req);
const paymentHeader = req.headers['x-payment'];
@@ -81,6 +81,19 @@ export async function authenticateRequest(
return { auth, x402Ctx: null };
}
+ // Free, public entry point. When the caller has no bearer/payment AND the
+ // request targets an explicitly-public tool (the endpoint passes
+ // allowFree=true only for those — never for merely-unpriced scoped tools), we
+ // serve as an anonymous principal instead of issuing the OAuth/x402 challenge.
+ // scope '' means scoped tools stay locked; rateKey null so per-user limits key
+ // off the caller IP. This is what lets getting_started work with no credentials.
+ if (allowFree) {
+ return {
+ auth: { userId: null, rateKey: null, scope: '', source: 'free' },
+ x402Ctx: null,
+ };
+ }
+
const resourceUrl = resolveResourceUrl(req, resourcePath);
const requirements = paymentRequirements(
resourceUrl,
diff --git a/api/_mcp/catalog.js b/api/_mcp/catalog.js
index 6ebaf800e..37039e9d0 100644
--- a/api/_mcp/catalog.js
+++ b/api/_mcp/catalog.js
@@ -1,6 +1,8 @@
import Ajv from 'ajv';
import addFormats from 'ajv-formats';
+import { buildGettingStartedTool } from '../_lib/mcp-getting-started.js';
+import { priceFor } from '../_lib/pump-pricing.js';
import { toolDefs as avatarDefs } from './tools/avatars.js';
import { toolDefs as modelDefs } from './tools/models.js';
import { toolDefs as solanaDefs } from './tools/solana.js';
@@ -10,7 +12,7 @@ import { toolDefs as animationDefs } from './tools/animations.js';
import { toolDefs as memoryDefs } from './tools/memory.js';
import { toolDefs as embedDefs } from './tools/embed.js';
-const allDefs = [
+const baseDefs = [
...avatarDefs,
...embedDefs,
...modelDefs,
@@ -21,6 +23,23 @@ const allDefs = [
...memoryDefs,
];
+// Free, public entry point — listed first so discovery clients see it up top.
+// priceFor annotates the per-call price of the paid tools in the overview.
+const gettingStarted = buildGettingStartedTool({
+ server: 'three.ws',
+ tagline:
+ 'The main three.ws MCP server: render and manage 3D avatars and models, animations, an agent registry, agent memory, and live pump.fun market data.',
+ tools: baseDefs,
+ priceFor,
+ access: [
+ 'Connect with a three.ws account (OAuth) for your account-scoped avatars, agents, and memory.',
+ 'Or pay per call via x402 (USDC) for the public tools — each priced tool shows its price in tools/list.',
+ ],
+ links: { homepage: 'https://three.ws', source: 'https://github.com/nirholas/three.ws' },
+});
+
+const allDefs = [gettingStarted, ...baseDefs];
+
// Schema objects for tools/list — strip internal fields (scope, handler).
export const TOOL_CATALOG = allDefs.map(({ scope: _s, handler: _h, ...schema }) => schema);
diff --git a/api/_mcp/dispatch.js b/api/_mcp/dispatch.js
index 8d139d5bb..612281e44 100644
--- a/api/_mcp/dispatch.js
+++ b/api/_mcp/dispatch.js
@@ -5,6 +5,8 @@ import { declareMcpDiscovery } from '../_lib/x402/bazaar-helpers.js';
import { sanitizeToolError } from '../_lib/mcp-error-sanitize.js';
import { TOOL_CATALOG, TOOLS } from './catalog.js';
+export { isPublicTool } from '../_lib/mcp-getting-started.js';
+
export const PROTOCOL_VERSION = '2025-06-18';
const SERVER_INFO = { name: '3d-agent-mcp', version: '1.0.0' };
const log = logger('mcp');
diff --git a/api/_mcp3d/catalog.js b/api/_mcp3d/catalog.js
index d257e3136..3b50b7df7 100644
--- a/api/_mcp3d/catalog.js
+++ b/api/_mcp3d/catalog.js
@@ -1,6 +1,7 @@
import Ajv from 'ajv';
import addFormats from 'ajv-formats';
+import { buildGettingStartedTool } from '../_lib/mcp-getting-started.js';
import { toolDefs as studioDefs } from './tools/studio.js';
import { toolDefs as modelDefs } from '../_mcp/tools/models.js';
import { toolDefs as animationDefs } from '../_mcp/tools/animations.js';
@@ -16,7 +17,21 @@ const reusedModelDefs = modelDefs.filter(
// The animation library (list_animations + apply_animation) completes the
// pipeline: text_to_3d → auto_rig_model → apply_animation. Same retarget engine
// the main server exposes — reused here, not duplicated.
-const allDefs = [...studioDefs, ...reusedModelDefs, ...animationDefs];
+const baseDefs = [...studioDefs, ...reusedModelDefs, ...animationDefs];
+
+// Free, public entry point — listed first so discovery clients see it up top.
+const gettingStarted = buildGettingStartedTool({
+ server: 'three.ws 3D Studio',
+ tagline: 'Turn text or images into interactive, animation-ready 3D models.',
+ tools: baseDefs,
+ access: [
+ 'Connect with a three.ws account (OAuth) or an x402 wallet — most studio tools just need a connected client.',
+ 'Generation tools (text_to_3d, image_to_3d) run async jobs; poll generation_status for the GLB and an inline <model-viewer> artifact.',
+ ],
+ links: { homepage: 'https://three.ws', source: 'https://github.com/nirholas/three.ws' },
+});
+
+const allDefs = [gettingStarted, ...baseDefs];
// Schema objects for tools/list — strip internal fields (scope, handler).
export const TOOL_CATALOG = allDefs.map(({ scope: _s, handler: _h, ...schema }) => schema);
diff --git a/api/_mcp3d/dispatch.js b/api/_mcp3d/dispatch.js
index 47fc8fc71..14552bdb8 100644
--- a/api/_mcp3d/dispatch.js
+++ b/api/_mcp3d/dispatch.js
@@ -4,6 +4,7 @@ import { makeDispatcher, PROTOCOL_VERSION } from '../_lib/mcp-dispatch.js';
import { TOOL_CATALOG, TOOLS } from './catalog.js';
export { PROTOCOL_VERSION };
+export { isPublicTool } from '../_lib/mcp-getting-started.js';
const INSTRUCTIONS = [
'three.ws 3D Studio turns text or images into interactive, animation-ready 3D models.',
diff --git a/api/_mcpagent/catalog.js b/api/_mcpagent/catalog.js
index b42b9549c..23baa09a1 100644
--- a/api/_mcpagent/catalog.js
+++ b/api/_mcpagent/catalog.js
@@ -1,16 +1,31 @@
import Ajv from 'ajv';
import addFormats from 'ajv-formats';
+import { buildGettingStartedTool } from '../_lib/mcp-getting-started.js';
import { toolDefs } from './tools.js';
+// Free, public entry point — listed first so discovery clients see it up top.
+const gettingStarted = buildGettingStartedTool({
+ server: 'three.ws Agent',
+ tagline: 'Give your assistant a real on-chain wallet to discover, pay for, and call x402 services in USDC.',
+ tools: toolDefs,
+ access: [
+ 'Sign in with your three.ws account (OAuth) to use your agent wallet.',
+ 'pay_and_call spends USDC from your own three.ws agent wallet within your spend caps — check wallet_status first.',
+ ],
+ links: { homepage: 'https://three.ws', source: 'https://github.com/nirholas/three.ws' },
+});
+
+const allDefs = [gettingStarted, ...toolDefs];
+
// Schema objects for tools/list — strip internal fields (scope, handler).
-export const TOOL_CATALOG = toolDefs.map(({ scope: _s, handler: _h, ...schema }) => schema);
+export const TOOL_CATALOG = allDefs.map(({ scope: _s, handler: _h, ...schema }) => schema);
const ajv = new Ajv({ allErrors: true, useDefaults: true, coerceTypes: true, strict: false });
addFormats(ajv);
export const TOOLS = Object.fromEntries(
- toolDefs.map(({ name, scope, handler, inputSchema }) => [
+ allDefs.map(({ name, scope, handler, inputSchema }) => [
name,
{ scope, handler, validate: inputSchema ? ajv.compile(inputSchema) : null },
]),
diff --git a/api/_mcpagent/dispatch.js b/api/_mcpagent/dispatch.js
index 6d50759d4..2c8dd7caa 100644
--- a/api/_mcpagent/dispatch.js
+++ b/api/_mcpagent/dispatch.js
@@ -6,6 +6,7 @@ import { makeDispatcher, PROTOCOL_VERSION } from '../_lib/mcp-dispatch.js';
import { TOOL_CATALOG, TOOLS } from './catalog.js';
export { PROTOCOL_VERSION };
+export { isPublicTool } from '../_lib/mcp-getting-started.js';
const INSTRUCTIONS = [
'three.ws Agent gives this assistant a real on-chain wallet on the x402 network.',
diff --git a/api/_mcpbazaar/catalog.js b/api/_mcpbazaar/catalog.js
index b42b9549c..a95f155ba 100644
--- a/api/_mcpbazaar/catalog.js
+++ b/api/_mcpbazaar/catalog.js
@@ -1,16 +1,31 @@
import Ajv from 'ajv';
import addFormats from 'ajv-formats';
+import { buildGettingStartedTool } from '../_lib/mcp-getting-started.js';
import { toolDefs } from './tools.js';
+// Free, public entry point — listed first so discovery clients see it up top.
+const gettingStarted = buildGettingStartedTool({
+ server: 'three.ws x402 Bazaar',
+ tagline: 'Discover, price, and locate paid agent services across the live x402 facilitator network.',
+ tools: toolDefs,
+ access: [
+ 'Connect with a three.ws account (OAuth) or an x402 wallet — discovery tools query the live x402 facilitator network.',
+ 'Use get_service(resource_url) to see a service’s exact price, payment networks, and a ready pay link before calling it.',
+ ],
+ links: { homepage: 'https://three.ws', source: 'https://github.com/nirholas/three.ws' },
+});
+
+const allDefs = [gettingStarted, ...toolDefs];
+
// Schema objects for tools/list — strip internal fields (scope, handler).
-export const TOOL_CATALOG = toolDefs.map(({ scope: _s, handler: _h, ...schema }) => schema);
+export const TOOL_CATALOG = allDefs.map(({ scope: _s, handler: _h, ...schema }) => schema);
const ajv = new Ajv({ allErrors: true, useDefaults: true, coerceTypes: true, strict: false });
addFormats(ajv);
export const TOOLS = Object.fromEntries(
- toolDefs.map(({ name, scope, handler, inputSchema }) => [
+ allDefs.map(({ name, scope, handler, inputSchema }) => [
name,
{ scope, handler, validate: inputSchema ? ajv.compile(inputSchema) : null },
]),
diff --git a/api/_mcpbazaar/dispatch.js b/api/_mcpbazaar/dispatch.js
index 45750d34b..456039190 100644
--- a/api/_mcpbazaar/dispatch.js
+++ b/api/_mcpbazaar/dispatch.js
@@ -4,6 +4,7 @@ import { makeDispatcher, PROTOCOL_VERSION } from '../_lib/mcp-dispatch.js';
import { TOOL_CATALOG, TOOLS } from './catalog.js';
export { PROTOCOL_VERSION };
+export { isPublicTool } from '../_lib/mcp-getting-started.js';
const INSTRUCTIONS = [
'The x402 Bazaar lets you discover paid agent services across the live x402 facilitator network.',
diff --git a/api/_providers/replicate.js b/api/_providers/replicate.js
index 2a291f54a..1832b767d 100644
--- a/api/_providers/replicate.js
+++ b/api/_providers/replicate.js
@@ -132,6 +132,29 @@ function stripInternal(params) {
return out;
}
+// TRELLIS-family detection (firtoz/trellis and pinned-version variants). The
+// :version suffix is ignored; a bare 64-hex version hash won't match, so an
+// operator who pins TRELLIS by raw hash should also pass generate_model via
+// params — the slug default below handles every normal case.
+function isTrellisModel(modelRef) {
+ const slug = String(modelRef || '').split(':')[0].toLowerCase();
+ return /(^|\/)trellis$/.test(slug) || slug === 'firtoz/trellis';
+}
+
+// TRELLIS gates GLB extraction behind `generate_model`, which DEFAULTS TO FALSE
+// — so the model "succeeds" yet returns no mesh unless we ask for one. It also
+// renders a color video by default (we never consume it), so we disable the
+// video/ply outputs to roughly halve GPU time and cost. These are defaults only:
+// any caller-supplied param (texture_size, mesh_simplify, seed, …) overrides.
+function trellisReconstructDefaults() {
+ return {
+ generate_model: true,
+ generate_color: false,
+ generate_normal: false,
+ save_gaussian_ply: false,
+ };
+}
+
// Map our modes onto the input shape each model expects. Caller-supplied
// generation params (seed, texture_size, …) survive and win; internal envelope
// keys are stripped so they never reach the model schema.
@@ -139,7 +162,7 @@ function stripInternal(params) {
// For `reconstruct` (image-to-3D) the canonical input across the Hunyuan3D
// family, TRELLIS and TripoSR is an `images` array of URIs — we always send
// that and never the singular `image`/`mode` fields the old payload leaked.
-function buildInput({ mode, sourceUrl, params, images }) {
+function buildInput({ mode, sourceUrl, params, images, modelRef }) {
const clean = stripInternal(params);
if (mode === 'reconstruct') {
// `images` is the already-resolved view list (trimmed to what the chosen
@@ -152,7 +175,11 @@ function buildInput({ mode, sourceUrl, params, images }) {
: [];
const primary = photos[0] || (typeof params?.image === 'string' ? params.image : sourceUrl);
const finalImages = photos.length ? photos : primary ? [primary] : [];
- return { images: finalImages, ...clean };
+ // Apply TRELLIS-only GLB-extraction flags when the chosen model is TRELLIS.
+ // Sending these to a non-TRELLIS model (e.g. Hunyuan3D) would 422 against
+ // its OpenAPI schema, so they're gated on the model slug. Caller params win.
+ const modelDefaults = isTrellisModel(modelRef) ? trellisReconstructDefaults() : {};
+ return { images: finalImages, ...modelDefaults, ...clean };
}
// remesh / retex / rerig / restyle operate on an existing GLB. Send the
// source under the two field names cog GLB-pipelines commonly accept.
@@ -196,7 +223,9 @@ function extractGlbUrl(output) {
}
}
if (typeof output === 'object') {
- for (const key of ['glb', 'mesh', 'mesh_url', 'output_url', 'url', 'model']) {
+ // `model_file` is TRELLIS's GLB key and must come first; the rest cover the
+ // Hunyuan3D / TripoSR / generic cog shapes we also target.
+ for (const key of ['model_file', 'glb', 'mesh', 'mesh_url', 'output_url', 'url', 'model']) {
if (typeof output[key] === 'string') return output[key];
}
}
@@ -275,6 +304,7 @@ export function createRegenProvider() {
sourceUrl: request.sourceUrl,
params: request.params,
images,
+ modelRef,
});
// Two Replicate API shapes:
diff --git a/api/agents/_id/_sub.js b/api/agents/_id/_sub.js
index cde570da1..ca7dce83f 100644
--- a/api/agents/_id/_sub.js
+++ b/api/agents/_id/_sub.js
@@ -379,11 +379,16 @@ const memoryBodySchema = z.object({
tags: z.array(z.string().trim().max(100)).max(20).optional().default([]),
salience: z.number().min(0).max(1).optional(),
expiresAt: z.string().datetime().optional().nullable(),
+ isPublic: z.boolean().optional().default(false),
+});
+
+const memoryPatchSchema = z.object({
+ isPublic: z.boolean(),
});
export const handleMemories = wrap(async (req, res, id, memoryId) => {
- if (cors(req, res, { methods: 'GET,POST,DELETE,OPTIONS', credentials: true })) return;
- if (!method(req, res, ['GET', 'POST', 'DELETE'])) return;
+ if (cors(req, res, { methods: 'GET,POST,PATCH,DELETE,OPTIONS', credentials: true })) return;
+ if (!method(req, res, ['GET', 'POST', 'PATCH', 'DELETE'])) return;
const session = await getSessionUser(req);
const bearer = session ? null : await authenticateBearer(extractBearer(req));
@@ -403,7 +408,7 @@ export const handleMemories = wrap(async (req, res, id, memoryId) => {
if (req.method === 'GET') {
const rows = await sql`
- SELECT id, type, content, tags, salience, expires_at, created_at
+ SELECT id, type, content, tags, salience, expires_at, created_at, is_public
FROM agent_memories
WHERE agent_id = ${id}
AND (expires_at IS NULL OR expires_at > now())
@@ -419,14 +424,29 @@ export const handleMemories = wrap(async (req, res, id, memoryId) => {
return json(res, 200, { deleted: true });
}
+ // PATCH /memories/:id — toggle a single memory's public visibility. Scoped
+ // to this agent so a caller can't flip a memory belonging to another agent.
+ if (req.method === 'PATCH') {
+ if (!memoryId) return error(res, 400, 'bad_request', 'memory id required');
+ const body = parse(memoryPatchSchema, await readJson(req));
+ const [row] = await sql`
+ UPDATE agent_memories
+ SET is_public = ${body.isPublic}
+ WHERE id = ${memoryId} AND agent_id = ${id}
+ RETURNING id, is_public
+ `;
+ if (!row) return error(res, 404, 'not_found', 'memory not found');
+ return json(res, 200, { id: row.id, isPublic: row.is_public });
+ }
+
// POST
const rl = await limits.authIp(clientIp(req));
if (!rl.success) return rateLimited(res, rl);
const body = parse(memoryBodySchema, await readJson(req));
const [row] = await sql`
- INSERT INTO agent_memories (id, agent_id, type, content, tags, salience, expires_at)
- VALUES (gen_random_uuid(), ${id}, ${body.type}, ${body.content}, ${body.tags}, ${body.salience ?? 0.5}, ${body.expiresAt ?? null})
+ INSERT INTO agent_memories (id, agent_id, type, content, tags, salience, expires_at, is_public)
+ VALUES (gen_random_uuid(), ${id}, ${body.type}, ${body.content}, ${body.tags}, ${body.salience ?? 0.5}, ${body.expiresAt ?? null}, ${body.isPublic})
RETURNING id
`;
return json(res, 201, { id: row.id });
diff --git a/api/ibm-mcp.js b/api/ibm-mcp.js
index e1d8cd976..824a16fa9 100644
--- a/api/ibm-mcp.js
+++ b/api/ibm-mcp.js
@@ -61,31 +61,15 @@ export default wrap(async (req, res) => {
const { toolName } = peekCalledTool(body);
const x402Amount = toolName ? graniteX402Amount(toolName) : null;
- // Free, public entry point: a single tools/call to a registered free tool
- // (ibm_granite_getting_started) skips the x402/OAuth gate so any client —
- // including non-x402 hosts like watsonx Orchestrate — can discover the server
- // before paying. IP rate-limited like every other path so it can't be abused.
- if (toolName && isFreeTool(toolName)) {
- const ipRl = await limits.mcpIp(clientIp(req));
- if (!ipRl.success)
- return sendJsonRpcError(res, null, -32000, 'rate_limited', {
- retry_after: Math.ceil((ipRl.reset - Date.now()) / 1000),
- });
-
- const auth = { userId: null, rateKey: `free:${clientIp(req)}`, scope: '', source: 'free' };
- const r = await dispatch(Array.isArray(body) ? body[0] : body, auth, req);
-
- res.statusCode = 200;
- res.setHeader('content-type', 'application/json; charset=utf-8');
- res.setHeader('mcp-protocol-version', PROTOCOL_VERSION);
- res.end(JSON.stringify(Array.isArray(body) ? [r].filter((x) => x !== null) : (r ?? null)));
- return;
- }
-
+ // A call to the free public ibm_granite_getting_started tool is served without
+ // an x402 payment or OAuth token so any client — including non-x402 hosts like
+ // watsonx Orchestrate — can discover the server before paying. isFreeTool is
+ // strict: only the registered, unpriced getting_started tool qualifies.
const result = await authenticateRequest(req, res, {
x402Amount,
resourcePath: RESOURCE_PATH,
challenge: GRANITE_CHALLENGE,
+ allowFree: Boolean(toolName && isFreeTool(toolName)),
});
if (!result) return;
const { auth, x402Ctx } = result;
diff --git a/api/mcp-3d.js b/api/mcp-3d.js
index 81e401d6d..5c912ac41 100644
--- a/api/mcp-3d.js
+++ b/api/mcp-3d.js
@@ -7,7 +7,8 @@
// MCP Registry as io.github.nirholas/three-ws-3d-studio (see server-3d.json).
import { cors, readJson, wrap } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
-import { PROTOCOL_VERSION, dispatch } from './_mcp3d/dispatch.js';
+import { peekCalledTool } from './_lib/mcp-dispatch.js';
+import { PROTOCOL_VERSION, dispatch, isPublicTool } from './_mcp3d/dispatch.js';
import { send401, sendJsonRpcError, authenticateRequest, handleSse, handleTerminate } from './_mcp/auth.js';
export default wrap(async (req, res) => {
@@ -17,7 +18,14 @@ export default wrap(async (req, res) => {
if (req.method === 'DELETE') return handleTerminate(req, res);
if (req.method !== 'POST') return send401(res, 'method not supported');
- const result = await authenticateRequest(req, res);
+ // Read + parse the body before auth so a call to the free public
+ // getting_started tool can be served without an OAuth token or x402 payment.
+ const body = await readJson(req, 1_000_000);
+ const { toolName } = peekCalledTool(body);
+
+ const result = await authenticateRequest(req, res, {
+ allowFree: Boolean(toolName && isPublicTool(toolName)),
+ });
if (!result) return;
const { auth } = result;
@@ -32,7 +40,6 @@ export default wrap(async (req, res) => {
retry_after: Math.ceil((userRl.reset - Date.now()) / 1000),
});
- const body = await readJson(req, 1_000_000);
const batch = Array.isArray(body) ? body : [body];
if (batch.length > 16) return sendJsonRpcError(res, null, -32600, 'batch too large (max 16)');
diff --git a/api/mcp-agent.js b/api/mcp-agent.js
index 2b6f8a540..15a1fcb0f 100644
--- a/api/mcp-agent.js
+++ b/api/mcp-agent.js
@@ -5,7 +5,8 @@
// Registered with the MCP Registry as io.github.nirholas/threews-agent.
import { cors, readJson, wrap } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
-import { PROTOCOL_VERSION, dispatch } from './_mcpagent/dispatch.js';
+import { peekCalledTool } from './_lib/mcp-dispatch.js';
+import { PROTOCOL_VERSION, dispatch, isPublicTool } from './_mcpagent/dispatch.js';
import { send401, sendJsonRpcError, authenticateRequest, handleSse, handleTerminate } from './_mcp/auth.js';
export default wrap(async (req, res) => {
@@ -15,7 +16,14 @@ export default wrap(async (req, res) => {
if (req.method === 'DELETE') return handleTerminate(req, res);
if (req.method !== 'POST') return send401(res, 'method not supported');
- const result = await authenticateRequest(req, res);
+ // Read + parse the body before auth so a call to the free public
+ // getting_started tool can be served without an OAuth token or x402 payment.
+ const body = await readJson(req, 1_000_000);
+ const { toolName } = peekCalledTool(body);
+
+ const result = await authenticateRequest(req, res, {
+ allowFree: Boolean(toolName && isPublicTool(toolName)),
+ });
if (!result) return;
const { auth } = result;
@@ -30,7 +38,6 @@ export default wrap(async (req, res) => {
retry_after: Math.ceil((userRl.reset - Date.now()) / 1000),
});
- const body = await readJson(req, 1_000_000);
const batch = Array.isArray(body) ? body : [body];
if (batch.length > 16) return sendJsonRpcError(res, null, -32600, 'batch too large (max 16)');
diff --git a/api/mcp-bazaar.js b/api/mcp-bazaar.js
index ead9fb7a5..5cffb91ec 100644
--- a/api/mcp-bazaar.js
+++ b/api/mcp-bazaar.js
@@ -7,7 +7,8 @@
// Registry as io.github.nirholas/three-ws-x402-bazaar (see server-bazaar.json).
import { cors, readJson, wrap } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
-import { PROTOCOL_VERSION, dispatch } from './_mcpbazaar/dispatch.js';
+import { peekCalledTool } from './_lib/mcp-dispatch.js';
+import { PROTOCOL_VERSION, dispatch, isPublicTool } from './_mcpbazaar/dispatch.js';
import { send401, sendJsonRpcError, authenticateRequest, handleSse, handleTerminate } from './_mcp/auth.js';
export default wrap(async (req, res) => {
@@ -17,7 +18,14 @@ export default wrap(async (req, res) => {
if (req.method === 'DELETE') return handleTerminate(req, res);
if (req.method !== 'POST') return send401(res, 'method not supported');
- const result = await authenticateRequest(req, res);
+ // Read + parse the body before auth so a call to the free public
+ // getting_started tool can be served without an OAuth token or x402 payment.
+ const body = await readJson(req, 1_000_000);
+ const { toolName } = peekCalledTool(body);
+
+ const result = await authenticateRequest(req, res, {
+ allowFree: Boolean(toolName && isPublicTool(toolName)),
+ });
if (!result) return;
const { auth } = result;
@@ -32,7 +40,6 @@ export default wrap(async (req, res) => {
retry_after: Math.ceil((userRl.reset - Date.now()) / 1000),
});
- const body = await readJson(req, 1_000_000);
const batch = Array.isArray(body) ? body : [body];
if (batch.length > 16) return sendJsonRpcError(res, null, -32600, 'batch too large (max 16)');
diff --git a/api/mcp.js b/api/mcp.js
index ad74bcadc..35ade6ff6 100644
--- a/api/mcp.js
+++ b/api/mcp.js
@@ -4,7 +4,7 @@ import { cors, readJson, wrap } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { settlePayment, encodePaymentResponseHeader } from './_lib/x402-spec.js';
import { x402AmountForTool } from './_lib/pump-pricing.js';
-import { PROTOCOL_VERSION, dispatch } from './_mcp/dispatch.js';
+import { PROTOCOL_VERSION, dispatch, isPublicTool } from './_mcp/dispatch.js';
import { send401, sendJsonRpcError, authenticateRequest, handleSse, handleTerminate } from './_mcp/auth.js';
import { sendX402Error } from './_mcp/payments.js';
@@ -40,7 +40,12 @@ export default wrap(async (req, res) => {
const { toolName } = peekCalledTool(body);
const x402Amount = toolName ? x402AmountForTool(toolName) : null;
- const result = await authenticateRequest(req, res, { x402Amount });
+ // A call to the free public getting_started tool is served without an OAuth
+ // token or x402 payment so any client can discover the server first.
+ const result = await authenticateRequest(req, res, {
+ x402Amount,
+ allowFree: Boolean(toolName && isPublicTool(toolName)),
+ });
if (!result) return;
const { auth, x402Ctx } = result;
diff --git a/api/pump/[action].js b/api/pump/[action].js
index 8d9ab9393..2f8b81101 100644
--- a/api/pump/[action].js
+++ b/api/pump/[action].js
@@ -2878,6 +2878,15 @@ async function handleCoinTrades(req, res) {
if (!MINT_RE.test(mint)) return error(res, 400, 'invalid_mint', 'mint must be a base58 address');
const limit = Math.min(Math.max(1, Number(url.searchParams.get('limit') || 30)), 100);
const upstream = `${PUMP_SWAP_BASE}/v2/coins/${mint}/trades?limit=${limit}`;
+ // "Recent trades" is a soft, continuously-polled feed (the homepage live card
+ // re-fetches every ~4s). A transient pump.fun swap-API blip means "no new data
+ // right now", not a hard error — so degrade to an empty 200 with `no-store`
+ // rather than a 5xx the browser console logs on every poll. The next poll
+ // retries immediately and the card recovers the moment upstream is back.
+ const stale = (extra = {}) => {
+ res.setHeader('cache-control', 'no-store');
+ return json(res, 200, { mint, trades: [], stale: true, ...extra });
+ };
let resp;
try {
resp = await fetch(upstream, {
@@ -2885,10 +2894,15 @@ async function handleCoinTrades(req, res) {
signal: AbortSignal.timeout(8000),
});
} catch {
- return error(res, 504, 'upstream_timeout', 'pump.fun swap API did not respond');
+ return stale({ reason: 'upstream_timeout' });
+ }
+ if (!resp.ok) return stale({ reason: `upstream_${resp.status}` });
+ let body;
+ try {
+ body = await resp.json();
+ } catch {
+ return stale({ reason: 'upstream_unparseable' });
}
- if (!resp.ok) return error(res, 502, 'upstream_failed', `pump.fun returned ${resp.status}`);
- const body = await resp.json();
const raw = Array.isArray(body) ? body : Array.isArray(body?.trades) ? body.trades : [];
const trades = raw
.map((t) => ({
diff --git a/api/users/[username].js b/api/users/[username].js
index 82f667eff..fb6fdecd2 100644
--- a/api/users/[username].js
+++ b/api/users/[username].js
@@ -29,6 +29,8 @@ export default wrap(async (req, res) => {
widgetRows,
skillRows,
pluginRows,
+ coinRows,
+ memoryRows,
socialRows,
statsRow,
] = await Promise.all([
@@ -85,6 +87,36 @@ export default wrap(async (req, res) => {
order by install_count desc, created_at desc
limit 24
`,
+ // Coins the user has launched. Each launch is recorded on the agent that
+ // minted it, in meta.token. Surface only public agents with a confirmed
+ // mint, newest first.
+ sql`
+ select id as agent_id, name as agent_name, profile_image_url, avatar_url,
+ meta->'token' as token
+ from agent_identities
+ where user_id = ${user.id}
+ and is_public = true
+ and deleted_at is null
+ and meta->'token'->>'mint' is not null
+ order by coalesce(meta->'token'->>'launched_at', created_at::text) desc
+ limit 48
+ `,
+ // Public memories the owner has explicitly opted to showcase, surfaced
+ // through their public agents. Private memories (the default) never leave
+ // the owner's own view.
+ sql`
+ select m.id, m.type, m.content, m.tags, m.created_at,
+ a.id as agent_id, a.name as agent_name
+ from agent_memories m
+ join agent_identities a on a.id = m.agent_id
+ where a.user_id = ${user.id}
+ and a.is_public = true
+ and a.deleted_at is null
+ and m.is_public = true
+ and (m.expires_at is null or m.expires_at > now())
+ order by m.created_at desc
+ limit 48
+ `,
sql`
select provider, username
from social_connections
@@ -103,6 +135,13 @@ export default wrap(async (req, res) => {
where author_id = ${user.id} and is_public = true) as skills_count,
(select count(*)::int from plugins
where author_id = ${user.id} and is_public = true and deleted_at is null) as plugins_count,
+ (select count(*)::int from agent_identities
+ where user_id = ${user.id} and is_public = true and deleted_at is null
+ and meta->'token'->>'mint' is not null) as coins_count,
+ (select count(*)::int from agent_memories m
+ join agent_identities a on a.id = m.agent_id
+ where a.user_id = ${user.id} and a.is_public = true and a.deleted_at is null
+ and m.is_public = true and (m.expires_at is null or m.expires_at > now())) as memories_count,
(select coalesce(sum(view_count), 0)::bigint from widgets
where user_id = ${user.id} and is_public = true and deleted_at is null) as total_widget_views
`,
@@ -177,6 +216,38 @@ export default wrap(async (req, res) => {
created_at: p.created_at,
}));
+ // Coins: the launch record lives in agent_identities.meta.token. Pass through
+ // only display-safe fields; the mint/links are user-supplied launch data.
+ const coins = coinRows
+ .map((c) => {
+ const t = c.token || {};
+ if (!t.mint) return null;
+ return {
+ mint: t.mint,
+ name: t.name || c.agent_name,
+ symbol: t.symbol || null,
+ description: t.description || null,
+ image: t.image || null,
+ cluster: t.cluster || 'mainnet',
+ launched_at: t.launched_at || null,
+ url: t.pumpfun_url || t.explorer_url || null,
+ agent_id: c.agent_id,
+ agent_name: c.agent_name,
+ agent_image: c.profile_image_url || c.avatar_url || null,
+ };
+ })
+ .filter(Boolean);
+
+ const memories = memoryRows.map((m) => ({
+ id: m.id,
+ type: m.type,
+ content: m.content,
+ tags: m.tags || [],
+ created_at: m.created_at,
+ agent_id: m.agent_id,
+ agent_name: m.agent_name,
+ }));
+
const social = {};
for (const row of socialRows) {
social[row.provider] = row.username;
@@ -188,6 +259,8 @@ export default wrap(async (req, res) => {
widgets: statsRow?.widgets_count ?? 0,
skills: statsRow?.skills_count ?? 0,
plugins: statsRow?.plugins_count ?? 0,
+ coins: statsRow?.coins_count ?? 0,
+ memories: statsRow?.memories_count ?? 0,
widget_views: Number(statsRow?.total_widget_views ?? 0),
};
@@ -207,5 +280,7 @@ export default wrap(async (req, res) => {
widgets,
skills,
plugins,
+ coins,
+ memories,
});
});
diff --git a/pages/agent-edit.html b/pages/agent-edit.html
index 9731dfa32..e8f22f230 100644
--- a/pages/agent-edit.html
+++ b/pages/agent-edit.html
@@ -893,6 +893,28 @@
.mem-item-type { font-size: 0.618rem; color: #93c5fd; text-transform: uppercase; letter-spacing: 0.08em; font-weight: 500; margin-bottom: 0.25rem; }
.mem-item-content { font-size: 0.875rem; color: rgba(255, 255, 255, 0.85); white-space: pre-wrap; word-break: break-word; }
.mem-item-tags { font-size: 0.618rem; color: rgba(255, 255, 255, 0.4); margin-top: 0.25rem; }
+ .mem-item-actions { display: flex; align-items: center; gap: 0.5rem; flex-shrink: 0; }
+ .mem-vis-toggle {
+ background: transparent;
+ border: 1px solid rgba(255, 255, 255, 0.12);
+ color: rgba(255, 255, 255, 0.45);
+ font-size: 0.618rem;
+ font-family: inherit;
+ letter-spacing: 0.03em;
+ padding: 0.2rem 0.5rem;
+ border-radius: 999px;
+ cursor: pointer;
+ white-space: nowrap;
+ transition: color 0.15s, border-color 0.15s, background 0.15s;
+ }
+ .mem-vis-toggle:hover { color: rgba(255, 255, 255, 0.8); border-color: rgba(255, 255, 255, 0.25); }
+ .mem-vis-toggle:focus-visible { outline: 2px solid rgba(255, 215, 0, 0.5); outline-offset: 1px; }
+ .mem-vis-toggle.is-public {
+ color: #ffd700;
+ border-color: rgba(255, 215, 0, 0.4);
+ background: rgba(255, 215, 0, 0.08);
+ }
+ .mem-vis-toggle:disabled { opacity: 0.5; cursor: progress; }
/* Chip list */
.chip-list { display: flex; flex-wrap: wrap; gap: 0.5rem; }
diff --git a/pages/profile.html b/pages/profile.html
index cc5676490..2bc103582 100644
--- a/pages/profile.html
+++ b/pages/profile.html
@@ -841,7 +841,7 @@
return;
}
const data = await res.json();
- const { user, stats = {}, social = {}, avatars = [], agents = [], widgets = [], skills = [], plugins = [] } = data;
+ const { user, stats = {}, social = {}, avatars = [], agents = [], widgets = [], skills = [], plugins = [], coins = [], memories = [] } = data;
// Update page meta
const display = user.display_name || user.username;
diff --git a/public/features.json b/public/features.json
index e41cceb83..124e3c1a6 100644
--- a/public/features.json
+++ b/public/features.json
@@ -1,5 +1,5 @@
{
- "generated_at": "2026-06-08T14:11:18.101Z",
+ "generated_at": "2026-06-08T16:28:41.723Z",
"generated_by": "scripts/build-page-index.mjs from data/pages.json",
"site": {
"name": "three.ws",
diff --git a/scripts/test-reconstruct-live.mjs b/scripts/test-reconstruct-live.mjs
new file mode 100644
index 000000000..40097ca79
--- /dev/null
+++ b/scripts/test-reconstruct-live.mjs
@@ -0,0 +1,107 @@
+// Live end-to-end check for the photo → 3D reconstruction provider.
+//
+// Exercises the REAL Replicate API through api/_providers/replicate.js: submits
+// a reconstruct job from an image, polls to completion, and verifies a valid
+// binary glTF (GLB) comes back. This is the proof that the TRELLIS contract fix
+// (generate_model:true + model_file output key) works against the live model —
+// not just the stubbed vitest regression.
+//
+// Usage:
+// node scripts/test-reconstruct-live.mjs [imageUrl]
+//
+// Requires REPLICATE_API_TOKEN in the environment (loaded from .env if present).
+
+import { readFileSync } from 'node:fs';
+import { createRegenProvider } from '../api/_providers/replicate.js';
+
+// Minimal .env loader so the script runs without extra deps.
+function loadDotEnv() {
+ try {
+ const raw = readFileSync(new URL('../.env', import.meta.url), 'utf8');
+ for (const line of raw.split('\n')) {
+ const m = line.match(/^([A-Z0-9_]+)=(.*)$/);
+ if (m && !process.env[m[1]]) process.env[m[1]] = m[2];
+ }
+ } catch (_) {}
+}
+
+const DEFAULT_IMAGE =
+ 'https://raw.githubusercontent.com/microsoft/TRELLIS/main/assets/example_image/typical_creature_dragon.png';
+
+const GLB_MAGIC = 0x46546c67; // 'glTF' little-endian
+
+function sleep(ms) {
+ return new Promise((r) => setTimeout(r, ms));
+}
+
+async function main() {
+ loadDotEnv();
+ if (!process.env.REPLICATE_API_TOKEN) {
+ console.error('✗ REPLICATE_API_TOKEN is not set. Paste a token into .env and re-run.');
+ process.exit(1);
+ }
+
+ const imageUrl = process.argv[2] || DEFAULT_IMAGE;
+ const provider = createRegenProvider();
+
+ console.log('→ submitting reconstruct job');
+ console.log(' image:', imageUrl);
+ const submission = await provider.submit({
+ mode: 'reconstruct',
+ params: { images: [imageUrl] },
+ sourceUrl: imageUrl,
+ });
+ console.log(' model:', submission.model);
+ console.log(' prediction:', submission.extJobId);
+
+ const deadline = Date.now() + 8 * 60 * 1000;
+ let glbUrl = null;
+ let last = '';
+ while (Date.now() < deadline) {
+ await sleep(3000);
+ const s = await provider.status(submission.extJobId);
+ if (s.rawStatus && s.rawStatus !== last) {
+ last = s.rawStatus;
+ console.log(' status:', s.rawStatus);
+ }
+ if (s.status === 'done') {
+ glbUrl = s.resultGlbUrl || null;
+ if (!glbUrl) {
+ console.error('✗ job finished but no GLB url — extractGlbUrl returned nothing:', s.error);
+ process.exit(1);
+ }
+ break;
+ }
+ if (s.status === 'failed') {
+ console.error('✗ job failed:', s.error);
+ process.exit(1);
+ }
+ }
+
+ if (!glbUrl) {
+ console.error('✗ timed out before the job completed');
+ process.exit(1);
+ }
+
+ console.log('→ downloading GLB:', glbUrl);
+ const resp = await fetch(glbUrl);
+ if (!resp.ok) {
+ console.error('✗ could not download GLB:', resp.status);
+ process.exit(1);
+ }
+ const buf = Buffer.from(await resp.arrayBuffer());
+ const magic = buf.readUInt32LE(0);
+ const version = buf.readUInt32LE(4);
+ if (magic !== GLB_MAGIC || version !== 2) {
+ console.error(`✗ downloaded file is not a valid binary glTF 2.0 (magic=${magic.toString(16)}, version=${version})`);
+ process.exit(1);
+ }
+
+ console.log(`✓ PASS — valid GLB, ${(buf.length / 1024).toFixed(0)} KB`);
+ console.log(' The selfie → 3D pipeline produces a real, well-formed model end to end.');
+}
+
+main().catch((err) => {
+ console.error('✗ unexpected error:', err?.message || err);
+ process.exit(1);
+});
diff --git a/src/agent-detail-market.js b/src/agent-detail-market.js
index 35af73acb..90aa264fc 100644
--- a/src/agent-detail-market.js
+++ b/src/agent-detail-market.js
@@ -555,9 +555,10 @@ function bindPurchaseDelegation() {
// ── Embed snippets ────────────────────────────────────────────────────────────
-function renderEmbed(a) {
+export function renderEmbed(a) {
const card = $('ad-embed-card');
if (!card) return;
+ if (card.dataset.embedDisabled === '1') return; // policy: embedding turned off
card.hidden = false;
const agentId = a.id;
const glbUrl = a.avatar_glb_url || '';
diff --git a/src/agent-detail.css b/src/agent-detail.css
index f3a752ee1..196e5fa35 100644
--- a/src/agent-detail.css
+++ b/src/agent-detail.css
@@ -1333,6 +1333,18 @@ a {
white-space: pre;
}
+/* Brief highlight when the ?view=embed deep-link scrolls to the embed card. */
+.ad-embed-card.ad-embed-flash {
+ animation: ad-embed-flash 1.6s ease-out;
+}
+@keyframes ad-embed-flash {
+ 0%, 15% { box-shadow: 0 0 0 2px var(--ad-accent, #6366f1), 0 0 22px rgba(99, 102, 241, 0.55); }
+ 100% { box-shadow: 0 0 0 0 transparent, 0 0 0 transparent; }
+}
+@media (prefers-reduced-motion: reduce) {
+ .ad-embed-card.ad-embed-flash { animation: none; }
+}
+
/* ── Version history ───────────────────────────────────────────────────── */
.ad-versions {
list-style: none;
diff --git a/src/agent-detail.js b/src/agent-detail.js
index e187faff1..06abde7ca 100644
--- a/src/agent-detail.js
+++ b/src/agent-detail.js
@@ -26,12 +26,12 @@ const solanaWeb3 = {
};
import { openSwapModal } from './swap-jupiter.js';
import { onchainBadgeEl } from './shared/onchain-badge.js';
-import { seeInWorldHref } from './shared/agent-3d.js';
+import { seeInWorldHref, agentAvatarGlb } from './shared/agent-3d.js';
import { renderError as renderAsyncError } from './shared/async-state.js';
import { openCoinLaunch } from './shared/agent-coin.js';
import { Modal } from './shared/modal.js';
import { showSharePanel } from './shared/share.js';
-import { enrichAgentDetail } from './agent-detail-market.js';
+import { enrichAgentDetail, renderEmbed as renderAgentEmbed } from './agent-detail-market.js';
import { log } from './shared/log.js';
import { mountViewSwitcher } from './view-switcher.js';
@@ -300,10 +300,15 @@ function render(agent) {
mountViewSwitcher($('view-switch-slot'), {
kind: 'agent',
id: agent.id,
- active: 'detail',
+ active: new URLSearchParams(location.search).get('view') === 'embed' ? 'embed' : 'detail',
worldHref: seeInWorldHref(agent),
});
+ // Embed snippets work for every agent, not just marketplace-published ones,
+ // so the "Embed" view always lands on real, copyable code. Marketplace
+ // enrichment later refreshes this with the canonical GLB if it differs.
+ renderAgentEmbed({ ...agent, avatar_glb_url: agent.avatar_glb_url || agentAvatarGlb(agent) });
+
const status = $('ad-status');
status.textContent = agent.active ? 'Active' : 'Inactive';
status.classList.toggle('ad-status-inactive', !agent.active);
@@ -483,7 +488,23 @@ function render(agent) {
// preview, creator profile, skill pricing, sale panel, embed, similar,
// versions) onto the canonical page. No-ops if the agent isn't published to
// the marketplace, so the base page is never blocked.
- enrichAgentDetail(agent).catch((e) => log.warn('[agent-detail] enrich failed:', e?.message));
+ enrichAgentDetail(agent)
+ .then(() => {
+ // Embed view (from the view switcher): reveal and highlight the embed
+ // snippets once enrichment has populated them.
+ if (new URLSearchParams(location.search).get('view') === 'embed') focusEmbedSection();
+ })
+ .catch((e) => log.warn('[agent-detail] enrich failed:', e?.message));
+}
+
+// Scroll to the embed snippets and flash them — used by the ?view=embed
+// deep-link so the switcher's "Embed" view lands on something concrete.
+function focusEmbedSection() {
+ const card = document.getElementById('ad-embed-card');
+ if (!card || card.hidden) return;
+ card.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ card.classList.add('ad-embed-flash');
+ setTimeout(() => card.classList.remove('ad-embed-flash'), 1600);
}
async function loadExtraSections(agentId, rec, isOwner) {
@@ -1044,6 +1065,14 @@ function renderEmbedPolicy(p) {
const allowedOrigins = Array.isArray(p.allowed_origins) ? p.allowed_origins : [];
const monthlyQuota = p?.brain?.monthly_quota;
+ // Respect the owner's embed policy: if embedding is turned off, hide the
+ // snippet card (and keep enrichment from re-revealing it).
+ const embedCard = document.getElementById('ad-embed-card');
+ if (embedCard && p.allow_embed === false) {
+ embedCard.dataset.embedDisabled = '1';
+ embedCard.hidden = true;
+ }
+
host.appendChild(
el('div', { class: 'ad-row ad-row-split' }, [
el('span', { class: 'ad-muted', text: 'Embeddable' }),
diff --git a/src/agent-edit.js b/src/agent-edit.js
index dd104a54d..a27ebbd18 100644
--- a/src/agent-edit.js
+++ b/src/agent-edit.js
@@ -1416,19 +1416,62 @@ function renderMemories(rows) {
container.innerHTML = '<div class="muted">No memories yet.</div>';
return;
}
- container.innerHTML = rows.map((m) => `
+ container.innerHTML = rows.map((m) => {
+ const isPublic = m.is_public === true;
+ return `
<div class="mem-item" data-id="${escapeHtml(m.id)}">
<div class="mem-item-body">
<div class="mem-item-type">${escapeHtml(m.type)}</div>
<div class="mem-item-content">${escapeHtml(m.content)}</div>
${m.tags?.length ? `<div class="mem-item-tags">${m.tags.map(escapeHtml).join(' · ')}</div>` : ''}
</div>
- <button class="chip-remove" data-del="${escapeHtml(m.id)}" title="Delete">×</button>
+ <div class="mem-item-actions">
+ <button
+ class="mem-vis-toggle${isPublic ? ' is-public' : ''}"
+ data-vis="${escapeHtml(m.id)}"
+ aria-pressed="${isPublic}"
+ title="${isPublic ? 'Public — shown on your profile. Click to make private.' : 'Private — only you can see this. Click to show it on your profile.'}"
+ >${isPublic ? '◉ Public' : '○ Private'}</button>
+ <button class="chip-remove" data-del="${escapeHtml(m.id)}" title="Delete">×</button>
+ </div>
</div>
- `).join('');
+ `;
+ }).join('');
container.querySelectorAll('[data-del]').forEach((btn) => {
btn.addEventListener('click', () => deleteMemory(btn.dataset.del));
});
+ container.querySelectorAll('[data-vis]').forEach((btn) => {
+ btn.addEventListener('click', () => toggleMemoryVisibility(btn));
+ });
+}
+
+async function toggleMemoryVisibility(btn) {
+ const id = btn.dataset.vis;
+ const makePublic = btn.getAttribute('aria-pressed') !== 'true';
+ btn.disabled = true;
+ try {
+ const r = await apiFetch(`${API_BASE}/agents/${agentId}/memories/${id}`, {
+ method: 'PATCH',
+ headers: { 'Content-Type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ isPublic: makePublic }),
+ });
+ if (!r.ok) {
+ const j = await r.json().catch(() => ({}));
+ throw new Error(j.error_description || j.error || `HTTP ${r.status}`);
+ }
+ btn.setAttribute('aria-pressed', String(makePublic));
+ btn.classList.toggle('is-public', makePublic);
+ btn.textContent = makePublic ? '◉ Public' : '○ Private';
+ btn.title = makePublic
+ ? 'Public — shown on your profile. Click to make private.'
+ : 'Private — only you can see this. Click to show it on your profile.';
+ } catch (err) {
+ $('mem-status').textContent = `Could not update visibility: ${err.message}`;
+ $('mem-status').className = 'form-status err';
+ } finally {
+ btn.disabled = false;
+ }
}
async function deleteMemory(id) {
diff --git a/src/agent-identity.js b/src/agent-identity.js
index 99e0844d5..4f515403b 100644
--- a/src/agent-identity.js
+++ b/src/agent-identity.js
@@ -10,30 +10,16 @@
*/
import { AgentMemory } from './agent-memory.js';
+import { apiFetch } from './api.js';
const STORAGE_KEY = 'agent_identity';
-// Single-use CSRF token cache. Required by /api/agents PUT/PATCH/DELETE +
-// /api/agents/:id/wallet on the server. Token is burned on consumption.
-let _csrfToken = null;
-async function getCsrfToken() {
- if (_csrfToken) return _csrfToken;
- try {
- const r = await fetch('/api/csrf-token', { credentials: 'include' });
- if (!r.ok) return null;
- const j = await r.json();
- _csrfToken = j?.data?.token || null;
- return _csrfToken;
- } catch {
- return null;
- }
-}
-
-async function csrfHeaders() {
- const csrf = await getCsrfToken();
- _csrfToken = null;
- return csrf ? { 'x-csrf-token': csrf } : {};
-}
+// All /api traffic goes through apiFetch (src/api.js): it issues a fresh
+// single-use CSRF token for every mutation, carries the session cookie, and
+// retries transient 5xx on safe methods. We pass allowAnonymous:true on every
+// call — this module routinely runs for signed-out widget visitors, and a 401
+// must surface as "no backend identity", never hijack the page to /login.
+const ANON = { allowAnonymous: true };
/**
* @typedef {Object} AgentRecord
@@ -118,11 +104,10 @@ export class AgentIdentity {
if (!this._record) return;
this._persist();
try {
- const csrf = await csrfHeaders();
- const resp = await fetch(`/api/agents/${this._record.id}`, {
+ const resp = await apiFetch(`/api/agents/${this._record.id}`, {
method: 'PUT',
- headers: { 'content-type': 'application/json', ...csrf },
- credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ ...ANON,
body: JSON.stringify({
name: this._record.name,
description: this._record.description,
@@ -156,11 +141,10 @@ export class AgentIdentity {
async linkWallet(address, chainId) {
await this.update({ walletAddress: address, chainId });
try {
- const csrf = await csrfHeaders();
- await fetch(`/api/agents/${this.id}/wallet`, {
+ await apiFetch(`/api/agents/${this.id}/wallet`, {
method: 'POST',
- headers: { 'content-type': 'application/json', ...csrf },
- credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ ...ANON,
body: JSON.stringify({ wallet_address: address, chain_id: chainId }),
});
} catch {}
@@ -169,12 +153,7 @@ export class AgentIdentity {
async unlinkWallet() {
await this.update({ walletAddress: null, chainId: null });
try {
- const csrf = await csrfHeaders();
- await fetch(`/api/agents/${this.id}/wallet`, {
- method: 'DELETE',
- headers: csrf,
- credentials: 'include',
- });
+ await apiFetch(`/api/agents/${this.id}/wallet`, { method: 'DELETE', ...ANON });
} catch {}
}
@@ -189,11 +168,10 @@ export class AgentIdentity {
if (!this._backendConfirmed) return; // no session — skip to avoid 401 noise
if (!this._owned) return; // viewing someone else's agent — backend would 403
try {
- const csrf = await csrfHeaders(); // cookie sessions require a CSRF token
- await fetch('/api/agent-actions', {
+ await apiFetch('/api/agent-actions', {
method: 'POST',
- headers: { 'content-type': 'application/json', ...csrf },
- credentials: 'include',
+ headers: { 'content-type': 'application/json' },
+ ...ANON,
body: JSON.stringify({
agent_id: this.id,
type: action.type,
@@ -214,7 +192,7 @@ export class AgentIdentity {
try {
const params = new URLSearchParams({ agent_id: this.id, limit: String(limit) });
if (cursor) params.set('cursor', cursor);
- const resp = await fetch(`/api/agent-actions?${params}`, { credentials: 'include' });
+ const resp = await apiFetch(`/api/agent-actions?${params}`, ANON);
if (!resp.ok) return [];
const { actions } = await resp.json();
return actions || [];
@@ -270,7 +248,7 @@ export class AgentIdentity {
const agentId = this._agentId;
const storedConfirmed = this._record?.backendConfirmed;
const url = (agentId && storedConfirmed) ? `/api/agents/${agentId}` : '/api/agents/me';
- const resp = await fetch(url, { credentials: 'include' });
+ const resp = await apiFetch(url, ANON);
if (resp.ok) {
const { agent } = await resp.json();
@@ -347,10 +325,10 @@ export class AgentIdentity {
function _makeEmbedFn(agentId) {
return async (text) => {
- const resp = await fetch(`/api/agents/${agentId}/embed`, {
+ const resp = await apiFetch(`/api/agents/${agentId}/embed`, {
method: 'POST',
headers: { 'content-type': 'application/json' },
- credentials: 'include',
+ ...ANON,
body: JSON.stringify({ text }),
});
if (!resp.ok) throw new Error(`embed ${resp.status}`);
diff --git a/src/avatar-page.js b/src/avatar-page.js
index 0337a8b03..df5a941f2 100644
--- a/src/avatar-page.js
+++ b/src/avatar-page.js
@@ -117,12 +117,33 @@ async function init() {
async function fetchAvatar(id) {
const r = await fetch(`/api/avatars/${encodeURIComponent(id)}`);
if (!r.ok) {
+ // A 404 may mean this id is actually an agent shared (or old-linked) as
+ // /avatars/:id. agent-detail.js does the reverse for avatar ids landing
+ // on /agents/:id — keep that symmetry so neither page dead-ends a valid
+ // entity behind "not found".
+ if (r.status === 404 && (await resolveAsAgent(id))) {
+ location.replace(`/agents/${encodeURIComponent(id)}`);
+ return new Promise(() => {}); // navigating away; never resolve
+ }
const j = await r.json().catch(() => ({}));
throw new Error(j.error_description || `Avatar not found (${r.status})`);
}
return (await r.json()).avatar;
}
+// Probe the agent store so a misrouted agent id can be handed back to the
+// agent detail page instead of rendering a dead "Avatar not found".
+async function resolveAsAgent(id) {
+ try {
+ const r = await fetch(`/api/agents/${encodeURIComponent(id)}`);
+ if (!r.ok) return false;
+ const j = await r.json();
+ return !!(j && j.agent);
+ } catch {
+ return false;
+ }
+}
+
async function fetchRelated() {
const url = new URL('/api/explore', location.origin);
url.searchParams.set('source', 'avatar');
@@ -572,10 +593,12 @@ function renderEmbedPanel(glbUrl) {
// ── View switcher ─────────────────────────────────────────────────────
// Surface the page-level views (3D · Chat · AR · Embed) in the action bar.
-// "Chat" is the active view when the page is opened on ?view=chat.
+// The active view tracks ?view= so Chat/Embed deep-links light up the right
+// segment; the bare page is the 3D view.
function mountSwitcher() {
if (isEmbed) return;
- const active = new URLSearchParams(location.search).get('view') === 'chat' ? 'chat' : '3d';
+ const view = new URLSearchParams(location.search).get('view');
+ const active = view === 'chat' || view === 'embed' ? view : '3d';
mountViewSwitcher($('view-switch-slot'), { kind: 'avatar', id: avatar.id || avatarId, active });
}
diff --git a/src/dashboard-next/pages/avatars.js b/src/dashboard-next/pages/avatars.js
index 4a2838852..148ae4e5b 100644
--- a/src/dashboard-next/pages/avatars.js
+++ b/src/dashboard-next/pages/avatars.js
@@ -277,7 +277,7 @@ function avatarCard(root, a) {
<div class="dn-av-thumb">
<threews-avatar avatar-id="${esc(a.id)}" hide-chrome bg="transparent"></threews-avatar>
<div class="dn-av-hover-actions">
- <a class="dn-av-hover-btn" href="/agents/${encodeURIComponent(a.id)}" target="_blank" rel="noopener">Live page</a>
+ <a class="dn-av-hover-btn" href="/avatars/${encodeURIComponent(a.id)}" target="_blank" rel="noopener">Live page</a>
<a class="dn-av-hover-btn" href="/app#avatar=${encodeURIComponent(a.id)}">3D Studio</a>
</div>
<button type="button" class="dn-av-more" data-more aria-haspopup="menu" aria-label="More actions">
@@ -395,7 +395,7 @@ function openMoreMenu(root, anchor, card, a) {
menu.dataset.for = a.id;
menu.setAttribute('role', 'menu');
const items = [
- { label: 'View live page', run: () => { window.open(`/agents/${encodeURIComponent(a.id)}`, '_blank'); } },
+ { label: 'View live page', run: () => { window.open(`/avatars/${encodeURIComponent(a.id)}`, '_blank'); } },
{ label: 'Update from selfie', run: async () => {
const result = await openSelfieModal({ existingAvatarId: a.id });
if (result?.avatarId) {
diff --git a/src/dashboard-next/pages/home.js b/src/dashboard-next/pages/home.js
index 881dc5230..8b2db52c1 100644
--- a/src/dashboard-next/pages/home.js
+++ b/src/dashboard-next/pages/home.js
@@ -585,7 +585,7 @@ function renderQuickActions(host, { avatars = [], agents = [] } = {}) {
const defaults = [];
if (firstAvatar) {
- defaults.push({ href: `/agents/${encodeURIComponent(firstAvatar.id)}`, title: 'View live agent page', sub: 'See how visitors experience your agent', iconKey: '/dashboard/agents', cat: 'Agents & Identity' });
+ defaults.push({ href: `/avatars/${encodeURIComponent(firstAvatar.id)}`, title: 'View live avatar page', sub: 'See how visitors experience your avatar', iconKey: '/dashboard/agents', cat: 'Agents & Identity' });
} else {
defaults.push({ href: '/create', title: 'Create avatar from selfie', sub: 'Snap a photo, get a 3D agent in 60 seconds', iconKey: '/create', cat: 'Create & Build' });
}
diff --git a/src/view-switcher.js b/src/view-switcher.js
index f94525c6f..9b4272d5f 100644
--- a/src/view-switcher.js
+++ b/src/view-switcher.js
@@ -36,7 +36,7 @@ function avatarViews(id) {
{ key: '3d', label: '3D', href: `/avatars/${e}`, title: '3D body & details' },
{ key: 'chat', label: 'Chat', href: `/avatars/${e}?view=chat`, title: 'Talk to this avatar' },
{ key: 'ar', label: 'AR', href: `/avatars/${e}/ar`, title: 'View in your space (AR)' },
- { key: 'embed', label: 'Embed', href: `/studio?avatar=${e}`, title: 'Build an embeddable widget' },
+ { key: 'embed', label: 'Embed', href: `/avatars/${e}?view=embed`, title: 'Embed this avatar anywhere' },
];
}
@@ -47,7 +47,7 @@ function agentViews(id, { worldHref } = {}) {
const e = encodeURIComponent(id);
const views = [{ key: 'detail', label: 'Detail', href: `/agents/${e}`, title: 'Agent profile & details' }];
if (worldHref) views.push({ key: '3d', label: '3D', href: worldHref, title: 'See this agent in 3D' });
- views.push({ key: 'embed', label: 'Embed', href: `/agent/${e}/embed`, title: 'Embeddable agent widget' });
+ views.push({ key: 'embed', label: 'Embed', href: `/agents/${e}?view=embed`, title: 'Embed this agent anywhere' });
return views;
}
diff --git a/tests/agent-identity-csrf.test.js b/tests/agent-identity-csrf.test.js
new file mode 100644
index 000000000..e968a5c33
--- /dev/null
+++ b/tests/agent-identity-csrf.test.js
@@ -0,0 +1,83 @@
+// Regression: agent action-log writes must carry a CSRF token.
+//
+// recordAction() once used a raw fetch() with no CSRF header, so every
+// owned-agent action POST to /api/agent-actions was rejected 403 csrf_missing
+// (visible as repeating 403s on the live widget). It now routes through
+// apiFetch (src/api.js), which attaches a fresh single-use token to every
+// mutation. These tests lock that in and guard the owner/anon gating.
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { AgentIdentity } from '../src/agent-identity.js';
+
+const CSRF = 'tok_deadbeef';
+
+function ownedIdentity() {
+ const id = new AgentIdentity({ agentId: 'agt_test', autoLoad: false });
+ id._record = { id: 'agt_test', skills: [], meta: {} };
+ id._backendConfirmed = true;
+ id._owned = true;
+ return id;
+}
+
+describe('agent-identity CSRF', () => {
+ let calls;
+
+ beforeEach(() => {
+ calls = [];
+ globalThis.fetch = vi.fn(async (path, init = {}) => {
+ calls.push({ path: String(path), init });
+ if (String(path).includes('/api/csrf-token')) {
+ return new Response(JSON.stringify({ data: { token: CSRF } }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ });
+ }
+ return new Response(JSON.stringify({ action: { id: '1' } }), {
+ status: 201,
+ headers: { 'content-type': 'application/json' },
+ });
+ });
+ });
+
+ afterEach(() => {
+ vi.restoreAllMocks();
+ delete globalThis.fetch;
+ });
+
+ it('recordAction attaches an x-csrf-token header to the append POST', async () => {
+ await ownedIdentity().recordAction({ type: 'view', payload: { x: 1 } });
+
+ const post = calls.find((c) => c.path.includes('/api/agent-actions'));
+ expect(post, 'expected a POST to /api/agent-actions').toBeTruthy();
+ expect(post.init.method).toBe('POST');
+
+ const headers = new Headers(post.init.headers);
+ expect(headers.get('x-csrf-token')).toBe(CSRF);
+ expect(headers.get('content-type')).toBe('application/json');
+ expect(post.init.credentials).toBe('include'); // apiFetch carries the session cookie
+
+ const body = JSON.parse(post.init.body);
+ expect(body).toMatchObject({ agent_id: 'agt_test', type: 'view' });
+ });
+
+ it('recordAction is a no-op when the session does not own the agent', async () => {
+ const id = ownedIdentity();
+ id._owned = false; // viewing someone else's agent
+ await id.recordAction({ type: 'view', payload: {} });
+ expect(calls).toHaveLength(0);
+ });
+
+ it('recordAction is a no-op before the backend confirms a session', async () => {
+ const id = ownedIdentity();
+ id._backendConfirmed = false;
+ await id.recordAction({ type: 'view', payload: {} });
+ expect(calls).toHaveLength(0);
+ });
+
+ it('recordAction swallows backend failures (fire-and-forget)', async () => {
+ globalThis.fetch = vi.fn(async () => {
+ throw new Error('network down');
+ });
+ await expect(ownedIdentity().recordAction({ type: 'view', payload: {} })).resolves.toBeUndefined();
+ });
+});
diff --git a/tests/api/mcp-3d.test.js b/tests/api/mcp-3d.test.js
index 7e0c9e4e8..c6f28abe2 100644
--- a/tests/api/mcp-3d.test.js
+++ b/tests/api/mcp-3d.test.js
@@ -56,7 +56,7 @@ vi.mock('../../api/_lib/usage.js', () => ({
logger: () => ({ info: () => {}, warn: () => {}, error: () => {} }),
}));
-const { dispatch } = await import('../../api/_mcp3d/dispatch.js');
+const { dispatch, isPublicTool } = await import('../../api/_mcp3d/dispatch.js');
const AUTH = { userId: null, rateKey: 'test', scope: '', source: 'x402' };
const call = (name, args) =>
@@ -93,6 +93,27 @@ describe('3D Studio MCP', () => {
expect(r.result.protocolVersion).toBe('2025-06-18');
});
+ it('exposes a free getting_started tool with no scope or pricing', async () => {
+ const r = await dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, AUTH);
+ const gs = r.result.tools.find((t) => t.name === 'getting_started');
+ expect(gs).toBeTruthy();
+ expect(gs.pricing).toBeUndefined();
+ expect(isPublicTool('getting_started')).toBe(true);
+ expect(isPublicTool('text_to_3d')).toBe(false);
+ });
+
+ it('getting_started returns an overview listing the studio tools — no auth needed', async () => {
+ const r = await dispatch(
+ { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'getting_started', arguments: {} } },
+ { userId: null, rateKey: null, scope: '', source: 'free' },
+ );
+ const out = r.result.structuredContent;
+ expect(out.ok).toBe(true);
+ expect(out.server).toBe('three.ws 3D Studio');
+ expect(out.tools.map((t) => t.name)).toEqual(expect.arrayContaining(['text_to_3d', 'image_to_3d']));
+ expect(r.result.content[0].text).toContain('Getting Started');
+ });
+
it('text_to_3d runs text→image then submits a reconstruction job', async () => {
const r = await call('text_to_3d', { prompt: 'a low-poly red fox' });
expect(t2iState.fn).toHaveBeenCalledWith('a low-poly red fox', { aspectRatio: '1:1' });
diff --git a/tests/api/mcp-agent.test.js b/tests/api/mcp-agent.test.js
index a31a66b0d..de292c99b 100644
--- a/tests/api/mcp-agent.test.js
+++ b/tests/api/mcp-agent.test.js
@@ -41,7 +41,7 @@ vi.mock('../../api/_lib/usage.js', () => ({
}));
const payer = await import('../../api/_lib/x402-user-payer.js');
-const { dispatch } = await import('../../api/_mcpagent/dispatch.js');
+const { dispatch, isPublicTool } = await import('../../api/_mcpagent/dispatch.js');
const ANON = { userId: null, rateKey: 'x402:anon', scope: '', source: 'x402' };
const USER = { userId: 'user-1', rateKey: 'user-1', scope: 'wallet:read', source: 'bearer' };
@@ -61,9 +61,10 @@ beforeEach(() => {
});
describe('threews-agent MCP', () => {
- it('lists the wallet toolset', async () => {
+ it('lists the wallet toolset behind a free getting_started tool', async () => {
const r = await dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, USER);
expect(r.result.tools.map((t) => t.name)).toEqual([
+ 'getting_started',
'wallet_status',
'find_services',
'pay_and_call',
@@ -72,6 +73,19 @@ describe('threews-agent MCP', () => {
]);
});
+ it('getting_started is free and callable with no sign-in', async () => {
+ expect(isPublicTool('getting_started')).toBe(true);
+ expect(isPublicTool('pay_and_call')).toBe(false);
+ const r = await dispatch(
+ { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'getting_started', arguments: {} } },
+ { userId: null, rateKey: null, scope: '', source: 'free' },
+ );
+ expect(r.result.structuredContent.server).toBe('three.ws Agent');
+ expect(r.result.structuredContent.tools.map((t) => t.name)).toEqual(
+ expect.arrayContaining(['wallet_status', 'pay_and_call']),
+ );
+ });
+
it('wallet_status requires sign-in', async () => {
const r = await call('wallet_status', {}, ANON);
expect(r.result.isError).toBe(true);
diff --git a/tests/api/mcp-bazaar.test.js b/tests/api/mcp-bazaar.test.js
index e25d1c24e..75fd8924a 100644
--- a/tests/api/mcp-bazaar.test.js
+++ b/tests/api/mcp-bazaar.test.js
@@ -38,7 +38,7 @@ vi.mock('../../api/_lib/usage.js', () => ({
logger: () => ({ info: () => {}, warn: () => {}, error: () => {} }),
}));
-const { dispatch } = await import('../../api/_mcpbazaar/dispatch.js');
+const { dispatch, isPublicTool } = await import('../../api/_mcpbazaar/dispatch.js');
const AUTH = { userId: null, rateKey: 'test', scope: '', source: 'x402' };
const call = (name, args) =>
@@ -83,15 +83,29 @@ beforeEach(() => {
});
describe('x402 Bazaar MCP', () => {
- it('exposes the discovery toolset', async () => {
+ it('exposes the discovery toolset behind a free getting_started tool', async () => {
const r = await dispatch({ jsonrpc: '2.0', id: 1, method: 'tools/list' }, AUTH);
expect(r.result.tools.map((t) => t.name)).toEqual([
+ 'getting_started',
'search_services',
'browse_services',
'get_service',
]);
});
+ it('getting_started is free and callable with no auth', async () => {
+ expect(isPublicTool('getting_started')).toBe(true);
+ expect(isPublicTool('search_services')).toBe(false);
+ const r = await dispatch(
+ { jsonrpc: '2.0', id: 1, method: 'tools/call', params: { name: 'getting_started', arguments: {} } },
+ { userId: null, rateKey: null, scope: '', source: 'free' },
+ );
+ expect(r.result.structuredContent.server).toBe('three.ws x402 Bazaar');
+ expect(r.result.structuredContent.tools.map((t) => t.name)).toEqual(
+ expect.arrayContaining(['search_services', 'get_service']),
+ );
+ });
+
it('search_services returns ranked, slimmed services', async () => {
bazState.search.mockResolvedValue({ resources: [item()], sources: [{ ok: true }], errors: [] });
const r = await call('search_services', { query: 'weather' });
diff --git a/tests/api/providers-replicate.test.js b/tests/api/providers-replicate.test.js
new file mode 100644
index 000000000..b580895cc
--- /dev/null
+++ b/tests/api/providers-replicate.test.js
@@ -0,0 +1,140 @@
+// Tests for the Replicate avatar-reconstruction provider.
+//
+// Regression cover for the two TRELLIS contract bugs that made the selfie → 3D
+// pipeline silently produce nothing:
+// • TRELLIS `generate_model` defaults to FALSE, so the prediction "succeeds"
+// but returns no GLB unless we explicitly ask for one. The provider must
+// send generate_model:true for TRELLIS-family models.
+// • TRELLIS emits the mesh under the `model_file` output key, which the GLB
+// extractor previously ignored. extractGlbUrl must resolve `model_file`.
+//
+// Also guards the model-awareness boundary: TRELLIS-only flags must NOT leak to
+// a non-TRELLIS model (e.g. Hunyuan3D), where they would 422 against its schema.
+//
+// We stub global fetch to capture the submitted prediction body and to model
+// Replicate's predictions API responses.
+
+import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
+
+const ORIGINAL_FETCH = globalThis.fetch;
+const ORIGINAL_TOKEN = process.env.REPLICATE_API_TOKEN;
+const ORIGINAL_RECONSTRUCT = process.env.REPLICATE_RECONSTRUCT_MODEL;
+const ORIGINAL_WEBHOOK = process.env.REPLICATE_WEBHOOK_URL;
+const ORIGINAL_ORIGIN = process.env.APP_ORIGIN;
+
+async function freshProvider() {
+ // Import fresh each time so module-level env reads don't bleed across cases.
+ const mod = await import('../../api/_providers/replicate.js?t=' + Math.random());
+ return mod.createRegenProvider();
+}
+
+// Capture the POST body sent to Replicate and reply with a queued prediction.
+function stubSubmit() {
+ const calls = [];
+ globalThis.fetch = vi.fn(async (url, opts) => {
+ calls.push({ url: String(url), body: JSON.parse(opts.body) });
+ return new Response(JSON.stringify({ id: 'pred_123', status: 'starting' }), {
+ status: 201,
+ headers: { 'content-type': 'application/json' },
+ });
+ });
+ return calls;
+}
+
+beforeEach(() => {
+ process.env.REPLICATE_API_TOKEN = 'r8_test_token';
+ delete process.env.REPLICATE_RECONSTRUCT_MODEL;
+ delete process.env.REPLICATE_WEBHOOK_URL;
+ delete process.env.APP_ORIGIN;
+});
+
+afterEach(() => {
+ globalThis.fetch = ORIGINAL_FETCH;
+ if (ORIGINAL_TOKEN === undefined) delete process.env.REPLICATE_API_TOKEN;
+ else process.env.REPLICATE_API_TOKEN = ORIGINAL_TOKEN;
+ if (ORIGINAL_RECONSTRUCT === undefined) delete process.env.REPLICATE_RECONSTRUCT_MODEL;
+ else process.env.REPLICATE_RECONSTRUCT_MODEL = ORIGINAL_RECONSTRUCT;
+ if (ORIGINAL_WEBHOOK === undefined) delete process.env.REPLICATE_WEBHOOK_URL;
+ else process.env.REPLICATE_WEBHOOK_URL = ORIGINAL_WEBHOOK;
+ if (ORIGINAL_ORIGIN === undefined) delete process.env.APP_ORIGIN;
+ else process.env.APP_ORIGIN = ORIGINAL_ORIGIN;
+ vi.restoreAllMocks();
+});
+
+describe('replicate provider — TRELLIS reconstruct input', () => {
+ it('sends generate_model:true (the default model would emit no GLB otherwise)', async () => {
+ const calls = stubSubmit();
+ const provider = await freshProvider();
+ await provider.submit({
+ mode: 'reconstruct',
+ params: { images: ['https://img/a.jpg'] },
+ sourceUrl: 'https://img/a.jpg',
+ });
+ expect(calls).toHaveLength(1);
+ // Default model is the firtoz/trellis slug → /models/.../predictions.
+ expect(calls[0].url).toContain('/models/firtoz/trellis/predictions');
+ const input = calls[0].body.input;
+ expect(input.generate_model).toBe(true);
+ expect(input.images).toEqual(['https://img/a.jpg']);
+ // Video/ply outputs are disabled to halve GPU cost — we only consume the mesh.
+ expect(input.generate_color).toBe(false);
+ });
+
+ it('lets caller params override the TRELLIS defaults', async () => {
+ const calls = stubSubmit();
+ const provider = await freshProvider();
+ await provider.submit({
+ mode: 'reconstruct',
+ params: { images: ['https://img/a.jpg'], generate_color: true, texture_size: 2048 },
+ sourceUrl: 'https://img/a.jpg',
+ });
+ const input = calls[0].body.input;
+ expect(input.generate_model).toBe(true); // still forced on
+ expect(input.generate_color).toBe(true); // caller wins
+ expect(input.texture_size).toBe(2048);
+ });
+
+ it('does NOT leak generate_model to a non-TRELLIS model (would 422)', async () => {
+ process.env.REPLICATE_RECONSTRUCT_MODEL = 'tencent/hunyuan3d-2';
+ const calls = stubSubmit();
+ const provider = await freshProvider();
+ await provider.submit({
+ mode: 'reconstruct',
+ params: { images: ['https://img/a.jpg'] },
+ sourceUrl: 'https://img/a.jpg',
+ });
+ const input = calls[0].body.input;
+ expect(input).not.toHaveProperty('generate_model');
+ expect(input).not.toHaveProperty('generate_color');
+ expect(input.images).toEqual(['https://img/a.jpg']);
+ });
+});
+
+describe('replicate provider — GLB extraction from status', () => {
+ function stubStatus(output) {
+ globalThis.fetch = vi.fn(async () =>
+ new Response(JSON.stringify({ id: 'pred_123', status: 'succeeded', output }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ }),
+ );
+ }
+
+ it('resolves the GLB from the TRELLIS `model_file` output key', async () => {
+ stubStatus({ model_file: 'https://cdn/replicate/output.glb', color_video: null });
+ const provider = await freshProvider();
+ const res = await provider.status('pred_123');
+ expect(res.status).toBe('done');
+ expect(res.resultGlbUrl).toBe('https://cdn/replicate/output.glb');
+ expect(res.error).toBeUndefined();
+ });
+
+ it('reports a clear error when a finished prediction carries no GLB', async () => {
+ stubStatus({ color_video: 'https://cdn/replicate/render.mp4' });
+ const provider = await freshProvider();
+ const res = await provider.status('pred_123');
+ expect(res.status).toBe('done');
+ expect(res.resultGlbUrl).toBeUndefined();
+ expect(res.error).toMatch(/no GLB/i);
+ });
+});
diff --git a/tests/e2e/create-agent-avatar.spec.js b/tests/e2e/create-agent-avatar.spec.js
new file mode 100644
index 000000000..62be80cfc
--- /dev/null
+++ b/tests/e2e/create-agent-avatar.spec.js
@@ -0,0 +1,140 @@
+/**
+ * Create-agent wizard — avatar step smoke.
+ *
+ * Verifies the "every agent gets a 3D body" rules added to step 2:
+ * • the four model tabs render (Starter / My avatars / Upload / Add later)
+ * • the step blocks advancing until a real choice is made
+ * • the "My avatars" tab loads the caller's library and lets you connect one
+ * • the "Add later" path is gated behind an explicit acknowledgment, after
+ * which the agent will launch with the default body
+ *
+ * Auth + the avatars list are fulfilled from the Playwright route layer so the
+ * client-side step logic can be exercised without a live session/DB. These are
+ * test fixtures for the harness — the product code still calls the real
+ * /api/auth/me and /api/avatars endpoints.
+ */
+
+import { test, expect } from '@playwright/test';
+
+const FIXTURE_USER = {
+ id: 'usr_e2e_creator',
+ handle: 'e2e-creator',
+ display_name: 'E2E Creator',
+ plan: 'free',
+};
+
+// Synthetic avatars — real shipped GLBs for the model URL, a real served PNG
+// for the thumbnail so tiles render as <img> without booting model-viewer.
+const FIXTURE_AVATARS = [
+ {
+ id: 'ava-e2e-one',
+ name: 'Test Avatar One',
+ url: '/avatars/default.glb',
+ thumbnail_url: '/favicon-32x32.png',
+ },
+ {
+ id: 'ava-e2e-two',
+ name: 'Test Avatar Two',
+ url: '/avatars/cz.glb',
+ thumbnail_url: '/favicon-32x32.png',
+ },
+];
+
+async function installFixtures(page) {
+ await page.route('**/api/auth/me**', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({ user: FIXTURE_USER }),
+ }),
+ );
+ await page.route('**/api/avatars?**', (route) =>
+ route.fulfill({
+ status: 200,
+ contentType: 'application/json',
+ body: JSON.stringify({ avatars: FIXTURE_AVATARS }),
+ }),
+ );
+}
+
+/** Advance from the Basics step into the 3D-model step with a valid name. */
+async function gotoModelStep(page) {
+ await page.goto('/create-agent');
+ const name = page.locator('#f-name');
+ await name.waitFor({ state: 'visible', timeout: 30_000 });
+ await name.fill('E2E Test Agent');
+ await page.locator('#btn-next').click();
+ await expect(page.locator('.panel[data-step="1"].is-active')).toBeVisible();
+}
+
+test.describe('create-agent / avatar step', () => {
+ test.beforeEach(async ({ page }) => {
+ page.on('pageerror', (err) => {
+ // Ignore Vite's dev-only HMR socket noise — not a product error.
+ if (/WebSocket closed without opened/i.test(err.message)) return;
+ throw new Error(`Uncaught page error: ${err.message}`);
+ });
+ await installFixtures(page);
+ });
+
+ test('renders all four model tabs', async ({ page }) => {
+ test.setTimeout(90_000);
+ await gotoModelStep(page);
+
+ const tabs = page.locator('.model-tab');
+ await expect(tabs).toHaveCount(4);
+ await expect(page.locator('.model-tab[data-pane="starter"]')).toHaveText('Starter library');
+ await expect(page.locator('.model-tab[data-pane="library"]')).toHaveText('My avatars');
+ await expect(page.locator('.model-tab[data-pane="upload"]')).toHaveText('Upload your own');
+ await expect(page.locator('.model-tab[data-pane="skip"]')).toHaveText('Add later');
+ });
+
+ test('blocks advancing with no avatar chosen', async ({ page }) => {
+ test.setTimeout(90_000);
+ await gotoModelStep(page);
+
+ await page.locator('#btn-next').click();
+
+ // Still on the model step, with an error prompting a choice.
+ await expect(page.locator('.panel[data-step="1"].is-active')).toBeVisible();
+ await expect(page.locator('#foot-msg.err')).toContainText('Pick a starter avatar');
+ });
+
+ test('connects an avatar from "My avatars" and advances', async ({ page }) => {
+ test.setTimeout(90_000);
+ await gotoModelStep(page);
+
+ await page.locator('.model-tab[data-pane="library"]').click();
+
+ // Tiles render from the (fixtured) library feed.
+ const tiles = page.locator('#library-grid .starter');
+ await expect(tiles).toHaveCount(FIXTURE_AVATARS.length);
+ await expect(tiles.first()).toContainText('Test Avatar One');
+
+ await tiles.first().click();
+ await expect(tiles.first()).toHaveClass(/is-selected/);
+
+ // A connected avatar satisfies the step — Next advances to Skills.
+ await page.locator('#btn-next').click();
+ await expect(page.locator('.panel[data-step="2"].is-active')).toBeVisible();
+ });
+
+ test('"Add later" requires acknowledgment, then uses the default body', async ({ page }) => {
+ test.setTimeout(90_000);
+ await gotoModelStep(page);
+
+ await page.locator('.model-tab[data-pane="skip"]').click();
+
+ // Without the acknowledgment, the step is blocked.
+ await page.locator('#btn-next').click();
+ await expect(page.locator('.panel[data-step="1"].is-active')).toBeVisible();
+ await expect(page.locator('#foot-msg.err')).toContainText('default 3D body');
+
+ // Acknowledge via the visible toggle (the native input is CSS-covered by
+ // the track), then the step clears and advances.
+ await page.locator('.model-pane[data-pane="skip"] label.toggle').click();
+ await expect(page.locator('#f-skip-ack')).toBeChecked();
+ await page.locator('#btn-next').click();
+ await expect(page.locator('.panel[data-step="2"].is-active')).toBeVisible();
+ });
+});