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(api): render the agent share card again, and align the ar, artifact, task and grind boundaries

nirholas4c19d3cbdcd2
diff --git a/api/agent-task.js b/api/agent-task.js
index b54080e71..9d08622f5 100644
--- a/api/agent-task.js
+++ b/api/agent-task.js
@@ -7,7 +7,7 @@
// POST body: { agentId: string, task: string, type?: string }
// GET resp: { task: { text, type, ts, userId } | null }
-import { cors, error, json, method, rateLimited, readJson } from './_lib/http.js';
+import { cors, error, json, method, rateLimited, readJson, wrap } from './_lib/http.js';
import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { getRedis } from './_lib/redis.js';
@@ -20,7 +20,10 @@ const MAX_QUEUE = 20;
const TASK_TTL = 60 * 60 * 6; // 6h — tasks expire if worker never shows up
const TASK_MAX_LEN = 1000;
-export default async function handleAgentTask(req, res) {
+// wrap() gives this route the same boundary every neighbouring handler has: a
+// DB outage degrades to a throttled 503 instead of one logged stack trace and a
+// generic 500 per poll, and a genuine fault gets a correlation ref.
+export default wrap(async function handleAgentTask(req, res) {
if (cors(req, res, { methods: 'GET,POST,OPTIONS' })) return;
if (!method(req, res, ['GET', 'POST'])) return;
@@ -121,4 +124,4 @@ export default async function handleAgentTask(req, res) {
return json(res, 200, { ok: true, queued: Math.min(len, MAX_QUEUE) });
}
-}
+});
diff --git a/api/agent-vanity-grind.js b/api/agent-vanity-grind.js
index c55ede2db..16672bec7 100644
--- a/api/agent-vanity-grind.js
+++ b/api/agent-vanity-grind.js
@@ -13,7 +13,7 @@
// activity log, or agent_actions. It is returned ONLY in this HTTP response, to
// the authenticated owner who triggered the grind.
-import { cors, error, json, method, readJson } from './_lib/http.js';
+import { cors, error, json, method, readJson, wrap } from './_lib/http.js';
import { getSessionUser, authenticateBearer, extractBearer } from './_lib/auth.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { getRedis } from './_lib/redis.js';
@@ -43,7 +43,10 @@ function sleep(ms) {
return new Promise((r) => setTimeout(r, ms));
}
-export default async function handleAgentVanityGrind(req, res) {
+// wrap() matches every neighbouring handler: a DB outage degrades to a throttled
+// 503 rather than a per-request stack trace, and a genuine fault returns a
+// correlation ref instead of a bare 500.
+export default wrap(async function handleAgentVanityGrind(req, res) {
if (cors(req, res, { methods: 'POST,OPTIONS' })) return;
if (!method(req, res, ['POST'])) return;
@@ -282,4 +285,4 @@ export default async function handleAgentVanityGrind(req, res) {
'privateKey64 and launch.mint_secret_key_b64 are a REAL Solana secret key for this address. ' +
'Store it securely now and never share it — it was returned only to you and never published to the live screen.',
});
-}
+});
diff --git a/api/app-og.js b/api/app-og.js
index 3c87f2b9e..437b64273 100644
--- a/api/app-og.js
+++ b/api/app-og.js
@@ -45,10 +45,15 @@ export default wrap(async (req, res) => {
const title = agent.name || 'Agent';
const desc = agent.description || 'An embodied AI agent on three.ws — with a body, a place, and an identity.';
- const thumbnailUrl = agent.avatar_thumbnail_key
+ // Named `avatarThumbnail`, not `thumbnailUrl`: a local `const thumbnailUrl`
+ // shadows the imported helper across this whole function body, so the
+ // initializer's own call hit the temporal dead zone and every agent that HAS a
+ // thumbnail (the only case this route exists for) 500'd instead of rendering
+ // its share card.
+ const avatarThumbnail = agent.avatar_thumbnail_key
? thumbnailUrl(agent.avatar_thumbnail_key)
: null;
- const ogImage = thumbnailUrl
+ const ogImage = avatarThumbnail
|| `${origin}/api/agent/${agentId}/og`;
const skills = agent.skills || [];
diff --git a/api/ar.js b/api/ar.js
index d6c39b9bc..6e45d14ef 100644
--- a/api/ar.js
+++ b/api/ar.js
@@ -22,7 +22,7 @@
* clean, designed error page — never a crash. Zero payment/coin surface.
*/
-import { cors, wrap } from './_lib/http.js';
+import { cors, method, wrap } from './_lib/http.js';
import { planArLaunch } from './_lib/ar-launch.js';
import { MODEL_VIEWER_SRC } from './_lib/model-viewer-cdn.js';
@@ -110,6 +110,9 @@ btn.addEventListener('click',function(){ if(mv.canActivateAR){ try{mv.activateAR
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS' })) return;
+ // The CORS preflight already advertises GET only; enforce it too, so a POST
+ // gets a 405 with an Allow header instead of being served the launch page.
+ if (!method(req, res, ['GET'])) return;
const url = new URL(req.url, 'http://x');
const src = url.searchParams.get('src') || '';
diff --git a/api/artifact.js b/api/artifact.js
index 5f2263126..38f0ef72f 100644
--- a/api/artifact.js
+++ b/api/artifact.js
@@ -13,7 +13,7 @@ import { readFileSync } from 'node:fs';
import { fileURLToPath } from 'node:url';
import { dirname, resolve as pathResolve } from 'node:path';
import { sql } from './_lib/db.js';
-import { error, wrap, rateLimited } from './_lib/http.js';
+import { cors, error, wrap, rateLimited } from './_lib/http.js';
import { limits, clientIp } from './_lib/rate-limit.js';
import { getObjectBuffer } from './_lib/r2.js';
import { assertSafePublicUrl } from './_lib/ssrf-guard.js';
@@ -209,6 +209,12 @@ async function loadModelArtifactConfig(modelUrl, opts) {
}
export default wrap(async (req, res) => {
+ // The response is public read-only HTML that already advertises itself as
+ // embeddable anywhere (frame-ancestors *, x-frame-options ALLOWALL), so an
+ // embedder that fetches it instead of iframing it needs the same open CORS.
+ // Without this a cross-origin preflight got a 405 from the method guard below.
+ if (cors(req, res, { methods: 'GET,HEAD,OPTIONS', origins: '*' })) return;
+
if (req.method !== 'GET' && req.method !== 'HEAD') {
res.setHeader('allow', 'GET, HEAD');
return error(res, 405, 'method_not_allowed', 'method not allowed');
diff --git a/prompts/swarm-100/api-top-03.md b/prompts/swarm-100/api-top-03.md
deleted file mode 100644
index 4238db6a5..000000000
--- a/prompts/swarm-100/api-top-03.md
+++ /dev/null
@@ -1,110 +0,0 @@
-# API audit: api/*.js batch 03 (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/agent-strategy.js
-- api/agent-task.js
-- api/agent-vanity-grind.js
-- api/agent-wallet-bridge.js
-- api/agents.js
-- api/api-keys.js
-- api/app-og.js
-- api/ar.js
-- api/artifact.js
-- api/asl-recognition.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-03.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/api-studio-retexture-region.test.js b/tests/api-studio-retexture-region.test.js
index a51e2098d..0bba0a383 100644
--- a/tests/api-studio-retexture-region.test.js
+++ b/tests/api-studio-retexture-region.test.js
@@ -52,7 +52,7 @@ vi.mock('../api/_lib/ssrf-guard.js', () => ({
const WORKER = 'https://texture-worker.test';
const { default: handler } = await import('../api/studio/retexture-region.js');
-const MESH = 'https://cdn.three.ws/models/avatar.glb';
+const MESH = 'https://three.ws/cdn/models/avatar.glb';
const MASK = 'iVBORw0KGgoAAAANSUhEUg==';
function mkReq({ method = 'GET', url = '/api/studio/retexture-region', headers = {}, body = null } = {}) {
@@ -129,7 +129,7 @@ beforeEach(() => {
return {
ok: true,
status: 200,
- json: async () => ({ status: 'done', result_url: 'https://cdn.three.ws/out/avatar-retex.glb' }),
+ json: async () => ({ status: 'done', result_url: 'https://three.ws/cdn/out/avatar-retex.glb' }),
};
}
throw new Error(`unexpected fetch: ${u}`);
@@ -185,7 +185,7 @@ describe('POST /api/studio/retexture-region — the success path', () => {
expect(body).toMatchObject({
ok: true,
status: 'done',
- result_url: 'https://cdn.three.ws/out/avatar-retex.glb',
+ result_url: 'https://three.ws/cdn/out/avatar-retex.glb',
error: null,
});
expect(workerCalls[1].url).toBe(`${WORKER}/tasks/task-42`);
diff --git a/tests/api/app-og.test.js b/tests/api/app-og.test.js
new file mode 100644
index 000000000..7e1077be1
--- /dev/null
+++ b/tests/api/app-og.test.js
@@ -0,0 +1,128 @@
+// Integration tests for GET /api/app-og, the server-rendered share card a
+// social crawler gets when it hits /app?agent=<uuid>.
+//
+// The regression this file exists for: the handler declared a local
+// `const thumbnailUrl` initialized by calling the imported `thumbnailUrl()`
+// helper. The local binding shadows the import across the whole function body,
+// so the initializer's own call landed in the temporal dead zone and threw
+// ReferenceError for every agent that HAS a thumbnail, which is the only case
+// the route exists to serve. Crawlers got a 500 with no OG tags at all.
+//
+// No network and no mocked HTTP layer: the real handler runs against mocked
+// req/res objects (the pattern in tests/api/avatar-og.test.js), so the assertions
+// exercise the real HTML builder.
+
+import { describe, it, expect, vi, beforeEach } from 'vitest';
+
+const sqlMock = vi.fn(async () => []);
+
+vi.mock('../../api/_lib/db.js', () => ({
+ sql: (...a) => sqlMock(...a),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+vi.mock('../../api/_lib/r2.js', () => ({
+ thumbnailUrl: (k) => `https://cdn.test/${k}`,
+}));
+vi.mock('../../api/_lib/env.js', () => ({ env: { APP_ORIGIN: 'https://three.ws' } }));
+vi.mock('../../api/_lib/zauth.js', () => ({ instrument: () => {}, drain: async () => {} }));
+vi.mock('../../api/_lib/sentry.js', () => ({ captureException: () => {} }));
+
+const { default: handler } = await import('../../api/app-og.js');
+
+const AGENT_UUID = 'fce196ec-aaa1-417e-bb9c-e8a5b4d9f945';
+
+function mkReq(qs = `agent=${AGENT_UUID}`, method = 'GET') {
+ return { method, url: `/api/app-og?${qs}`, headers: { host: 'three.ws' } };
+}
+
+function mkRes() {
+ return {
+ statusCode: 200,
+ _h: {},
+ _body: undefined,
+ writableEnded: false,
+ setHeader(k, v) { this._h[k.toLowerCase()] = v; },
+ getHeader(k) { return this._h[k.toLowerCase()]; },
+ end(b) { this._body = b; this.writableEnded = true; },
+ };
+}
+
+const AGENT_WITH_THUMBNAIL = {
+ id: AGENT_UUID,
+ name: 'Aurora',
+ description: 'A research agent.',
+ avatar_id: '5b888ec3-bca3-4d9e-bdab-c802bb35f6a0',
+ skills: ['greet', 'think'],
+ avatar_thumbnail_key: 'u/272dc4a6/draft-bb4pq9/mp4b08rd_og.png',
+ avatar_storage_key: 'u/272dc4a6/draft-bb4pq9/mp4b08rd.glb',
+ avatar_visibility: 'public',
+};
+
+beforeEach(() => {
+ sqlMock.mockReset();
+ sqlMock.mockResolvedValue([]);
+});
+
+describe('GET /api/app-og', () => {
+ it('renders the card with the avatar thumbnail as og:image', async () => {
+ sqlMock.mockResolvedValueOnce([AGENT_WITH_THUMBNAIL]);
+ const res = mkRes();
+ await handler(mkReq(), res);
+
+ expect(res.statusCode).toBe(200);
+ expect(res.getHeader('content-type')).toMatch(/text\/html/);
+ expect(res._body).toContain(
+ '<meta property="og:image" content="https://cdn.test/u/272dc4a6/draft-bb4pq9/mp4b08rd_og.png">',
+ );
+ expect(res._body).toMatch(/<meta property="og:title" content="Aurora .{1,3}three\.ws">/);
+ });
+
+ it('falls back to the rendered agent OG image when the avatar has no thumbnail', async () => {
+ sqlMock.mockResolvedValueOnce([{ ...AGENT_WITH_THUMBNAIL, avatar_thumbnail_key: null }]);
+ const res = mkRes();
+ await handler(mkReq(), res);
+
+ expect(res.statusCode).toBe(200);
+ expect(res._body).toContain(
+ `<meta property="og:image" content="https://three.ws/api/agent/${AGENT_UUID}/og">`,
+ );
+ });
+
+ it('appends the agent skills to the description', async () => {
+ sqlMock.mockResolvedValueOnce([AGENT_WITH_THUMBNAIL]);
+ const res = mkRes();
+ await handler(mkReq(), res);
+
+ expect(res._body).toContain('Skills: greet, think.');
+ });
+
+ it('escapes HTML in the agent name so a crafted name cannot inject markup', async () => {
+ sqlMock.mockResolvedValueOnce([
+ { ...AGENT_WITH_THUMBNAIL, name: '<script>alert(1)</script>', description: null },
+ ]);
+ const res = mkRes();
+ await handler(mkReq(), res);
+
+ expect(res._body).not.toContain('<script>alert(1)</script>');
+ expect(res._body).toContain('&lt;script&gt;alert(1)&lt;/script&gt;');
+ });
+
+ it('redirects to /app for a non-UUID agent param without touching the DB', async () => {
+ const res = mkRes();
+ await handler(mkReq('agent=not-a-uuid'), res);
+
+ expect(res.statusCode).toBe(302);
+ expect(res.getHeader('location')).toBe('/app');
+ expect(sqlMock).not.toHaveBeenCalled();
+ });
+
+ it('redirects to /app when the agent does not exist', async () => {
+ sqlMock.mockResolvedValueOnce([]);
+ const res = mkRes();
+ await handler(mkReq(), res);
+
+ expect(res.statusCode).toBe(302);
+ expect(res.getHeader('location')).toBe('/app');
+ });
+});