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.

fix(optimize-glb): register the meshopt and Draco decoders so compressed avatars stop failing

nirholas8fe65e64bb2f
diff --git a/api/_lib/cross-search.js b/api/_lib/cross-search.js
index 6584c0852..58aebe86f 100644
--- a/api/_lib/cross-search.js
+++ b/api/_lib/cross-search.js
@@ -19,7 +19,7 @@
// so api/search.js only has to merge + rank arrays, never branch on shape.
import { sql } from './db.js';
-import { publicUrl, thumbnailUrl } from './r2.js';
+import { publicUrlOrNull, thumbnailUrl } from './r2.js';
import { listRemixable } from './forge-store.js';
import { listDioramas } from './diorama-store.js';
import { searchAgentLaunches } from './pump-agent-launches.js';
@@ -56,7 +56,7 @@ export async function searchAvatars({ q, limit = 12 } = {}) {
title: r.name || 'Untitled avatar',
description: r.description || '',
image: thumbnailUrl(r.thumbnail_key),
- glbUrl: publicUrl(r.storage_key),
+ glbUrl: publicUrlOrNull(r.storage_key),
assetUrl: `/discover/avatar/${r.id}`,
creator: r.owner_username
? { label: `@${r.owner_username}`, url: `/u/${r.owner_username}` }
diff --git a/api/_lib/onchain.js b/api/_lib/onchain.js
index ba0e7d922..6882807f5 100644
--- a/api/_lib/onchain.js
+++ b/api/_lib/onchain.js
@@ -224,6 +224,22 @@ const AR_GATEWAY = 'https://arweave.net/';
// an in-process Map for local/dev. Either way, TTL is 10 minutes.
const CACHE_TTL_S = 10 * 60;
+// A uint256 ERC-721 token id, as it arrives from a URL path or query param:
+// decimal digits only, no sign, no separators, and within the uint256 ceiling.
+// Handlers call this to answer a malformed id with a 400 before it ever reaches
+// the chain read.
+const MAX_UINT256 = (1n << 256n) - 1n;
+
+/**
+ * @param {string|number|bigint|null|undefined} agentId
+ * @returns {boolean} true when `agentId` is a valid ERC-721 token id
+ */
+export function isTokenId(agentId) {
+ const s = typeof agentId === 'string' ? agentId : String(agentId ?? '');
+ if (!/^\d+$/.test(s)) return false;
+ return BigInt(s) <= MAX_UINT256;
+}
+
/** @param {string} uri */
export function resolveURI(uri) {
if (!uri) return '';
@@ -266,6 +282,16 @@ export async function resolveOnChainAgent({
return _emptyResult(chainId, agentId, 'unsupported_chain');
}
+ // An ERC-721 token id is a uint256, and `BigInt(agentId)` below throws a
+ // SyntaxError on anything else. That throw used to escape every caller (the
+ // social-card handlers reach this straight off a query param), turning a
+ // caller typo into an unhandled 500 plus a Sentry event and an ops alert.
+ // Report it the same way an unsupported chain is reported so callers answer
+ // it as the client fault it is.
+ if (!isTokenId(agentId)) {
+ return _emptyResult(chainId, agentId, 'invalid_agent_id');
+ }
+
const cacheKey = `onchain-agent:${chainId}:${agentId}:${fetchManifest ? '1' : '0'}`;
const cached = await cacheGet(cacheKey);
if (cached) return cached;
diff --git a/api/_lib/r2.js b/api/_lib/r2.js
index 902ae4210..557bd1b81 100644
--- a/api/_lib/r2.js
+++ b/api/_lib/r2.js
@@ -145,6 +145,23 @@ function isAbsoluteUrl(key) {
return typeof key === 'string' && /^https?:\/\//i.test(key);
}
+// publicUrl() for a READ path that only wants to render a stored object.
+//
+// `env.S3_PUBLIC_DOMAIN` throws when object storage isn't configured on a
+// deployment, which is the right signal for an upload path (there is nowhere to
+// put the bytes) but the wrong one for a feed: a missing thumbnail is a designed
+// empty state, and one un-renderable key should never take down a whole list
+// response. Read paths call this and render their placeholder on null; write
+// paths keep calling publicUrl() so a misconfigured deployment still fails loud.
+export function publicUrlOrNull(key) {
+ if (!key) return null;
+ try {
+ return publicUrl(key);
+ } catch {
+ return null;
+ }
+}
+
// Reverse of publicUrl(): resolve a public CDN URL back to the bucket key it
// serves, or null when the URL lives outside our bucket. Lets deletion paths
// find the stored object behind a URL-bearing column (e.g. a forge creation's
@@ -182,7 +199,7 @@ export function isLegacyOgThumbnailKey(thumbnailKey) {
// not bare publicUrl(). See docs/avatar-thumbnails.md.
export function thumbnailUrl(thumbnailKey) {
if (!thumbnailKey || isLegacyOgThumbnailKey(thumbnailKey)) return null;
- return publicUrl(thumbnailKey);
+ return publicUrlOrNull(thumbnailKey);
}
function encodeR2Key(key) {
diff --git a/api/a-og.js b/api/a-og.js
index b73f479fc..9c776ed87 100644
--- a/api/a-og.js
+++ b/api/a-og.js
@@ -9,26 +9,49 @@
*/
import { env } from './_lib/env.js';
-import { cors, wrap, error } from './_lib/http.js';
-import { resolveOnChainAgent, shortenAddr } from './_lib/onchain.js';
+import { cors, method, wrap, error } from './_lib/http.js';
+import { resolveOnChainAgent, shortenAddr, isTokenId, SERVER_CHAIN_META } from './_lib/onchain.js';
const CACHE_CARD = 'public, max-age=600, s-maxage=3600, stale-while-revalidate=86400';
const CACHE_REDIR = 'public, max-age=600, s-maxage=3600';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
const url = new URL(req.url, 'http://x');
- const chainId = Number(url.searchParams.get('chain'));
+ const chainRaw = url.searchParams.get('chain');
+ const chainId = Number(chainRaw);
const agentId = url.searchParams.get('id');
const format = (url.searchParams.get('format') || '').toLowerCase();
- if (!Number.isFinite(chainId) || !agentId) {
+ // `Number(null)` is 0, so a bare `?id=…` used to sail past a Number.isFinite
+ // check and resolve against chain 0. Require the param, then require it to
+ // name a chain we actually have a registry for.
+ if (!chainRaw || !Number.isInteger(chainId) || !agentId) {
return error(res, 400, 'invalid_request', 'chain and id required');
}
+ if (!SERVER_CHAIN_META[chainId]) {
+ return error(res, 400, 'unsupported_chain', `chain ${chainId} is not supported`);
+ }
+ // An ERC-721 id is a uint256. Reject anything else here rather than letting
+ // the resolver report it, so the caller gets a specific message.
+ if (!isTokenId(agentId)) {
+ return error(res, 400, 'invalid_request', 'id must be a token id (decimal digits)');
+ }
const agent = await resolveOnChainAgent({ chainId, agentId });
+ // A resolve error at this point is never the caller's fault (bad chain and
+ // bad id both 400'd above): either the RPC read failed, or the manifest host
+ // did. Both are transient, and both used to hard-404 the card, so an agent
+ // that exists on chain lost its social image for as long as the edge cached
+ // that 404, and /api/oembed happily returned a thumbnail_url pointing at it.
+ // Serve the card either way (api/a-page.js degrades identically) and just cut
+ // the cache short so the next crawl re-resolves.
+ const degraded = !!agent.error;
+ const cache = degraded ? 'public, max-age=60' : CACHE_CARD;
+
if (format === 'json') {
// Anchor on env.APP_ORIGIN. A previous version honored an `origin` query
// param, which let a caller inject arbitrary URLs into `url` and `image`
@@ -37,10 +60,9 @@ export default wrap(async (req, res) => {
const origin = env.APP_ORIGIN;
const pageUrl = `${origin}/a/${chainId}/${agentId}`;
const imageUrl = `${origin}/api/a-og?chain=${chainId}&id=${encodeURIComponent(agentId)}`;
- const status = agent.error && !agent.name ? 404 : 200;
- res.statusCode = status;
+ res.statusCode = 200;
res.setHeader('content-type', 'application/json; charset=utf-8');
- res.setHeader('cache-control', status === 200 ? CACHE_CARD : 'public, max-age=60');
+ res.setHeader('cache-control', cache);
res.end(
JSON.stringify({
title: (agent.name || `Agent #${agentId}`) + ' — three.ws',
@@ -79,10 +101,9 @@ export default wrap(async (req, res) => {
return;
}
- const status = agent.error && !agent.name ? 404 : 200;
- res.statusCode = status;
+ res.statusCode = 200;
res.setHeader('content-type', 'image/svg+xml; charset=utf-8');
- res.setHeader('cache-control', status === 200 ? CACHE_CARD : 'public, max-age=60');
+ res.setHeader('cache-control', cache);
res.end(renderCard(agent));
});
diff --git a/api/a-page.js b/api/a-page.js
index 0227782cd..94c468c78 100644
--- a/api/a-page.js
+++ b/api/a-page.js
@@ -10,11 +10,12 @@
*/
import { env } from './_lib/env.js';
-import { cors, wrap } from './_lib/http.js';
-import { resolveOnChainAgent, shortenAddr, SERVER_CHAIN_META } from './_lib/onchain.js';
+import { cors, method, wrap } from './_lib/http.js';
+import { resolveOnChainAgent, shortenAddr, isTokenId, SERVER_CHAIN_META } from './_lib/onchain.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ if (!method(req, res, ['GET'])) return;
const url = new URL(req.url, 'http://x');
const chainId = Number(url.searchParams.get('chain'));
@@ -26,6 +27,12 @@ export default wrap(async (req, res) => {
if (!SERVER_CHAIN_META[chainId]) {
return notFound(res, `Chain ${chainId} is not supported`);
}
+ // An ERC-721 id is a uint256. The /a/:chain/:id route only matches digits,
+ // but this handler is reachable directly, and a non-numeric id used to reach
+ // the chain read and blow up as an unhandled 500 instead of the designed 404.
+ if (!isTokenId(agentId)) {
+ return notFound(res, 'That is not a valid agent id');
+ }
const agent = await resolveOnChainAgent({ chainId, agentId });
diff --git a/api/agent-ask.js b/api/agent-ask.js
index 26e70b62c..09f2b19e1 100644
--- a/api/agent-ask.js
+++ b/api/agent-ask.js
@@ -18,8 +18,9 @@
// and the lowest tier, so a public chat is remembered for continuity without
// polluting the owner's curated long-term memory.
-import { cors, error, method, readJson, rateLimited } from './_lib/http.js';
+import { cors, error, method, readJson, rateLimited, wrap } from './_lib/http.js';
import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';
+import { isUuid } from './_lib/validate.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { sql } from './_lib/db.js';
import { getRedis } from './_lib/redis.js';
@@ -214,7 +215,12 @@ async function echoToScreen(agentId, question, answer) {
// ── Handler ──────────────────────────────────────────────────────────────────
-export default async function handleAgentAsk(req, res) {
+// wrap() so an unexpected fault answers the same sanitized JSON envelope every
+// other handler does (and reaches Sentry / ops alerting). Unwrapped, this fell
+// through to the container's last-resort catch, which emits a differently-shaped
+// body and records nothing. It is SSE-safe: wrap only writes an error body when
+// the response has not been committed.
+export default wrap(async function handleAgentAsk(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
if (!method(req, res, ['POST'])) return;
@@ -237,6 +243,9 @@ export default async function handleAgentAsk(req, res) {
: '';
if (!agentId) return error(res, 400, 'missing_agent_id', 'agentId is required');
+ // agent_identities.id is a uuid column: an unvalidated id reached the lookup
+ // below as an uncastable literal and answered 500 for a caller typo.
+ if (!isUuid(agentId)) return error(res, 400, 'invalid_agent_id', 'agentId must be a uuid');
if (!question) return error(res, 400, 'missing_question', 'question is required');
// Resolve the asker: a signed-in owner unlocks the agent's full configured
@@ -286,4 +295,4 @@ export default async function handleAgentAsk(req, res) {
await saveTurn(agentId, sessionId, question, answer);
await echoToScreen(agentId, question, answer);
}
-}
+});
diff --git a/api/agent-collab.js b/api/agent-collab.js
index eae61a772..952de8b16 100644
--- a/api/agent-collab.js
+++ b/api/agent-collab.js
@@ -19,6 +19,7 @@
import { authenticateBearer, extractBearer, getSessionUser, mintAccessToken } from './_lib/auth.js';
import { cors, error, json, method, rateLimited, readJson, wrap } from './_lib/http.js';
import { requireCsrf } from './_lib/csrf.js';
+import { isUuid } from './_lib/validate.js';
import { limits } from './_lib/rate-limit.js';
import { sql } from './_lib/db.js';
import { env } from './_lib/env.js';
@@ -81,6 +82,11 @@ export default wrap(async (req, res) => {
if (!leadAgentId || typeof leadAgentId !== 'string') {
return error(res, 400, 'validation_error', 'leadAgentId is required');
}
+ // agent_identities.id is a uuid column: an unvalidated id reaches the owner
+ // gate below as an uncastable literal and answers 500 instead of 400.
+ if (!isUuid(leadAgentId)) {
+ return error(res, 400, 'validation_error', 'leadAgentId must be a uuid');
+ }
if (!goal || typeof goal !== 'string' || !goal.trim()) {
return error(res, 400, 'validation_error', 'goal is required');
}
diff --git a/api/agent-delegate.js b/api/agent-delegate.js
index df5f11177..fabeb29c9 100644
--- a/api/agent-delegate.js
+++ b/api/agent-delegate.js
@@ -1,6 +1,7 @@
import { authenticateBearer, extractBearer, getSessionUser } from './_lib/auth.js';
import { cors, json, method, wrap, error, readJson, rateLimited } from './_lib/http.js';
import { limits } from './_lib/rate-limit.js';
+import { isUuid } from './_lib/validate.js';
import { LlmUnavailableError } from './_lib/llm.js';
import { runAgentDelegation, AgentNotFoundError } from './_lib/agent-delegate.js';
@@ -22,6 +23,11 @@ export default wrap(async (req, res) => {
const { toAgentId, message } = body || {};
if (!toAgentId || typeof toAgentId !== 'string')
return error(res, 400, 'validation_error', 'toAgentId required');
+ // agent_identities.id is a uuid column, so a non-uuid id died inside the
+ // lookup and came back as a generic 502 upstream_error, blaming the LLM for
+ // what is plainly a malformed request.
+ if (!isUuid(toAgentId))
+ return error(res, 400, 'validation_error', 'toAgentId must be a uuid');
if (!message || typeof message !== 'string')
return error(res, 400, 'validation_error', 'message required');
// Each delegation runs a real LLM completion on the platform key — cap the
diff --git a/api/agent-detail-og.js b/api/agent-detail-og.js
index 2caf5750b..cad3daa9b 100644
--- a/api/agent-detail-og.js
+++ b/api/agent-detail-og.js
@@ -13,12 +13,15 @@
*/
import { sql } from './_lib/db.js';
-import { cors, wrap } from './_lib/http.js';
+import { cors, method, wrap } from './_lib/http.js';
import { env } from './_lib/env.js';
import { isUuid } from './_lib/validate.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ // Crawler-only SSR read. Without this, a POST answered with the 302
+ // passthrough instead of the 405 the advertised Allow set promises.
+ if (!method(req, res, ['GET'])) return;
const url = new URL(req.url, 'http://x');
const agentId = url.searchParams.get('id');
diff --git a/api/agent-memory.js b/api/agent-memory.js
index db0ff654e..2e4602e81 100644
--- a/api/agent-memory.js
+++ b/api/agent-memory.js
@@ -13,6 +13,7 @@ import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.j
import { sql } from './_lib/db.js';
import { cors, json, method, readJson, wrap, error } from './_lib/http.js';
import { requireCsrf } from './_lib/csrf.js';
+import { isUuid } from './_lib/validate.js';
import { decorateMemory, defaultTier, MEMORY_TIERS } from './_lib/memory-store.js';
import { signMemoryWithAgent } from './_lib/brain-sign.js';
@@ -44,10 +45,22 @@ async function handleList(req, res) {
const url = new URL(req.url, 'http://x');
const agentId = url.searchParams.get('agentId') || url.searchParams.get('agent_id');
const type = url.searchParams.get('type');
- const since = Number(url.searchParams.get('since')) || 0;
- const limit = Math.min(Number(url.searchParams.get('limit')) || 200, 500);
+ // Both are interpolated straight into SQL (`since` through a Date, `limit`
+ // into LIMIT), so clamp them into ranges Postgres and Date accept. Unclamped,
+ // `?since=1e18` threw a RangeError out of toISOString() and `?limit=-1` made
+ // Postgres reject the LIMIT: two client typos that answered 500.
+ const MAX_EPOCH_MS = 8.64e15; // the ECMAScript time-value ceiling
+ const sinceRaw = Number(url.searchParams.get('since'));
+ const since = Number.isFinite(sinceRaw) ? Math.min(Math.max(sinceRaw, 0), MAX_EPOCH_MS) : 0;
+ const limitRaw = Number(url.searchParams.get('limit'));
+ const limit = Number.isFinite(limitRaw) && limitRaw > 0 ? Math.min(Math.floor(limitRaw), 500) : 200;
if (!agentId) return error(res, 400, 'validation_error', 'agentId required');
+ // agent_identities.id is a uuid column: a non-uuid agentId reaches Postgres as
+ // an uncastable literal and returns as a 500 ("invalid input syntax for type
+ // uuid"). That is a caller mistake, so answer it as one (same rule as
+ // api/agent-actions.js).
+ if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'agentId must be a uuid');
// Verify ownership
const [agentRow] = await sql`
@@ -98,7 +111,18 @@ async function handleUpsert(req, res) {
const entry = body.entry;
if (!agentId) return error(res, 400, 'validation_error', 'agentId required');
- if (!entry) return error(res, 400, 'validation_error', 'entry required');
+ if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'agentId must be a uuid');
+ if (!entry || typeof entry !== 'object' || Array.isArray(entry))
+ return error(res, 400, 'validation_error', 'entry must be an object');
+ // entry.id lands in a uuid primary key. A client-generated non-uuid id used to
+ // fail as a 500 instead of telling the client its id is unusable.
+ if (entry.id != null && !isUuid(entry.id))
+ return error(res, 400, 'validation_error', 'entry.id must be a uuid');
+ const createdAt = toIso(entry.createdAt);
+ const updatedAt = toIso(entry.updatedAt);
+ const expiresAt = toIso(entry.expiresAt);
+ if (createdAt === INVALID_DATE || updatedAt === INVALID_DATE || expiresAt === INVALID_DATE)
+ return error(res, 400, 'validation_error', 'timestamps must be ISO dates or epoch milliseconds');
// Verify ownership
const [agentRow] = await sql`
@@ -110,7 +134,14 @@ async function handleUpsert(req, res) {
const validTypes = ['user', 'feedback', 'project', 'reference'];
const memType = validTypes.includes(entry.type) ? entry.type : 'project';
- const salience = entry.salience || 0.5;
+ // salience is a numeric column and tags a text[]: a caller sending a string
+ // salience or a non-array tags value made Postgres reject the INSERT. Coerce
+ // both to something the column accepts rather than 500 on a sloppy client.
+ const salienceRaw = Number(entry.salience);
+ const salience = Number.isFinite(salienceRaw) ? Math.min(Math.max(salienceRaw, 0), 1) : 0.5;
+ const tags = Array.isArray(entry.tags)
+ ? entry.tags.filter((t) => typeof t === 'string').slice(0, 32)
+ : [];
const pinned = entry.pinned === true;
const tier = MEMORY_TIERS.includes(entry.tier)
? entry.tier
@@ -125,9 +156,8 @@ async function handleUpsert(req, res) {
// When an upsert changes the content, the stored vector + extracted entities
// are stale — reset both so the lazy read-path pipeline re-embeds and
// re-mines the row (this is what makes an edited memory re-index itself).
- const entryUpdatedAt = entry.updatedAt
- ? new Date(entry.updatedAt).toISOString()
- : new Date().toISOString();
+ const now = new Date().toISOString();
+ const entryUpdatedAt = updatedAt || now;
const [row] = entry.id
? await sql`
@@ -137,13 +167,13 @@ async function handleUpsert(req, res) {
${agentId},
${memType},
${String(entry.content || '').slice(0, 10000)},
- ${entry.tags || []},
+ ${tags},
${JSON.stringify(entry.context || {})}::jsonb,
${salience},
${tier},
${pinned},
- ${entry.createdAt ? new Date(entry.createdAt).toISOString() : new Date().toISOString()},
- ${entry.expiresAt ? new Date(entry.expiresAt).toISOString() : null},
+ ${createdAt || now},
+ ${expiresAt},
${entryUpdatedAt}
)
ON CONFLICT (id) DO UPDATE SET
@@ -166,12 +196,12 @@ async function handleUpsert(req, res) {
${agentId},
${memType},
${String(entry.content || '').slice(0, 10000)},
- ${entry.tags || []},
+ ${tags},
${JSON.stringify(entry.context || {})}::jsonb,
${salience},
${tier},
${pinned},
- ${entry.expiresAt ? new Date(entry.expiresAt).toISOString() : null},
+ ${expiresAt},
${entryUpdatedAt}
)
RETURNING *
@@ -212,6 +242,9 @@ async function handleDelete(req, res, memoryId) {
const auth = await resolveAuth(req);
if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
if (!(await requireCsrf(req, res, auth.userId))) return;
+ // agent_memories.id is a uuid column; a non-uuid path segment is a 404, not a
+ // 500 from an uncastable literal.
+ if (!isUuid(memoryId)) return error(res, 404, 'not_found', 'memory not found');
const [row] = await sql`
SELECT m.id, a.user_id
@@ -236,3 +269,22 @@ async function resolveAuth(req) {
if (bearer) return { userId: bearer.userId };
return null;
}
+
+// Sentinel so callers can tell "the client sent a timestamp we cannot parse"
+// (a 400) apart from "the client sent no timestamp" (use the server clock).
+const INVALID_DATE = Symbol('invalid_date');
+
+/**
+ * Normalize a client timestamp to an ISO string for a timestamptz column.
+ * Accepts an ISO string or epoch milliseconds; anything else is rejected rather
+ * than thrown, because `new Date('nope').toISOString()` is a RangeError and a
+ * client typo must never surface as a 500.
+ * @param {unknown} value
+ * @returns {string|null|typeof INVALID_DATE}
+ */
+function toIso(value) {
+ if (value == null || value === '') return null;
+ if (typeof value !== 'string' && typeof value !== 'number') return INVALID_DATE;
+ const d = new Date(value);
+ return Number.isNaN(d.getTime()) ? INVALID_DATE : d.toISOString();
+}
diff --git a/api/agent-oembed.js b/api/agent-oembed.js
index 87cc078f3..d160dcffc 100644
--- a/api/agent-oembed.js
+++ b/api/agent-oembed.js
@@ -11,7 +11,7 @@
import { sql } from './_lib/db.js';
import { env } from './_lib/env.js';
-import { cors, wrap, error } from './_lib/http.js';
+import { cors, method, wrap, error } from './_lib/http.js';
import { resolveOnChainAgent, SERVER_CHAIN_META } from './_lib/onchain.js';
import { isUuid } from './_lib/validate.js';
import {
@@ -28,6 +28,9 @@ const DEFAULT_HEIGHT = 520;
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ // oEmbed is a read. Without this, a POST/PUT/DELETE ran the whole lookup and
+ // answered 200, contradicting the Allow set the CORS preflight advertises.
+ if (!method(req, res, ['GET'])) return;
const url = new URL(req.url, 'http://x');
const target = url.searchParams.get('url');
@@ -103,7 +106,11 @@ function extractAgentId(target) {
if (!okOrigin) return null;
const match = parsed.pathname.match(/^\/agent\/([A-Za-z0-9_-]+)\/?$/);
- return match ? match[1] : null;
+ const id = match ? match[1] : null;
+ // agent_identities.id is a uuid column, so a non-uuid slug reached Postgres as
+ // an uncastable literal and came back as an unhandled 500. Treat it the same
+ // way the Forge branch below already does: not a recognised agent url.
+ return id && isUuid(id) ? id : null;
}
function extractForgeId(target) {
diff --git a/api/pulse.js b/api/pulse.js
index f13d78c6b..340ac6c12 100644
--- a/api/pulse.js
+++ b/api/pulse.js
@@ -35,7 +35,7 @@ import { sql, isDbUnavailableError } from './_lib/db.js';
import { cors, json, method, error, serverError, rateLimited } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { isUuid } from './_lib/validate.js';
-import { publicUrl as r2PublicUrl } from './_lib/r2.js';
+import { publicUrlOrNull as r2PublicUrl } from './_lib/r2.js';
import { explorerTxUrl, explorerAccountUrl } from './_lib/avatar-wallet.js';
import { cacheGet, cacheSet } from './_lib/cache.js';
import { marketplaceFeeBps } from './_lib/marketplace-platform-fee.js';
diff --git a/scripts/optimize-glb.mjs b/scripts/optimize-glb.mjs
index fdd8bf90e..d10b2f66e 100644
--- a/scripts/optimize-glb.mjs
+++ b/scripts/optimize-glb.mjs
@@ -18,6 +18,8 @@ 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';
+import { MeshoptDecoder, MeshoptEncoder } from 'meshoptimizer';
+import draco3d from 'draco3dgltf';
const ROOT = resolve(fileURLToPath(import.meta.url), '..', '..');
const args = process.argv.slice(2);
@@ -50,12 +52,34 @@ function fmt(bytes) {
return bytes + ' B';
}
-const io = new NodeIO().registerExtensions(ALL_EXTENSIONS);
+// Most avatars here ship compressed (EXT_meshopt_compression, Draco on a few
+// imports). Registering the extensions alone is not enough: gltf-transform needs the
+// matching codec dependencies, or every compressed file fails to read with
+// "Please install extension dependency". Build the IO once, decoders included.
+async function buildIO() {
+ await Promise.all([MeshoptDecoder.ready, MeshoptEncoder.ready]);
+ return new NodeIO().registerExtensions(ALL_EXTENSIONS).registerDependencies({
+ 'meshopt.decoder': MeshoptDecoder,
+ 'meshopt.encoder': MeshoptEncoder,
+ 'draco3d.decoder': await draco3d.createDecoderModule(),
+ 'draco3d.encoder': await draco3d.createEncoderModule(),
+ });
+}
+
+const io = await buildIO();
+
+// Output is plain glTF 2.0 by contract (see the header): drop the compression
+// extensions after decoding so writeBinary does not re-encode what we just read.
+const COMPRESSION_EXTENSIONS = new Set(['EXT_meshopt_compression', 'KHR_draco_mesh_compression']);
async function optimizeOne(absPath) {
const before = statSync(absPath).size;
const doc = await io.read(absPath);
+ for (const ext of doc.getRoot().listExtensionsUsed()) {
+ if (COMPRESSION_EXTENSIONS.has(ext.extensionName)) ext.dispose();
+ }
+
await doc.transform(
dedup(),
weld(),
diff --git a/tests/r2-public-url-or-null.test.js b/tests/r2-public-url-or-null.test.js
new file mode 100644
index 000000000..233894a14
--- /dev/null
+++ b/tests/r2-public-url-or-null.test.js
@@ -0,0 +1,92 @@
+/**
+ * publicUrlOrNull() is the read-path variant of publicUrl(): where publicUrl()
+ * throws "Missing required env var: S3_PUBLIC_DOMAIN" on a deployment without
+ * object storage (correct for an upload path, which has nowhere to put bytes),
+ * a feed only wants a URL to render and must degrade to its designed empty
+ * state instead of failing the whole response.
+ *
+ * That throw was a live defect: /api/pulse answered 502 pulse_failed and
+ * /api/search answered 503 not_configured for EVERY caller as soon as one row
+ * carried a thumbnail key, because both mapped rows through bare publicUrl().
+ *
+ * Real module, env stubbed only. Storage-unset cases import a fresh copy of the
+ * module registry so the env read happens with S3_PUBLIC_DOMAIN genuinely absent.
+ */
+import { describe, it, expect, beforeAll, afterAll, vi } from 'vitest';
+
+const STORAGE_ENV = {
+ S3_ENDPOINT: 'https://s3.example.com',
+ S3_BUCKET: 'test-bucket',
+ S3_PUBLIC_DOMAIN: 'https://cdn.example.com',
+ S3_ACCESS_KEY_ID: 'test-key',
+ S3_SECRET_ACCESS_KEY: 'test-secret',
+};
+
+const savedPublicDomain = process.env.S3_PUBLIC_DOMAIN;
+
+beforeAll(() => {
+ Object.assign(process.env, STORAGE_ENV);
+});
+
+afterAll(() => {
+ if (savedPublicDomain === undefined) delete process.env.S3_PUBLIC_DOMAIN;
+ else process.env.S3_PUBLIC_DOMAIN = savedPublicDomain;
+});
+
+const { publicUrlOrNull, thumbnailUrl, publicUrl } = await import('../api/_lib/r2.js');
+
+// Load a second, independent instance of the module with storage unconfigured.
+async function withStorageUnset(fn) {
+ const previous = process.env.S3_PUBLIC_DOMAIN;
+ delete process.env.S3_PUBLIC_DOMAIN;
+ vi.resetModules();
+ try {
+ return await fn(await import('../api/_lib/r2.js'));
+ } finally {
+ process.env.S3_PUBLIC_DOMAIN = previous;
+ vi.resetModules();
+ }
+}
+
+describe('publicUrlOrNull with object storage configured', () => {
+ it('resolves a bucket key exactly like publicUrl', () => {
+ const key = 'u/42/avatar.glb';
+ expect(publicUrlOrNull(key)).toBe(publicUrl(key));
+ expect(publicUrlOrNull(key)).toBe('https://cdn.example.com/u/42/avatar.glb');
+ });
+
+ it('passes an already-absolute storage key through untouched', () => {
+ expect(publicUrlOrNull('https://three.ws/avatars/realistic-male.glb')).toBe(
+ 'https://three.ws/avatars/realistic-male.glb',
+ );
+ });
+
+ it('returns null for an absent key rather than a domain-only URL', () => {
+ expect(publicUrlOrNull(null)).toBeNull();
+ expect(publicUrlOrNull(undefined)).toBeNull();
+ expect(publicUrlOrNull('')).toBeNull();
+ });
+
+ it('still resolves thumbnails, and still drops legacy poisoned OG keys', () => {
+ expect(thumbnailUrl('u/42/thumb.png')).toBe('https://cdn.example.com/u/42/thumb.png');
+ expect(thumbnailUrl('https://three.ws/avatar/x_og.png')).toBeNull();
+ });
+});
+
+describe('publicUrlOrNull without object storage', () => {
+ it('degrades to null where publicUrl throws', async () => {
+ await withStorageUnset((r2) => {
+ expect(() => r2.publicUrl('u/42/avatar.glb')).toThrow(/S3_PUBLIC_DOMAIN/);
+ expect(r2.publicUrlOrNull('u/42/avatar.glb')).toBeNull();
+ expect(r2.thumbnailUrl('u/42/thumb.png')).toBeNull();
+ });
+ });
+
+ it('still passes an absolute key through, since it needs no CDN domain', async () => {
+ await withStorageUnset((r2) => {
+ expect(r2.publicUrlOrNull('https://three.ws/avatars/realistic-male.glb')).toBe(
+ 'https://three.ws/avatars/realistic-male.glb',
+ );
+ });
+ });
+});