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.

chore: optimize GLB avatars, harden API handlers, add glb optimizer script

nirholas4f6735809cfd
diff --git a/.gitignore b/.gitignore
index b9d86083a..1613013b3 100644
--- a/.gitignore
+++ b/.gitignore
@@ -70,3 +70,6 @@ threews-launch-week-case-study.html
# Temp working directories
.tmp/
+
+# GLB optimization backups (see scripts/optimize-glb.mjs)
+*.glb.bak
diff --git a/agent-detail.html b/agent-detail.html
index 50d9afc51..d0cbb6a6c 100644
--- a/agent-detail.html
+++ b/agent-detail.html
@@ -188,26 +188,6 @@
<div id="ad-token-body" class="ad-muted">No agent token linked for this agent yet.</div>
</section>
- <section class="ad-card">
- <div class="ad-card-head">
- <span class="ad-bullet ad-bullet-red"></span>
- <h2>LIVESTREAM</h2>
- <span class="ad-pill ad-pill-live">LIVE</span>
- </div>
- <div class="ad-livestream-embed">
- <!-- Replace with your livestream embed code (e.g., from Twitch or YouTube) -->
- <iframe
- width="100%"
- height="100%"
- src="https://www.youtube.com/embed/dQw4w9WgXcQ?autoplay=1"
- title="Livestream"
- frameborder="0"
- allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
- allowfullscreen
- ></iframe>
- </div>
- </section>
-
<section class="ad-card">
<div class="ad-card-head">
<span class="ad-bullet ad-bullet-green"></span>
diff --git a/api/admin/user/[id].js b/api/admin/user/[id].js
index 8661fe348..070195d30 100644
--- a/api/admin/user/[id].js
+++ b/api/admin/user/[id].js
@@ -48,16 +48,37 @@ export default wrap(async (req, res) => {
// PATCH
const body = parse(patchSchema, await readJson(req));
- const sets = [];
- if (body.plan !== undefined) sets.push(sql`plan = ${body.plan}`);
- if (body.is_admin !== undefined) sets.push(sql`is_admin = ${body.is_admin}`);
- if (body.deleted !== undefined) sets.push(sql`deleted_at = ${body.deleted ? sql`now()` : null}`);
-
- const [updated] = await sql`
- update users set ${sql(sets.reduce((a, b) => sql`${a}, ${b}`))}
- where id = ${id}
+ const setFrags = [];
+ const params = [];
+ if (body.plan !== undefined) {
+ params.push(body.plan);
+ setFrags.push(`plan = $${params.length}`);
+ }
+ if (body.is_admin !== undefined) {
+ params.push(body.is_admin);
+ setFrags.push(`is_admin = $${params.length}`);
+ }
+ if (body.deleted !== undefined) {
+ if (body.deleted) {
+ setFrags.push(`deleted_at = now()`);
+ } else {
+ setFrags.push(`deleted_at = NULL`);
+ }
+ }
+
+ if (setFrags.length === 0) return error(res, 400, 'validation_error', 'nothing to update');
+
+ params.push(id);
+ const idIdx = params.length;
+
+ const [updated] = await sql(
+ `
+ update users set ${setFrags.join(', ')}
+ where id = $${idIdx}
returning id, email, display_name, plan, is_admin, deleted_at
- `;
+ `,
+ params,
+ );
if (!updated) return error(res, 404, 'not_found', 'user not found');
return json(res, 200, { user: updated });
});
diff --git a/api/agents.js b/api/agents.js
index 08fde9407..5b2e7e5ef 100644
--- a/api/agents.js
+++ b/api/agents.js
@@ -74,15 +74,14 @@ async function handleList(req, res) {
if (isMe) return handleGetOrCreateMe(req, res, auth);
- const onchainFilter = onchainOnly ? sql`AND (erc8004_agent_id IS NOT NULL OR meta->>'onchain' IS NOT NULL)` : sql``;
-
- const rows = await sql`
+ const text = `
SELECT * FROM agent_identities
- WHERE user_id = ${auth.userId}
+ WHERE user_id = $1
AND deleted_at IS NULL
- ${onchainFilter}
+ ${onchainOnly ? `AND (erc8004_agent_id IS NOT NULL OR meta->>'onchain' IS NOT NULL)` : ''}
ORDER BY created_at ASC
`;
+ const rows = await sql(text, [auth.userId]);
return json(res, 200, { agents: rows.map((row) => decorate(row)) });
}
diff --git a/api/billing/revenue.js b/api/billing/revenue.js
index c6bf46563..edd28403b 100644
--- a/api/billing/revenue.js
+++ b/api/billing/revenue.js
@@ -37,9 +37,12 @@ export default wrap(async (req, res) => {
if (isNaN(toDate.getTime()))
return error(res, 400, 'validation_error', 'to must be a valid ISO-8601 date');
- const agentFilter = agentId ? sql`AND re.agent_id = ${agentId}::uuid` : sql``;
+ const baseParams = [user.id, fromDate, toDate];
+ const agentFilterSql = agentId ? `AND re.agent_id = $4::uuid` : '';
+ const filterParams = agentId ? [...baseParams, agentId] : baseParams;
- const [summaryRow] = await sql`
+ const [summaryRow] = await sql(
+ `
SELECT
COALESCE(SUM(re.gross_amount), 0)::bigint AS gross_total,
COALESCE(SUM(re.fee_amount), 0)::bigint AS fee_total,
@@ -49,38 +52,50 @@ export default wrap(async (req, res) => {
MAX(re.chain) AS chain
FROM agent_revenue_events re
JOIN agent_identities ai ON ai.id = re.agent_id
- WHERE ai.user_id = ${user.id}
- AND re.created_at BETWEEN ${fromDate} AND ${toDate}
- ${agentFilter}
- `;
+ WHERE ai.user_id = $1
+ AND re.created_at BETWEEN $2 AND $3
+ ${agentFilterSql}
+ `,
+ filterParams,
+ );
- const bySkill = await sql`
+ const bySkill = await sql(
+ `
SELECT
re.skill,
COALESCE(SUM(re.net_amount), 0)::bigint AS net_total,
COUNT(*)::int AS count
FROM agent_revenue_events re
JOIN agent_identities ai ON ai.id = re.agent_id
- WHERE ai.user_id = ${user.id}
- AND re.created_at BETWEEN ${fromDate} AND ${toDate}
- ${agentFilter}
+ WHERE ai.user_id = $1
+ AND re.created_at BETWEEN $2 AND $3
+ ${agentFilterSql}
GROUP BY re.skill
ORDER BY net_total DESC
- `;
+ `,
+ filterParams,
+ );
- const timeseries = await sql`
+ const tsParams = agentId
+ ? [user.id, fromDate, toDate, granularity, agentId]
+ : [user.id, fromDate, toDate, granularity];
+ const tsAgentFilter = agentId ? `AND re.agent_id = $5::uuid` : '';
+ const timeseries = await sql(
+ `
SELECT
- date_trunc(${granularity}, re.created_at) AS period,
+ date_trunc($4, re.created_at) AS period,
COALESCE(SUM(re.net_amount), 0)::bigint AS net_total,
COUNT(*)::int AS count
FROM agent_revenue_events re
JOIN agent_identities ai ON ai.id = re.agent_id
- WHERE ai.user_id = ${user.id}
- AND re.created_at BETWEEN ${fromDate} AND ${toDate}
- ${agentFilter}
+ WHERE ai.user_id = $1
+ AND re.created_at BETWEEN $2 AND $3
+ ${tsAgentFilter}
GROUP BY period
ORDER BY period
- `;
+ `,
+ tsParams,
+ );
return json(res, 200, {
summary: {
diff --git a/api/cron/[name].js b/api/cron/[name].js
index b36b8cca6..83cd6e199 100644
--- a/api/cron/[name].js
+++ b/api/cron/[name].js
@@ -1287,6 +1287,14 @@ function dcaLog(level, event, fields = {}) {
else console.log(line);
}
+async function insertDcaExecution(row) {
+ const keys = Object.keys(row);
+ const cols = keys.map((k) => `"${k}"`).join(', ');
+ const placeholders = keys.map((_, i) => `$${i + 1}`).join(', ');
+ const values = keys.map((k) => row[k]);
+ return sql(`INSERT INTO dca_executions (${cols}) VALUES (${placeholders})`, values);
+}
+
function dcaIsTransient(err) {
// Network-level & RPC transport errors
const code = err?.code;
@@ -1572,7 +1580,7 @@ async function handleRunDca(req, res) {
`;
execRow.status = 'aborted';
execRow.error = `Delegation ${strategy.delegation_status}`;
- await sql`INSERT INTO dca_executions ${sql(execRow)}`.catch((e) =>
+ await insertDcaExecution(execRow).catch((e) =>
dcaLog('error', 'exec_insert_failed', { ...logCtx, message: e?.message }),
);
dcaLog('info', 'skipped', { ...logCtx, reason: execRow.error });
@@ -1586,7 +1594,7 @@ async function handleRunDca(req, res) {
`;
execRow.status = 'aborted';
execRow.error = 'Delegation expired';
- await sql`INSERT INTO dca_executions ${sql(execRow)}`.catch((e) =>
+ await insertDcaExecution(execRow).catch((e) =>
dcaLog('error', 'exec_insert_failed', { ...logCtx, message: e?.message }),
);
dcaLog('info', 'skipped', { ...logCtx, reason: execRow.error });
@@ -1672,7 +1680,7 @@ async function handleRunDca(req, res) {
}
// Insert execution record regardless of outcome
- await sql`INSERT INTO dca_executions ${sql(execRow)}`.catch((e) =>
+ await insertDcaExecution(execRow).catch((e) =>
dcaLog('error', 'exec_insert_failed', { ...logCtx, message: e?.message }),
);
}
diff --git a/api/skills/[id].js b/api/skills/[id].js
index e689b2049..7cdb31af4 100644
--- a/api/skills/[id].js
+++ b/api/skills/[id].js
@@ -123,22 +123,41 @@ async function handleUpdate(req, res, id) {
return error(res, 400, 'validation_error', 'no fields to update');
}
- const updates = [];
- if (body.name !== undefined) updates.push(sql`name = ${body.name}`);
- if (body.description !== undefined) updates.push(sql`description = ${body.description}`);
- if (body.tags !== undefined) updates.push(sql`tags = ${body.tags}`);
- if (body.is_public !== undefined) updates.push(sql`is_public = ${body.is_public}`);
- if (body.schema_json !== undefined)
- updates.push(sql`schema_json = ${JSON.stringify(body.schema_json)}::jsonb`);
- if (body.content !== undefined)
- updates.push(sql`content = ${body.content}`);
- updates.push(sql`updated_at = now()`);
-
- const setClauses = updates.reduce((acc, frag) => sql`${acc}, ${frag}`);
-
- const [updated] = await sql`
- UPDATE marketplace_skills SET ${setClauses} WHERE id = ${id} RETURNING *
- `;
+ const setFrags = [];
+ const params = [];
+ if (body.name !== undefined) {
+ params.push(body.name);
+ setFrags.push(`name = $${params.length}`);
+ }
+ if (body.description !== undefined) {
+ params.push(body.description);
+ setFrags.push(`description = $${params.length}`);
+ }
+ if (body.tags !== undefined) {
+ params.push(body.tags);
+ setFrags.push(`tags = $${params.length}`);
+ }
+ if (body.is_public !== undefined) {
+ params.push(body.is_public);
+ setFrags.push(`is_public = $${params.length}`);
+ }
+ if (body.schema_json !== undefined) {
+ params.push(JSON.stringify(body.schema_json));
+ setFrags.push(`schema_json = $${params.length}::jsonb`);
+ }
+ if (body.content !== undefined) {
+ params.push(body.content);
+ setFrags.push(`content = $${params.length}`);
+ }
+ setFrags.push(`updated_at = now()`);
+
+ params.push(id);
+ const idIdx = params.length;
+
+ const [updated] = await sql(
+ `UPDATE marketplace_skills SET ${setFrags.join(', ')} WHERE id = $${idIdx} RETURNING *`,
+ params,
+ );
const [author] = updated.author_id
? await sql`SELECT id, display_name FROM users WHERE id = ${updated.author_id}`
diff --git a/api/subscriptions/plans.js b/api/subscriptions/plans.js
index 1c8cea6c2..b40bc34e8 100644
--- a/api/subscriptions/plans.js
+++ b/api/subscriptions/plans.js
@@ -128,20 +128,41 @@ async function handlePatch(req, res, planId) {
`;
if (!existing) return error(res, 404, 'not_found', 'plan not found');
- const sets = [];
- if (body.name !== undefined) sets.push(sql`name = ${body.name}`);
- if (body.price_usd !== undefined) sets.push(sql`price_usd = ${body.price_usd}`);
- if (body.perks !== undefined) sets.push(sql`perks = ${body.perks}`);
- if (body.active !== undefined) sets.push(sql`active = ${body.active}`);
+ const setFrags = [];
+ const params = [];
+ if (body.name !== undefined) {
+ params.push(body.name);
+ setFrags.push(`name = $${params.length}`);
+ }
+ if (body.price_usd !== undefined) {
+ params.push(body.price_usd);
+ setFrags.push(`price_usd = $${params.length}`);
+ }
+ if (body.perks !== undefined) {
+ params.push(body.perks);
+ setFrags.push(`perks = $${params.length}`);
+ }
+ if (body.active !== undefined) {
+ params.push(body.active);
+ setFrags.push(`active = $${params.length}`);
+ }
- if (sets.length === 0) return error(res, 400, 'validation_error', 'nothing to update');
+ if (setFrags.length === 0) return error(res, 400, 'validation_error', 'nothing to update');
- const [plan] = await sql`
+ params.push(planId);
+ const planIdIdx = params.length;
+ params.push(user.id);
+ const userIdIdx = params.length;
+
+ const [plan] = await sql(
+ `
UPDATE subscription_plans
- SET ${sql(sets.reduce((a, b) => sql`${a}, ${b}`))}
- WHERE id = ${planId} AND creator_id = ${user.id}
+ SET ${setFrags.join(', ')}
+ WHERE id = $${planIdIdx} AND creator_id = $${userIdIdx}
RETURNING id, creator_id, agent_id, name, price_usd, interval, perks, active, created_at
- `;
+ `,
+ params,
+ );
return json(res, 200, { plan });
}
diff --git a/api/x402-pay.js b/api/x402-pay.js
index 52f081ecf..b7200f066 100644
--- a/api/x402-pay.js
+++ b/api/x402-pay.js
@@ -216,7 +216,24 @@ function loadAgentKeypair() {
if (_agent) return _agent;
const b58 = process.env.X402_AGENT_SOLANA_SECRET_BASE58;
if (b58) {
- _agent = Keypair.fromSecretKey(bs58.decode(b58));
+ let raw;
+ try {
+ raw = bs58.decode(b58);
+ } catch {
+ const e = new Error('X402_AGENT_SOLANA_SECRET_BASE58 is not valid base58');
+ e.status = 503;
+ e.code = 'wallet_misconfigured';
+ throw e;
+ }
+ if (raw.length !== 64) {
+ const e = new Error(
+ `X402_AGENT_SOLANA_SECRET_BASE58 decoded to ${raw.length} bytes; expected 64 (ed25519 keypair)`,
+ );
+ e.status = 503;
+ e.code = 'wallet_misconfigured';
+ throw e;
+ }
+ _agent = Keypair.fromSecretKey(raw);
return _agent;
}
try {
@@ -226,7 +243,8 @@ function loadAgentKeypair() {
return _agent;
} catch {
const e = new Error('agent wallet not configured (set X402_AGENT_SOLANA_SECRET_BASE58)');
- e.status = 500;
+ e.status = 503;
+ e.code = 'wallet_unconfigured';
throw e;
}
}
@@ -432,8 +450,14 @@ export default wrap(async (req, res) => {
if (u.searchParams.get('balance') === '1') {
try {
const b = await getAgentBalance();
- return json(res, 200, b);
+ return json(res, 200, { configured: true, ...b });
} catch (err) {
+ // Wallet config problems are surfaced as a 200 with a flag so
+ // the demo UI can render "wallet not configured" instead of a
+ // red console error. Other failures still bubble as 500.
+ if (err.code === 'wallet_misconfigured' || err.code === 'wallet_unconfigured') {
+ return json(res, 200, { configured: false, error: err.message, address: null, sol: 0, usdc: 0 });
+ }
return json(res, err.status || 500, { error: err.message });
}
}
diff --git a/cors.json b/cors.json
index a10171f52..10392bd91 100644
--- a/cors.json
+++ b/cors.json
@@ -2,9 +2,9 @@
{
"method": ["GET"],
"origin": [
- "https://three.ws/",
- " "https://chat.sperax.io",
- "https://sperax.io",",
+ "https://three.ws",
+ "https://chat.sperax.io",
+ "https://sperax.io",
"https://sperax-jam2emun9-moomsi.vercel.app",
"https://sperax-iota.vercel.app",
"http://localhost:*",
diff --git a/package-lock.json b/package-lock.json
index e467248eb..48bc86b03 100644
--- a/package-lock.json
+++ b/package-lock.json
@@ -73,6 +73,7 @@
"zod": "^3.23.8"
},
"devDependencies": {
+ "@gltf-transform/functions": "^4.3.0",
"@x402/fetch": "^2.11.0",
"ajv": "^8.17.1",
"ajv-formats": "^3.0.1",
@@ -7090,6 +7091,24 @@
"url": "https://github.com/sponsors/donmccurdy"
}
},
+ "node_modules/@gltf-transform/functions": {
+ "version": "4.3.0",
+ "resolved": "https://registry.npmjs.org/@gltf-transform/functions/-/functions-4.3.0.tgz",
+ "integrity": "sha512-FZggHVgt3DHOezgESBrf2vDzuD2FYQYaNT2sT/aP316SIwhuiIwby3z7rhV9joDvWqqUaPkf1UmkjlOaY9riSQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@gltf-transform/core": "^4.3.0",
+ "@gltf-transform/extensions": "^4.3.0",
+ "ktx-parse": "^1.0.1",
+ "ndarray": "^1.0.19",
+ "ndarray-lanczos": "^0.3.0",
+ "ndarray-pixels": "^5.0.1"
+ },
+ "funding": {
+ "url": "https://github.com/sponsors/donmccurdy"
+ }
+ },
"node_modules/@huggingface/inference": {
"version": "2.8.1",
"resolved": "https://registry.npmjs.org/@huggingface/inference/-/inference-2.8.1.tgz",
@@ -20574,6 +20593,13 @@
"@types/node": "*"
}
},
+ "node_modules/@types/ndarray": {
+ "version": "1.0.14",
+ "resolved": "https://registry.npmjs.org/@types/ndarray/-/ndarray-1.0.14.tgz",
+ "integrity": "sha512-oANmFZMnFQvb219SSBIhI1Ih/r4CvHDOzkWyJS/XRqkMrGH5/kaPSA1hQhdIBzouaE+5KpE/f5ylI9cujmckQg==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/@types/node": {
"version": "25.6.0",
"resolved": "https://registry.npmjs.org/@types/node/-/node-25.6.0.tgz",
@@ -26264,6 +26290,16 @@
"integrity": "sha512-PjiQ659aQ+fUTQqSrd1XEDnOr52jh30RBurfzkscaE2tPaFsDH5wOAHJiw8XAHphRknCwMUE9KRayc4K/NbO8A==",
"license": "MIT"
},
+ "node_modules/cwise-compiler": {
+ "version": "1.1.3",
+ "resolved": "https://registry.npmjs.org/cwise-compiler/-/cwise-compiler-1.1.3.tgz",
+ "integrity": "sha512-WXlK/m+Di8DMMcCjcWr4i+XzcQra9eCdXIJrgh4TUgh0pIS/yJduLxS9JgefsHJ/YVLdgPtXm9r62W92MvanEQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "uniq": "^1.0.0"
+ }
+ },
"node_modules/dat.gui": {
"version": "0.7.9",
"resolved": "https://registry.npmjs.org/dat.gui/-/dat.gui-0.7.9.tgz",
@@ -31083,6 +31119,13 @@
"node": ">= 0.4"
}
},
+ "node_modules/iota-array": {
+ "version": "1.0.0",
+ "resolved": "https://registry.npmjs.org/iota-array/-/iota-array-1.0.0.tgz",
+ "integrity": "sha512-pZ2xT+LOHckCatGQ3DcG/a+QuEqvoxqkiL7tvE8nn3uuu+f6i1TtpB5/FtWFbxUuVr5PZCx8KskuGatbJDXOWA==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/ip-address": {
"version": "10.1.1",
"resolved": "https://registry.npmjs.org/ip-address/-/ip-address-10.1.1.tgz",
@@ -34894,6 +34937,51 @@
"dev": true,
"license": "MIT"
},
+ "node_modules/ndarray": {
+ "version": "1.0.19",
+ "resolved": "https://registry.npmjs.org/ndarray/-/ndarray-1.0.19.tgz",
+ "integrity": "sha512-B4JHA4vdyZU30ELBw3g7/p9bZupyew5a7tX1Y/gGeF2hafrPaQZhgrGQfsvgfYbgdFZjYwuEcnaobeM/WMW+HQ==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "iota-array": "^1.0.0",
+ "is-buffer": "^1.0.2"
+ }
+ },
+ "node_modules/ndarray-lanczos": {
+ "version": "0.3.0",
+ "resolved": "https://registry.npmjs.org/ndarray-lanczos/-/ndarray-lanczos-0.3.0.tgz",
+ "integrity": "sha512-5kBmmG3Zvyj77qxIAC4QFLKuYdDIBJwCG+DukT6jQHNa1Ft74/hPH1z5mbQXeHBt8yvGPBGVrr3wEOdJPYYZYg==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/ndarray": "^1.0.11",
+ "ndarray": "^1.0.19"
+ }
+ },
+ "node_modules/ndarray-ops": {
+ "version": "1.2.2",
+ "resolved": "https://registry.npmjs.org/ndarray-ops/-/ndarray-ops-1.2.2.tgz",
+ "integrity": "sha512-BppWAFRjMYF7N/r6Ie51q6D4fs0iiGmeXIACKY66fLpnwIui3Wc3CXiD/30mgLbDjPpSLrsqcp3Z62+IcHZsDw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "cwise-compiler": "^1.0.0"
+ }
+ },
+ "node_modules/ndarray-pixels": {
+ "version": "5.0.1",
+ "resolved": "https://registry.npmjs.org/ndarray-pixels/-/ndarray-pixels-5.0.1.tgz",
+ "integrity": "sha512-IBtrpefpqlI8SPDCGjXk4v5NV5z7r3JSuCbfuEEXaM0vrOJtNGgYUa4C3Lt5H+qWdYF4BCPVFsnXhNC7QvZwkw==",
+ "dev": true,
+ "license": "MIT",
+ "dependencies": {
+ "@types/ndarray": "^1.0.14",
+ "ndarray": "^1.0.19",
+ "ndarray-ops": "^1.2.2",
+ "sharp": "^0.34.0"
+ }
+ },
"node_modules/near-hd-key": {
"version": "1.2.1",
"resolved": "https://registry.npmjs.org/near-hd-key/-/near-hd-key-1.2.1.tgz",
@@ -41547,6 +41635,13 @@
"ev-emitter": "^2.0.0"
}
},
+ "node_modules/uniq": {
+ "version": "1.0.1",
+ "resolved": "https://registry.npmjs.org/uniq/-/uniq-1.0.1.tgz",
+ "integrity": "sha512-Gw+zz50YNKPDKXs+9d+aKAjVwpjNwqzvNpLigIruT4HA9lMZNdMqs9x07kKHB/L9WRzqp4+DlTU5s4wG2esdoA==",
+ "dev": true,
+ "license": "MIT"
+ },
"node_modules/unique-string": {
"version": "2.0.0",
"resolved": "https://registry.npmjs.org/unique-string/-/unique-string-2.0.0.tgz",
diff --git a/package.json b/package.json
index 9d680e5ad..c4afb67a0 100644
--- a/package.json
+++ b/package.json
@@ -59,6 +59,7 @@
"release:lib": "npm run build:lib && npm run publish:lib",
"clean": "rm -rf dist/* dist-lib/* || true",
"generate-icons": "node scripts/generate-pwa-icons.mjs",
+ "optimize:glb": "node scripts/optimize-glb.mjs",
"fetch-animations": "node scripts/download-animations.mjs",
"fetch:mixamo-catalog": "node scripts/fetch-mixamo-catalog.mjs",
"test": "vitest run",
@@ -138,6 +139,7 @@
"zod": "^3.23.8"
},
"devDependencies": {
+ "@gltf-transform/functions": "^4.3.0",
"@x402/fetch": "^2.11.0",
"ajv": "^8.17.1",
"ajv-formats": "^3.0.1",
diff --git a/public/animations/robotexpressive.glb b/public/animations/robotexpressive.glb
index 6fec9cfb4..ec3423e3a 100644
Binary files a/public/animations/robotexpressive.glb and b/public/animations/robotexpressive.glb differ
diff --git a/public/animations/soldier.glb b/public/animations/soldier.glb
index 1788f122d..2632ae74a 100644
Binary files a/public/animations/soldier.glb and b/public/animations/soldier.glb differ
diff --git a/public/avatars/cz.glb b/public/avatars/cz.glb
index 48f6b081e..79648be49 100644
Binary files a/public/avatars/cz.glb and b/public/avatars/cz.glb differ
diff --git a/public/cz/cz.js b/public/cz/cz.js
index e365def89..feef2c44d 100644
--- a/public/cz/cz.js
+++ b/public/cz/cz.js
@@ -20,8 +20,13 @@ const snippetIframe = document.getElementById('snippet-iframe');
const errorMsgEl = document.getElementById('error-msg');
const rehearsalBadge = document.getElementById('rehearsal-badge');
-// Wire agent-id into the embed element
-document.getElementById('preview').setAttribute('agent-id', AGENT_ID);
+// Wire the preview element. We point at a local body GLB rather than resolving
+// agent-id=cz-preview through /api/agents/* so the on-page preview renders
+// instantly without depending on whether the cz-preview agent has been seeded
+// in the current environment. The embed snippets below still surface the
+// agent-id form for users to copy.
+document.getElementById('preview').setAttribute('body', '/avatars/cz.glb');
+document.getElementById('preview').setAttribute('name', AGENT_NAME);
if (REHEARSAL) rehearsalBadge.classList.remove('hidden');
diff --git a/pump-3d-agent.html b/pump-3d-agent.html
index 9f88101b7..e4d975e06 100644
--- a/pump-3d-agent.html
+++ b/pump-3d-agent.html
@@ -3,145 +3,12 @@
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
-<link rel="icon" href="data:image/svg+xml,<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 100 100'><text y='.9em' font-size='90'>🟢</text></svg>">
<title>3D-Agent · PumpFun Live</title>
-<meta name="description" content="Real-time stream of new PumpFun token launches on Solana — embedded in 3D-Agent.">
-<link rel="canonical" href="/pump-live.html">
-<style>
- * { margin: 0; padding: 0; box-sizing: border-box; }
- body {
- background: #0a0a0a;
- color: #00ff41;
- font-family: 'Courier New', monospace;
- font-size: 13px;
- line-height: 1.5;
- padding: 0;
- }
-
- #stage {
- position: fixed;
- top: 60px;
- right: 20px;
- width: 300px;
- height: 300px;
- border: 1px solid #222;
- z-index: 20;
- }
-
- /* ── Header ────────────────────────────────────────── */
- #header {
- background: #111;
- border-bottom: 1px solid #222;
- padding: 12px 20px;
- display: flex;
- align-items: center;
- gap: 16px;
- flex-wrap: wrap;
- position: sticky;
- top: 0;
- z-index: 10;
- }
- #header h1 {
- font-size: 16px;
- color: #00ff41;
- white-space: nowrap;
- }
- #header .status {
- font-size: 12px;
- color: #666;
- }
- #header .status.connected { color: #00ff41; }
- #header .status.error { color: #ff4141; }
-
- /* ── Log area ──────────────────────────────────────── */
- #log {
- padding: 12px 20px;
- max-height: calc(100vh - 60px);
- overflow-y: auto;
- }
- .entry {
- border-bottom: 1px solid #111;
- padding: 8px 0;
- animation: fadeIn 0.3s ease;
- }
- @keyframes fadeIn {
- from { opacity: 0; transform: translateY(-4px); }
- to { opacity: 1; transform: translateY(0); }
- }
-</style>
- <link rel="stylesheet" href="/nav.css" />
- <link rel="stylesheet" href="/footer.css" />
- <script defer src="/footer-newsletter.js"></script>
- </head>
+<link rel="canonical" href="/pump-live">
+<meta http-equiv="refresh" content="0; url=/pump-live">
+<script>location.replace('/pump-live');</script>
+</head>
<body>
- <header class="site-header">
- <h1 class="site-header-brand">
- <a href="/" aria-label="three.ws home"><img class="wordmark-logo" src="/three.svg" alt="" aria-hidden="true" /><span class="wordmark-dot" aria-hidden="true"></span>three.ws</a>
- </h1>
- <div id="nav-container"></div>
- </header>
- <script src="/nav.js"></script>
-
-
-<div id="header">
- <h1>PumpFun Live</h1>
- <div class="status">Connecting...</div>
-</div>
-
-<div id="log"></div>
-
-<div id="stage"></div>
-
-<script type="module">
- import { Viewer } from '/src/viewer.js';
- import { AgentIdentity } from '/src/agent-identity.js';
- import { AgentAvatar } from '/src/agent-avatar.js';
- import { protocol } from '/src/agent-protocol.js';
-
- async function bootAgent() {
- const agentId = 'agent-test-ad415d18';
- const identity = new AgentIdentity({ agentId, autoLoad: true });
- await identity.load();
-
- if (!identity.avatarId) {
- console.error('Agent has no avatar body');
- return;
- }
-
- const resp = await fetch(`/api/avatars/${identity.avatarId}`);
- if (!resp.ok) {
- console.error(`Failed to fetch avatar: ${resp.status}`);
- return;
- }
-
- const { avatar } = await resp.json();
- const glbUrl = avatar?.url;
- if (!glbUrl) {
- console.error('No avatar URL found');
- return;
- }
-
- const stage = document.getElementById('stage');
- const viewer = new Viewer(stage, { kiosk: true });
- viewer.renderer?.setClearAlpha(0);
- if (viewer.scene) viewer.scene.background = null;
- await viewer.load(glbUrl, '', new Map());
-
- const avatarCtl = new AgentAvatar(viewer, protocol, identity);
- avatarCtl.attach();
- }
-
- try {
- await bootAgent();
- } catch (err) {
- console.error('Failed to load 3D agent:', err);
- const stage = document.getElementById('stage');
- stage.innerHTML = `<div style="color: #ff4141; padding: 10px;">Failed to load agent. See console for details.</div>`;
- }
-</script>
-
-
- <div id="footer-container"></div>
- <script src="/footer.js"></script>
+<p>Moved to <a href="/pump-live">/pump-live</a>.</p>
</body>
</html>
diff --git a/rider/assets/avatars/cz.glb b/rider/assets/avatars/cz.glb
index 48f6b081e..79648be49 100644
Binary files a/rider/assets/avatars/cz.glb and b/rider/assets/avatars/cz.glb differ
diff --git a/rider/assets/avatars/robotexpressive.glb b/rider/assets/avatars/robotexpressive.glb
index 6fec9cfb4..ec3423e3a 100644
Binary files a/rider/assets/avatars/robotexpressive.glb and b/rider/assets/avatars/robotexpressive.glb differ
diff --git a/rider/assets/avatars/soldier.glb b/rider/assets/avatars/soldier.glb
index 1788f122d..2632ae74a 100644
Binary files a/rider/assets/avatars/soldier.glb and b/rider/assets/avatars/soldier.glb differ
diff --git a/scripts/optimize-glb.mjs b/scripts/optimize-glb.mjs
new file mode 100644
index 000000000..fdd8bf90e
--- /dev/null
+++ b/scripts/optimize-glb.mjs
@@ -0,0 +1,117 @@
+#!/usr/bin/env node
+/**
+ * GLB optimization pipeline.
+ *
+ * Lossless geometry passes + WebP texture re-encode. Output GLBs use only the
+ * standard glTF 2.0 feature set — no EXT_meshopt_compression, no KHR_draco — so
+ * they load in every GLTFLoader site without decoder wiring.
+ *
+ * Run: npm run optimize:glb (process all GLBs, in-place with .bak)
+ * npm run optimize:glb -- --dry (report-only, no writes)
+ * npm run optimize:glb -- <path> (single file)
+ */
+import { readFileSync, writeFileSync, statSync, renameSync, existsSync } from 'node:fs';
+import { readdir } from 'node:fs/promises';
+import { resolve, relative, join, extname } from 'node:path';
+import { fileURLToPath } from 'node:url';
+import sharp from 'sharp';
+import { NodeIO } from '@gltf-transform/core';
+import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
+import { dedup, prune, resample, weld, textureCompress } from '@gltf-transform/functions';
+
+const ROOT = resolve(fileURLToPath(import.meta.url), '..', '..');
+const args = process.argv.slice(2);
+const DRY = args.includes('--dry');
+const explicit = args.filter((a) => !a.startsWith('--'));
+
+// Directories to scan when no explicit paths are given.
+const SCAN_DIRS = ['assets', 'public', 'rider/assets'];
+
+async function walkGlb(dir) {
+ const out = [];
+ const abs = resolve(ROOT, dir);
+ if (!existsSync(abs)) return out;
+ const stack = [abs];
+ while (stack.length) {
+ const cur = stack.pop();
+ const entries = await readdir(cur, { withFileTypes: true });
+ for (const e of entries) {
+ const p = join(cur, e.name);
+ if (e.isDirectory()) stack.push(p);
+ else if (e.isFile() && extname(e.name).toLowerCase() === '.glb') out.push(p);
+ }
+ }
+ return out;
+}
+
+function fmt(bytes) {
+ if (bytes >= 1024 * 1024) return (bytes / 1024 / 1024).toFixed(2) + ' MB';
+ if (bytes >= 1024) return (bytes / 1024).toFixed(1) + ' KB';
+ return bytes + ' B';
+}
+
+const io = new NodeIO().registerExtensions(ALL_EXTENSIONS);
+
+async function optimizeOne(absPath) {
+ const before = statSync(absPath).size;
+ const doc = await io.read(absPath);
+
+ await doc.transform(
+ dedup(),
+ weld(),
+ resample(),
+ prune({ keepLeaves: false, keepAttributes: false }),
+ textureCompress({ encoder: sharp, targetFormat: 'webp', quality: 85 }),
+ );
+
+ const bytes = await io.writeBinary(doc);
+ const after = bytes.byteLength;
+ const rel = relative(ROOT, absPath);
+
+ if (after >= before) {
+ console.log(` skip ${rel} ${fmt(before)} → ${fmt(after)} (no gain)`);
+ return { before, after: before, written: false };
+ }
+
+ if (!DRY) {
+ const bak = absPath + '.bak';
+ if (!existsSync(bak)) renameSync(absPath, bak);
+ writeFileSync(absPath, bytes);
+ }
+ const pct = (((before - after) / before) * 100).toFixed(1);
+ console.log(` ${DRY ? 'would' : 'wrote'} ${rel} ${fmt(before)} → ${fmt(after)} (-${pct}%)`);
+ return { before, after, written: !DRY };
+}
+
+async function main() {
+ let targets = [];
+ if (explicit.length) {
+ targets = explicit.map((p) => resolve(ROOT, p));
+ } else {
+ for (const d of SCAN_DIRS) targets.push(...(await walkGlb(d)));
+ }
+ targets = [...new Set(targets)].sort();
+
+ if (!targets.length) {
+ console.error('no .glb files found');
+ process.exit(1);
+ }
+
+ console.log(`${DRY ? '[dry-run] ' : ''}optimizing ${targets.length} GLB file(s)`);
+ let totalBefore = 0;
+ let totalAfter = 0;
+ for (const t of targets) {
+ try {
+ const r = await optimizeOne(t);
+ totalBefore += r.before;
+ totalAfter += r.after;
+ } catch (err) {
+ console.error(` FAIL ${relative(ROOT, t)} ${err.message}`);
+ process.exitCode = 1;
+ }
+ }
+ const pct = totalBefore ? (((totalBefore - totalAfter) / totalBefore) * 100).toFixed(1) : '0.0';
+ console.log(`\ntotal: ${fmt(totalBefore)} → ${fmt(totalAfter)} (-${pct}%)`);
+}
+
+main();
diff --git a/src/marketplace.js b/src/marketplace.js
index 1d84e7fbb..24bd2a24c 100644
--- a/src/marketplace.js
+++ b/src/marketplace.js
@@ -1362,7 +1362,7 @@ function renderAvatarCard(a, spotlight = false) {
// the observer promotes it to `src` on intersect — no GLB download, no
// scene parse, no animation loop until the card is actually on screen.
const preview = a.image
- ? `<img src="${escapeHtml(a.image)}" alt="${name}" loading="lazy" decoding="async" />`
+ ? `<img src="${escapeHtml(a.image)}" alt="${name}" loading="lazy" decoding="async" onerror="this.replaceWith(Object.assign(document.createElement('div'),{className:'card-img-fallback'}))" />`
: a.glbUrl
? `<model-viewer
data-src="${escapeHtml(a.glbUrl)}"
@@ -1448,7 +1448,7 @@ function renderOnchainCard(a) {
const x402 = a.x402Support ? `<span class="onchain-x402" title="Accepts x402 micropayments">x402</span>` : '';
const href = a.viewerUrl || a.tokenExplorerUrl || '#';
const preview = a.image
- ? `<img src="${escapeHtml(a.image)}" alt="${name}" loading="lazy" decoding="async" />`
+ ? `<img src="${escapeHtml(a.image)}" alt="${name}" loading="lazy" decoding="async" onerror="this.replaceWith(Object.assign(document.createElement('div'),{className:'card-img-fallback'}))" />`
: a.glbUrl
? `<model-viewer
src="${escapeHtml(a.glbUrl)}"
diff --git a/tests/agent-monetization.test.js b/tests/agent-monetization.test.js
index 70ac7dc88..94b24d25e 100644
--- a/tests/agent-monetization.test.js
+++ b/tests/agent-monetization.test.js
@@ -17,7 +17,11 @@ vi.mock('../api/_lib/auth.js', () => ({
vi.mock('../api/_lib/db.js', () => ({
sql: vi.fn(async (strings, ...values) => {
- sqlState.calls.push({ query: strings.join('?'), values });
+ if (typeof strings === 'string') {
+ sqlState.calls.push({ query: strings, values: values[0] ?? [] });
+ } else {
+ sqlState.calls.push({ query: strings.join('?'), values });
+ }
return sqlState.queue.length ? sqlState.queue.shift() : [];
}),
}));
@@ -360,8 +364,6 @@ describe('Revenue Dashboard', () => {
it('returns correct revenue totals', async () => {
authState.session = { id: 'user-1' };
- // revenue.js calls sql`` for agentFilter when agentId is null
- sqlState.queue.push([]); // agentFilter = sql``
// summary query
sqlState.queue.push([
{
diff --git a/tests/api/agents.test.js b/tests/api/agents.test.js
index 9a89f895d..2d785d5bc 100644
--- a/tests/api/agents.test.js
+++ b/tests/api/agents.test.js
@@ -24,10 +24,12 @@ const sqlState = {
vi.mock('../../api/_lib/db.js', () => ({
sql: vi.fn(async (strings, ...values) => {
- sqlState.calls.push({
- query: strings.join('?'),
- values,
- });
+ // Supports both `sql\`...\`` tagged-template form and `sql(text, params)` form.
+ if (typeof strings === 'string') {
+ sqlState.calls.push({ query: strings, values: values[0] ?? [] });
+ } else {
+ sqlState.calls.push({ query: strings.join('?'), values });
+ }
if (sqlState.queue.length === 0) return [];
return sqlState.queue.shift();
}),
@@ -110,9 +112,6 @@ describe('GET /api/agents — list', () => {
it('returns caller agents when authenticated via session', async () => {
authState.session = { id: 'user-1' };
- // handlers makes sql`` (empty fragment for onchainFilter) before the SELECT;
- // the mock intercepts both calls so queue needs one entry per sql call.
- sqlState.queue.push([]); // sql`` empty fragment
sqlState.queue.push([
{
id: 'agent-1',