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(discover): give external Solana agents a real link preview and stop malformed ids 500ing

nirholas5bd39382fd39
diff --git a/api/_lib/validate.js b/api/_lib/validate.js
index 80db9906c..5401e3a36 100644
--- a/api/_lib/validate.js
+++ b/api/_lib/validate.js
@@ -187,6 +187,17 @@ export function isoTimestamp(value) {
return Number.isNaN(ms) ? null : new Date(ms).toISOString();
}
+// ERC-8004 agent ids are uint256 token ids and are stored as TEXT, precisely
+// because they can exceed what a JS number holds. A handler that does
+// `parseInt(id, 10)` before the query therefore has two failure modes on a
+// public endpoint: a non-numeric id becomes NaN, and an id past 2^53 becomes a
+// rounded float in exponent notation that can never match the text column. Both
+// are client faults; validate the raw digit string and pass it through as text.
+// 78 digits is the width of 2^256 - 1, so nothing valid is rejected.
+export function isErc8004AgentId(value) {
+ return typeof value === 'string' && /^\d{1,78}$/.test(value);
+}
+
export function isValidSolanaAddress(address) {
return typeof address === 'string' && /^[1-9A-HJ-NP-Za-km-z]{32,44}$/.test(address);
}
diff --git a/api/discover-detail.js b/api/discover-detail.js
index 1fe77b918..d942802e7 100644
--- a/api/discover-detail.js
+++ b/api/discover-detail.js
@@ -3,8 +3,10 @@
* -----------------------------------------
* GET /api/discover-detail?kind=onchain&chain=<id>&id=<agentId>
* GET /api/discover-detail?kind=avatar&id=<avatarId>
+ * GET /api/discover-detail?kind=solana&asset=<asset_or_registry_ref>
*
- * Wired to /discover/a/:chainId/:agentId and /discover/avatar/:id via vercel.json.
+ * Wired to /discover/a/:chainId/:agentId, /discover/a/sol/:asset and
+ * /discover/avatar/:id via vercel.json.
*
* Returns the detail.html shell with Open Graph + Twitter Card meta tags already
* baked into the <head>, so link unfurlers (Slack, Discord, X, iMessage) get a
@@ -16,6 +18,7 @@ import { sql } from './_lib/db.js';
import { cors, method, wrap } from './_lib/http.js';
import { CHAIN_BY_ID, tokenExplorerUrl, addressExplorerUrl } from './_lib/erc8004-chains.js';
import { publicUrl, thumbnailUrl } from './_lib/r2.js';
+import { isErc8004AgentId, isUuid } from './_lib/validate.js';
import { env } from './_lib/env.js';
export default wrap(async (req, res) => {
@@ -33,14 +36,18 @@ export default wrap(async (req, res) => {
if (kind === 'onchain') {
const chainId = parseInt(url.searchParams.get('chain') || '', 10);
- if (!Number.isFinite(chainId) || !id) return sendShell(res, origin, null, null, null);
+ // agent_id is TEXT holding a uint256 token id, so the raw digit string is
+ // the only correct comparand: parseInt() rounds anything past 2^53 into
+ // exponent notation and silently matches no row, which reads as "this agent
+ // has no preview" rather than as the bug it is.
+ if (!Number.isFinite(chainId) || !isErc8004AgentId(id)) return sendShell(res, origin, null, null, null);
const rows = await sql`
SELECT chain_id, agent_id, owner, name, description, image, glb_url,
has_3d, x402_support, registered_at, registered_tx,
services, agent_uri
FROM erc8004_agents_index
- WHERE active = true AND chain_id = ${chainId} AND agent_id = ${parseInt(id, 10)}
+ WHERE active = true AND chain_id = ${chainId} AND agent_id = ${id}
LIMIT 1
`.catch(() => []);
@@ -112,9 +119,52 @@ export default wrap(async (req, res) => {
};
canonicalUrl = `${origin}/discover/a/sol/${asset}`;
ogImageUrl = thumb || `${origin}/og-image.png`;
+ } else {
+ // Not one of ours: fall back to the crawled directory of external Solana
+ // agents, the same fallback api/explore-item.js does for the client fetch.
+ // Without it the home chain's entire external directory (Metaplex Agent
+ // Registry + AgenC) unfurls as a nameless generic card in Slack, Discord,
+ // X and iMessage, and ships a generic <title> to crawlers, while the EVM
+ // half of the very same /discover grid previews correctly.
+ const ext = await sql`
+ SELECT source, ref, owner, asset, name, description, image, glb_url,
+ network, registered_at
+ FROM solana_agents_index
+ WHERE active = true
+ AND (asset = ${asset} OR ref = ${asset})
+ LIMIT 1
+ `.catch(() => []);
+
+ if (ext.length) {
+ const r = ext[0];
+ const target = r.asset || r.ref;
+ const cluster = r.network === 'devnet' ? '?cluster=devnet' : '';
+ item = {
+ kind: 'solana',
+ asset: target,
+ name: r.name || 'Solana Agent',
+ description: r.description || '',
+ image: r.image || null,
+ has3d: !!r.glb_url,
+ glbUrl: r.glb_url || null,
+ skills: [],
+ owner: r.owner || null,
+ ownerShort: shortAddr(r.owner),
+ createdAt: r.registered_at,
+ network: r.network || 'mainnet',
+ source: r.source,
+ viewerUrl: r.glb_url ? `/app#model=${encodeURIComponent(r.glb_url)}` : null,
+ explorerUrl: target ? `https://solscan.io/token/${target}${cluster}` : null,
+ ownerExplorerUrl: r.owner ? `https://solscan.io/account/${r.owner}${cluster}` : null,
+ };
+ canonicalUrl = `${origin}/discover/a/sol/${asset}`;
+ ogImageUrl = r.image || `${origin}/og-image.png`;
+ }
}
} else if (kind === 'avatar') {
- if (!id) return sendShell(res, origin, null, null, null);
+ // avatars.id is a uuid column; a malformed id would otherwise reach Postgres
+ // as a 22P02 that the .catch() below swallows into an unexplained blank shell.
+ if (!isUuid(id)) return sendShell(res, origin, null, null, null);
const rows = await sql`
SELECT a.id, a.slug, a.name, a.description, a.storage_key, a.thumbnail_key,
diff --git a/api/explore-item.js b/api/explore-item.js
index 8e9b9b521..7314d9538 100644
--- a/api/explore-item.js
+++ b/api/explore-item.js
@@ -11,6 +11,7 @@ import { cors, json, method, wrap, error, rateLimited } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { CHAIN_BY_ID, tokenExplorerUrl, addressExplorerUrl } from './_lib/erc8004-chains.js';
import { publicUrl, thumbnailUrl } from './_lib/r2.js';
+import { isErc8004AgentId, isUuid } from './_lib/validate.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;
@@ -28,6 +29,10 @@ export default wrap(async (req, res) => {
if (kind === 'onchain') {
const chainId = parseInt(url.searchParams.get('chain') || '', 10);
if (!Number.isFinite(chainId)) return error(res, 400, 'validation_error', 'chain is required for onchain items');
+ // agent_id is a TEXT column holding a uint256 token id. Match on the raw
+ // digit string: parseInt() would round anything past 2^53 into exponent
+ // notation that matches no row, and turn a non-numeric id into NaN.
+ if (!isErc8004AgentId(id)) return error(res, 404, 'not_found', 'agent not found');
const rows = await sql`
SELECT chain_id, agent_id, owner, name, description, image, glb_url,
@@ -36,7 +41,7 @@ export default wrap(async (req, res) => {
FROM erc8004_agents_index
WHERE active = true
AND chain_id = ${chainId}
- AND agent_id = ${parseInt(id, 10)}
+ AND agent_id = ${id}
LIMIT 1
`;
@@ -74,6 +79,12 @@ export default wrap(async (req, res) => {
}
if (kind === 'avatar') {
+ // avatars.id is a uuid column: an unvalidated id reaches Postgres as an
+ // invalid-text-representation error (22P02) and surfaced as a 500 on a
+ // public endpoint. A malformed id names no avatar, so answer 404, which is
+ // also the status the detail page renders its "Not found" state for.
+ if (!isUuid(id)) return error(res, 404, 'not_found', 'avatar not found');
+
const rows = await sql`
SELECT a.id, a.slug, a.name, a.description, a.storage_key, a.thumbnail_key,
a.tags, a.created_at, a.source,
diff --git a/api/explore.js b/api/explore.js
index c655c1cc6..9273a94df 100644
--- a/api/explore.js
+++ b/api/explore.js
@@ -7,7 +7,12 @@
* q=<text> — name/description substring
* cursor=<iso> — created_at/registered_at ISO string for pagination
* limit=<int> — page size, default 24, max 60
- * source=<all|onchain|avatar|solana> — restrict feed to one source. Default 'all'.
+ * source=<all|onchain|avatar|solana|agents>: restrict feed to one source.
+ * Default 'all'. 'agents' is the agent-directory meta-source:
+ * every on-chain agent (EVM + Solana, ours and external) and
+ * no avatars, which is what /agents renders.
+ * category=<c[,c]>: avatar model_category filter (avatar, accessory, item,
+ * scene, creature, vehicle, other). Unknown values are a 400.
* quality=<all|high> — avatar quality filter. 'high' (default) hides
* autonamed/filename-like junk and surfaces named
* community + curated avatars first.
diff --git a/api/feed-stream.js b/api/feed-stream.js
index 035e144eb..bc8469b2f 100644
--- a/api/feed-stream.js
+++ b/api/feed-stream.js
@@ -34,7 +34,6 @@
// before the hard timeout, and EventSource reconnects automatically.
import { cors, method } from './_lib/http.js';
-import { env } from './_lib/env.js';
import { getRedis as _getSharedRedis, isRedisAuthError } from './_lib/redis.js';
const FEED_KEY = 'feed:events';
diff --git a/prompts/swarm-100/api-top-06.md b/prompts/swarm-100/api-top-06.md
deleted file mode 100644
index 5a515f86f..000000000
--- a/prompts/swarm-100/api-top-06.md
+++ /dev/null
@@ -1,110 +0,0 @@
-# API audit: api/*.js batch 06 (10 files)
-
-How to run: paste this file's repo path into a fresh Claude Code chat in this
-repository and say "run this work order". This file is fully self-contained:
-it depends on no other prompt file anywhere. If neighboring files in
-prompts/swarm-100/ are gone, that work is done; if present, ignore them.
-Every claim below rots; step 0 re-measures, and what you measure wins.
-
-## Operating clause (binding)
-
-- Read CLAUDE.md first. Its rules override everything, including this file.
-- Finish 100% in this session. Never end the turn with a question, an option
- list, or an unexecuted plan. A judgment call goes in one line of the final
- report; it never becomes a question that halts work.
-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real
- funds or any irreversible on-chain write, git push or a production deploy,
- committing content that references a crypto project other than $THREE, and
- destroying unrecoverable data.
-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no
- commented-out code. Real APIs and real integrations only.
-- The em-dash and en-dash characters are banned in everything you write.
-- Concurrent agents share this worktree: stage explicit paths only (never a
- bare add-everything), and commit finished work promptly.
-- Before committing, run: npm run check:rules -- --paths <files you touched>.
- It must exit 0.
-
-## Step 0: re-derive the current state
-
-1. Confirm each file below still exists; deleted ones are done, skip them.
-2. For each, decide routability: grep its path in vercel.json and read how
- server/index.mjs maps filesystem handlers. Routed files get an endpoint
- audit; internal modules get a code and test audit.
-3. Start a local server for endpoint checks: node server/index.mjs with .env
- loaded, on a free PORT if 3000 is busy.
-
-## Task: audit these api files, then fix everything found
-
-Files in this batch:
-
-- api/deployments.js
-- api/diorama.js
-- api/discover-detail.js
-- api/explore-item.js
-- api/explore.js
-- api/fact-check-benchmark.js
-- api/feature-og.js
-- api/features.js
-- api/feed-stream.js
-- api/feed.js
-
-For every routed handler:
-
-1. Exercise it with curl against the local server: the success path returns
- real data with the correct status; malformed input returns a 4xx JSON
- error, never a stack trace or an HTML error page; auth is enforced where
- the code intends it; CORS matches neighboring handlers.
-2. Hard-rule scan: no mock fallbacks, no fake-data arrays, no stubbed
- responses, no unfinished markers. Errors are handled at the boundary and
- internal code trusts itself.
-3. Do not spend funds or sign anything on-chain while probing. Payment and
- trading handlers get their validation and error paths exercised, never a
- live settlement.
-
-For every internal (non-routed) module:
-
-4. Something must import it; if nothing does, delete it as dead code (verify
- with a repo-wide grep first).
-5. Its main path and one failure path must be covered in tests/; add the
- missing test if not.
-
-## Definition of done
-
-- [ ] Every listed file has recorded evidence: a curl transcript for routed
- handlers, a passing test or a deletion for internal modules.
-- [ ] Zero hard-rule violations remain in these files.
-- [ ] vitest run passes; npm run check:rules -- --paths <touched files>
- exits 0.
-
-## Never blocked
-
-| Blocker | Resolution (act, do not ask) |
-|---|---|
-| Missing env var or credential | Check .env and .env.local, then the Cloud Run service env, then Secret Manager (the CLAUDE.md self-unblock playbook has the exact commands). If it truly exists nowhere, wire the code fully behind the env var, prove the wiring with a dry run, and name the single missing var in the report. |
-| gcloud not on PATH | Run: export PATH="$HOME/google-cloud-sdk/bin:$PATH" |
-| Dev server port 3000 busy | Another agent may be serving this repo; probe it and reuse if so. Otherwise start your own on a free port: npx vite --port 3101 |
-| Playwright browser missing | npx playwright install chromium |
-| A surface needs a signed-in user | Register a fresh account through the real /register flow against the real API and use it. Never mock the session. |
-| A defect sits in code you did not touch | Fix it if it blocks a Definition of done line (root cause it, never mask it). Otherwise note it in the report and continue. |
-| An unrelated test is red | Same rule. Never pipe npm test through tail; it masks exit codes. |
-
-## Close out (required)
-
-1. Verify every Definition of done line with the actual command output in
- front of you. Never claim a line you did not verify.
-2. Commit with explicit paths and a subject that describes the diff (house
- style: type(scope): what changed and why a reader cares).
-3. Delete this prompt file in that same commit:
-
- git rm prompts/swarm-100/api-top-06.md
-
- The shrinking directory is this campaign's only progress ledger; there is
- no progress log to update.
-4. Final report: what step 0 measured, what changed (file list), evidence per
- Definition of done line, and any one-line judgment calls. No trailing
- questions, no unexecuted plans.
-
-If a line genuinely cannot pass inside this session (an external party must
-respond, or an owner-gated action is the final step), finish everything else,
-leave this file in place, and state exactly which line remains and who owns
-it. Never delete this file on a partial.
diff --git a/tests/explore-item-ids.test.js b/tests/explore-item-ids.test.js
new file mode 100644
index 000000000..bfc81d6f2
--- /dev/null
+++ b/tests/explore-item-ids.test.js
@@ -0,0 +1,133 @@
+// Malformed ids on the public discover detail endpoints must be client errors,
+// never 500s and never silent wrong answers.
+//
+// Two real defects this pins, both found by probing the live handlers:
+//
+// 1. GET /api/explore-item?kind=avatar&id=abc answered 500 internal_error.
+// `avatars.id` is a uuid column, so an unvalidated id reached Postgres as
+// 22P02 (invalid input syntax for type uuid) and bubbled out of the handler
+// as an unhandled 5xx on an unauthenticated endpoint that anyone can hit,
+// complete with a Sentry event per request. The detail page (public/discover
+// /detail.js showError) renders its designed "Not found" state for 404 and a
+// generic "something went wrong" for anything else, so the bug also showed
+// the wrong empty state to every visitor who followed a stale avatar link.
+//
+// 2. Both handlers matched `agent_id = parseInt(id, 10)` against what is a TEXT
+// column holding a uint256 ERC-8004 token id. Any id past 2^53 rounds to a
+// float in exponent notation ("1.157920892373162e+77") that matches no row,
+// so a perfectly valid high agent id silently 404s instead of resolving.
+//
+// The malformed-input assertions below run without a database: every guard sits
+// in front of the first query, so the response is the same with DATABASE_URL set
+// or unset. That is deliberate: it keeps the regression pinned in CI.
+
+import { describe, it, expect, beforeAll, afterAll } from 'vitest';
+import { startTestServer } from './helpers/test-server.js';
+import { isErc8004AgentId, isUuid } from '../api/_lib/validate.js';
+import { splitCapabilities } from '../api/explore-item.js';
+
+describe('isErc8004AgentId', () => {
+ it('accepts a uint256 token id well past what a JS number holds', () => {
+ // 2^256 - 1, the widest legal ERC-8004 agent id.
+ const max = '115792089237316195423570985008687907853269984665640564039457584007913129639935';
+ expect(isErc8004AgentId(max)).toBe(true);
+ // Why the raw string has to reach the query: the old parseInt() comparand
+ // could not round-trip, so it matched no row in a TEXT column.
+ expect(String(Number.parseInt(max, 10))).not.toBe(max);
+ expect(String(Number.parseInt(max, 10))).toContain('e+');
+ });
+
+ it('accepts an ordinary id', () => {
+ expect(isErc8004AgentId('50035')).toBe(true);
+ expect(isErc8004AgentId('0')).toBe(true);
+ });
+
+ it('rejects anything that is not a bare digit string', () => {
+ for (const bad of ['abc', '', '12a', '1.5', '-1', ' 12', '1e77', null, undefined, 12]) {
+ expect(isErc8004AgentId(bad), `should reject ${JSON.stringify(bad)}`).toBe(false);
+ }
+ });
+
+ it('rejects an id wider than uint256 so a padded flood cannot reach the query', () => {
+ expect(isErc8004AgentId('9'.repeat(78))).toBe(true);
+ expect(isErc8004AgentId('9'.repeat(79))).toBe(false);
+ });
+});
+
+describe('splitCapabilities', () => {
+ it('splits the free-text capability list the crawled registries publish', () => {
+ expect(splitCapabilities('trading, analysis; imaging|research')).toEqual([
+ 'trading',
+ 'analysis',
+ 'imaging',
+ 'research',
+ ]);
+ });
+
+ it('passes an array through and drops empties', () => {
+ expect(splitCapabilities([' a ', '', 'b'])).toEqual(['a', 'b']);
+ });
+
+ it('caps a padded entry so one row cannot flood the page', () => {
+ expect(splitCapabilities(Array.from({ length: 100 }, (_, i) => `cap${i}`)).length).toBe(24);
+ expect(splitCapabilities(Array.from({ length: 100 }, (_, i) => `cap${i}`).join(',')).length).toBe(24);
+ });
+
+ it('returns an empty list for a row with no capabilities', () => {
+ expect(splitCapabilities(null)).toEqual([]);
+ expect(splitCapabilities(undefined)).toEqual([]);
+ expect(splitCapabilities(42)).toEqual([]);
+ });
+});
+
+describe('GET /api/explore-item rejects malformed ids without a 500', () => {
+ let BASE;
+ let server;
+
+ beforeAll(async () => {
+ server = await startTestServer();
+ BASE = server.base;
+ }, 90000);
+
+ afterAll(() => server?.close());
+
+ it('answers 404, not 500, for an avatar id that is not a uuid', async () => {
+ const res = await fetch(`${BASE}/api/explore-item?kind=avatar&id=abc`, {
+ signal: AbortSignal.timeout(10000),
+ });
+ expect(res.status).toBe(404);
+ const body = await res.json();
+ expect(body.error).toBe('not_found');
+ }, 15000);
+
+ it('answers 404 for an on-chain agent id that is not a digit string', async () => {
+ const res = await fetch(`${BASE}/api/explore-item?kind=onchain&chain=1&id=abc`, {
+ signal: AbortSignal.timeout(10000),
+ });
+ expect(res.status).toBe(404);
+ expect((await res.json()).error).toBe('not_found');
+ }, 15000);
+
+ it('still answers 400 when kind or id is missing at all', async () => {
+ const res = await fetch(`${BASE}/api/explore-item`, { signal: AbortSignal.timeout(10000) });
+ expect(res.status).toBe(400);
+ expect((await res.json()).error).toBe('validation_error');
+ }, 15000);
+
+ it('still answers 400 for an unknown kind', async () => {
+ const res = await fetch(`${BASE}/api/explore-item?kind=bogus&id=1`, {
+ signal: AbortSignal.timeout(10000),
+ });
+ expect(res.status).toBe(400);
+ expect((await res.json()).error).toBe('validation_error');
+ }, 15000);
+
+ it('serves the SSR shell for a malformed detail-page id instead of erroring', async () => {
+ const res = await fetch(`${BASE}/api/discover-detail?kind=avatar&id=abc`, {
+ signal: AbortSignal.timeout(10000),
+ });
+ expect(res.status).toBe(200);
+ expect(res.headers.get('content-type')).toContain('text/html');
+ expect(await res.text()).toContain('<title>three.ws</title>');
+ }, 15000);
+});