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.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(agent-api): stop a mistyped id or mint 500ing, and keep share cards alive without a bucket
nirholas163fbb5f1f8d
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 21ca8caeb..7389cc03b 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,7 @@ Public history for [three.ws](https://three.ws), newest first. New pages come fr- **A coin world link now unfurls as the live world, and only ever points at three.ws**: Pasting a coin community link into WordPress, Ghost, Discord, Notion or any editor built on embed.ly or iframely now turns it into the live 3D world instead of a plain link. The service that answers those editors existed but nothing on the page told them where to find it, so it was never called. Two problems in that service are fixed at the same time. It used to build the embed from the address in the incoming request rather than from the site address, so a crafted request could hand an editor an embed that framed somebody else site under the three.ws name; the embed is now always built from three.ws itself. And it used to answer for any link at all, returning a generic three.ws world card for a link that was never ours; it now says plainly that the link is not one of ours. It also answers in both of the formats the standard defines, and ignores a coin address that is not a real Solana address instead of putting it in the embed. Separately, the share images for pages and coin worlds, the holder leaderboard card, the free model verification check and the Oracle coin page now accept only read requests, and answer anything else with a clear message rather than doing the work anyway. (`/play`) `[fix, security]`- **A mistyped id on the signal marketplace answers plainly, and the live feed links to the right chain**: The signal marketplace identifies a feed or a subscription by a number. Anything that was not one (a typo, a stray word, an empty box) went straight to the database, which threw the whole query out, so the caller got an opaque "something went wrong" and our alerting recorded a fault that was never a fault. Pausing a feed, killing or resyncing a subscription, and subscribing to a feed each now answer with a plain "that is not a valid id" instead. Separately, the paid live signal stream built its Solscan links from whichever network the request named rather than the one the feed actually publishes on, so a subscriber could be handed devnet explorer links for a mainnet call; the feed's own record now decides, and every proof link lands on the chain the trade really happened on. (`/signals`) `[fix]`- **Agent attestations that stopped indexing now recover on their own**: An agent's on-chain attestation history is indexed by walking Solana signatures newer than the last one we recorded. If that recorded signature aged out of the RPC node's history, the walk failed outright and kept failing: the same dead signature was replayed on every run, so that agent's attestations silently stopped appearing on its profile while the scheduled job still reported success. The crawler now recognises that case, re-scans from the most recent signatures instead, and clears the stale marker, so an agent that fell behind catches up by itself on the next pass. `[fix, infra]`+- **Agent share cards survive an unconfigured bucket, and a mistyped payment mint is refused instead of listed**: An audit of the agent endpoints turned up four things worth fixing. A skill price set through /api/agents/:id/skills/set-price accepted any text as its payment mint and saved it, so a typo produced a listing nobody could actually pay; it now has to be a real base58 address, matching the other door onto the same table. The agent share page and its OG image used to answer a social crawler with a hard error whenever object storage was not configured, instead of falling back to the plain card they already knew how to draw. A mistyped agent id in the diary, skill-price and screen-push endpoints came back as a server error rather than the plain "that is not an agent id" it is. And an agent screen with no live frame store now tells you the agent is offline right away instead of leaving you on "Connecting" for five minutes. `[fix, improvement]`- **An expired X connection now offers to reconnect instead of sending you to the login page**: Posting a Walk screenshot or clip to X goes through your connected X account. When that connection could no longer be renewed, the share endpoint answered with the same code it uses for a signed-out visitor, so the capture panel told an already signed-in user to sign in to three.ws and linked them to the login page, which fixed nothing. That case now comes back as its own answer with the X connect link attached, and the panel offers a Reconnect X button that takes you straight to the flow that repairs it. The share caption also lost a stray dash. (`/walk`) `[fix]`- **Avatar Studio trait library: the mirror can no longer be pointed at someone else's server**: Avatar Studio loads its hair, clothing and accessory traits through a three.ws address that mirrors the open-source trait library, so your browser never talks to an outside CDN. The list of where those traits live was being written using the address in the incoming request, and that address can be set by whoever sends the request. Because the mirror is cached at the edge for a day, one crafted request could have left every Avatar Studio visitor loading trait files from a stranger's server for the next 24 hours. That list is now written the same way for everybody, with no part of it taken from the request, so there is nothing left to steer. Three smaller repairs went in alongside it: asking the mirror how big a file is no longer answers with the compressed size (a trait manifest claimed 2 KB and delivered 20 KB), the mirror will not hand back a web page or script even if the upstream library ever served one, and a failure at the library now answers plainly as either not found or mirror is down instead of passing its raw status through as ours. (`/avatar-studio`) `[security, fix]`- **Corrected stale numbers across the avatar and animation docs**: An audit of eight documentation pages against the code they describe turned up four claims that had drifted. The Animations page said the motion-capture library held about 2,000 clips when it actually serves 2,874, so both the intro and the gallery section now quote the real size and point at the count the API itself returns. The selfie-to-avatar page listed the wrong default for the face-morph displacement clamp and credited a single tuning sweep instead of the two that chose it. The avatar-creation walkthrough still told people to pick a body type on the selfie flow, a control that was deliberately removed because it changed nothing, and named the wrong fields on the event the page dispatches. The architecture page now says plainly that the whitelist trust mode is reserved rather than enforced. (`/docs/animations`) `[docs]`diff --git a/api/agent-og.js b/api/agent-og.jsindex 652111d55..3a36f0f44 100644--- a/api/agent-og.js+++ b/api/agent-og.js@@ -39,7 +39,11 @@ export default wrap(async (req, res) => {if (!agent) return sendNotFound(res);if (agent.avatar_id) {- const avatar = await getAvatar({ id: agent.avatar_id });+ // getAvatar() derives its urls through env.S3_PUBLIC_DOMAIN, which THROWS when+ // object storage isn't configured on a deployment. That must degrade to the SVG+ // card this handler already promises, never to a 503 in a crawler's face: the+ // same rule api/og/agent.js follows for the identical hazard.+ const avatar = await getAvatar({ id: agent.avatar_id }).catch(() => null);if (avatar?.thumbnail_url) {res.statusCode = 302;res.setHeader('location', avatar.thumbnail_url);diff --git a/api/agent-reflect-digest.js b/api/agent-reflect-digest.jsindex 1a05f2806..215690591 100644--- a/api/agent-reflect-digest.js+++ b/api/agent-reflect-digest.js@@ -26,6 +26,7 @@ import { sql } from './_lib/db.js';import { cors, json, method, wrap, error } from './_lib/http.js';import { buildGraph } from './_lib/memory-store.js';import { llmComplete, llmConfigured, LlmUnavailableError } from './_lib/llm.js';+import { isUuid } from './_lib/validate.js';import { shapeDigestEntities, digestCounts } from '../src/agent-memory-graph.js';// How far back to look when the caller doesn't pass `since` — a rolling day.@@ -50,6 +51,10 @@ export default wrap(async (req, res) => {const url = new URL(req.url, 'http://x');const agentId = url.searchParams.get('agentId') || url.searchParams.get('agent_id');if (!agentId) return error(res, 400, 'validation_error', 'agentId required');+ // agent_identities.id is a uuid column: handing Postgres a non-uuid throws+ // 22P02, which turns a plain client typo into a 500 plus a Sentry event and an+ // ops alert. Reject the shape here, alongside the missing-id check.+ if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'agentId must be a uuid');const auth = await resolveAuth(req);if (!auth) return error(res, 401, 'unauthorized', 'sign in to read your agent\'s diary');diff --git a/api/agent-screen-active.js b/api/agent-screen-active.jsindex 8bf1335be..d16ec3d7b 100644--- a/api/agent-screen-active.js+++ b/api/agent-screen-active.js@@ -9,7 +9,7 @@// scene passes ?env=<envName> to bias placement within that environment's// coordinate space.-import { cors, json, method, rateLimited } from './_lib/http.js';+import { cors, json, method, rateLimited, wrap } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import { getRedis } from './_lib/redis.js';import { sql } from './_lib/db.js';@@ -24,7 +24,10 @@ const DESK_SLOTS = [];const MAX_DESKS = 4;-export default async function handleAgentScreenActive(req, res) {+// wrap(): an unhandled fault here must land the platform's sanitized envelope+// with a correlation ref, a Sentry capture and an ops alert, not the container's+// bare "The request failed unexpectedly" catch-all that tells nobody anything.+export default wrap(async function handleAgentScreenActive(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS' })) return;if (!method(req, res, ['GET'])) return;@@ -87,4 +90,4 @@ export default async function handleAgentScreenActive(req, res) {});return json(res, 200, { desks }, { 'cache-control': 'no-store' });-}+});diff --git a/api/agent-screen-control-drain.js b/api/agent-screen-control-drain.jsindex 9cf83ddac..98cf74143 100644--- a/api/agent-screen-control-drain.js+++ b/api/agent-screen-control-drain.js@@ -13,7 +13,7 @@// events, sanitized input events in dispatch order (oldest first), drainedimport { timingSafeEqual } from 'node:crypto';-import { cors, error, json, method, readJson } from './_lib/http.js';+import { cors, error, json, method, readJson, wrap } from './_lib/http.js';import { extractBearer } from './_lib/auth.js';import { getRedis } from './_lib/redis.js';@@ -31,7 +31,10 @@ function isPoolWorker(bearer) {const leaseKey = (id) => `agent:screen:${id}:ctl:lease`;const queueKey = (id) => `agent:screen:${id}:ctl:q`;-export default async function handleAgentScreenControlDrain(req, res) {+// wrap(): an unhandled fault here must land the platform's sanitized envelope+// with a correlation ref, a Sentry capture and an ops alert, not the container's+// bare "The request failed unexpectedly" catch-all that tells nobody anything.+export default wrap(async function handleAgentScreenControlDrain(req, res) {if (cors(req, res, { methods: 'POST,OPTIONS' })) return;if (!method(req, res, ['POST'])) return;@@ -77,4 +80,4 @@ export default async function handleAgentScreenControlDrain(req, res) {}));return json(res, 200, { agents });-}+});diff --git a/api/agent-screen-control.js b/api/agent-screen-control.jsindex 7e80457ca..b9e750727 100644--- a/api/agent-screen-control.js+++ b/api/agent-screen-control.js@@ -27,7 +27,7 @@// release , bearer lease token; drops the lease immediatelyimport crypto from 'node:crypto';-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, extractBearer } from './_lib/auth.js';import { requireCsrf } from './_lib/csrf.js';import { limits, clientIp } from './_lib/rate-limit.js';@@ -65,7 +65,10 @@ function timingEqual(a, b) {}}-export default async function handleAgentScreenControl(req, res) {+// wrap(): an unhandled fault here must land the platform's sanitized envelope+// with a correlation ref, a Sentry capture and an ops alert, not the container's+// bare "The request failed unexpectedly" catch-all that tells nobody anything.+export default wrap(async function handleAgentScreenControl(req, res) {if (cors(req, res, { methods: 'POST,OPTIONS' })) return;if (!method(req, res, ['POST'])) return;@@ -154,4 +157,4 @@ export default async function handleAgentScreenControl(req, res) {await r.expire(queueKey(agentId), QUEUE_TTL_S);return json(res, 200, { ok: true, accepted: events.length });-}+});diff --git a/api/agent-screen-push.js b/api/agent-screen-push.jsindex 5a5ffe9ae..17870476f 100644--- a/api/agent-screen-push.js+++ b/api/agent-screen-push.js@@ -20,11 +20,12 @@// for the activity log panel.import { timingSafeEqual } from 'node:crypto';-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';import { sql } from './_lib/db.js';+import { isUuid } from './_lib/validate.js';import { sanitizeFrameMeta } from '../src/shared/forge-frames.js';// First-party on-demand caster pool (workers/agent-screen-pool) authenticates@@ -99,7 +100,7 @@ export function shouldLogEntry({ activity, pnl, meta, mm }) {return Boolean(activity || pnl || meta || mm);}-export default async function handleAgentScreenPush(req, res) {+export default wrap(async function handleAgentScreenPush(req, res) {if (cors(req, res, { methods: 'POST,OPTIONS' })) return;if (!method(req, res, ['POST'])) return;@@ -139,6 +140,12 @@ export default async function handleAgentScreenPush(req, res) {if (!agentId || typeof agentId !== 'string') {return error(res, 400, 'missing_agent_id', 'agentId is required');}+ // agent_identities.id is a uuid column, so a non-uuid throws 22P02 on the+ // ownership lookup below and a caster typo becomes a 500 instead of the 400 it+ // is. Reject the shape before it reaches Postgres.+ if (!isUuid(agentId)) {+ return error(res, 400, 'invalid_agent_id', 'agentId must be a uuid');+ }if (!frame || typeof frame !== 'object') {return error(res, 400, 'missing_frame', 'frame object is required');}@@ -200,4 +207,4 @@ export default async function handleAgentScreenPush(req, res) {]);return json(res, 200, { ok: true, ts: now });-}+});diff --git a/api/agent-screen-stream.js b/api/agent-screen-stream.jsindex 6289742f7..d2e14dd89 100644--- a/api/agent-screen-stream.js+++ b/api/agent-screen-stream.js@@ -20,7 +20,7 @@// The stream runs for up to 280s (Vercel limit 300s — budget for setup/teardown).// Clients reconnect automatically via EventSource's built-in retry.-import { cors, method, rateLimited } from './_lib/http.js';+import { cors, error, method, rateLimited, wrap } from './_lib/http.js';import { limits, clientIp } from './_lib/rate-limit.js';import { getRedis } from './_lib/redis.js';import { sql } from './_lib/db.js';@@ -88,7 +88,11 @@ async function fetchDbActivity(agentId) {return rows.map(rowToEntry).reverse();}-export default async function handleAgentScreenStream(req, res) {+// wrap(): a fault raised before the SSE head is written must land the platform's+// sanitized envelope with a correlation ref, a Sentry capture and an ops alert.+// Once the head is out, the loop below owns its own errors and wrap()'s+// headersSent guard keeps it from writing a second response over the stream.+export default wrap(async function handleAgentScreenStream(req, res) {if (cors(req, res, { methods: 'GET,OPTIONS' })) return;if (!method(req, res, ['GET'])) return;@@ -97,21 +101,16 @@ export default async function handleAgentScreenStream(req, res) {const url = new URL(req.url, `http://${req.headers.host || 'x'}`);const agentId = (url.searchParams.get('agentId') || '').trim();- if (!agentId) {- res.writeHead(400, { 'Content-Type': 'application/json' });- res.end(JSON.stringify({ error: 'agentId is required' }));- return;- }+ // Answer pre-stream faults through the shared error() envelope so an SSE client+ // reads the same { error, error_description } shape every other endpoint emits,+ // with the standard no-store + nosniff headers.+ if (!agentId) return error(res, 400, 'validation_error', 'agentId is required');// Resolve agent name for the open eventconst [agentRow] = await sql`SELECT name FROM agent_identities WHERE id = ${agentId} LIMIT 1`.catch(() => []);- if (!agentRow) {- res.writeHead(404, { 'Content-Type': 'application/json' });- res.end(JSON.stringify({ error: 'agent not found' }));- return;- }+ if (!agentRow) return error(res, 404, 'not_found', 'agent not found');const r = getRedis();@@ -174,6 +173,14 @@ export default async function handleAgentScreenStream(req, res) {const reactionTotalKey = reactionsTotalKey(agentId);let lastTs = 0;let wasDark = false;+ // With no frame store configured there is nothing to poll, so the loop below+ // never reaches its dark branch and the viewer would sit on "Connecting…" for+ // the whole 280s. Say it once up front instead; the DB activity backfill above+ // and its refresh below still keep the panel meaningful.+ if (!r) {+ wasDark = true;+ send('dark', {});+ }// Only replay reactions that arrive AFTER this viewer connects — joining mid// stream shouldn't dump a backlog of bursts. But do send the current windowed// total straight away so the live count is correct the instant the bar mounts.@@ -263,4 +270,4 @@ export default async function handleAgentScreenStream(req, res) {};loop().catch(() => { if (!res.writableEnded) res.end(); });-}+});diff --git a/api/agent-share.js b/api/agent-share.jsindex 50e8ea530..9edb1213b 100644--- a/api/agent-share.js+++ b/api/agent-share.js@@ -62,8 +62,13 @@ export default wrap(async (req, res) => {}}- // Build public thumbnail URL for OG image- const CDN_BASE = env.S3_PUBLIC_DOMAIN || `${origin}/cdn`;+ // Build public thumbnail URL for OG image.+ // Read the bucket domain off process.env rather than env.S3_PUBLIC_DOMAIN: that+ // getter THROWS when the var is unset, so the `|| ${origin}/cdn` fallback below+ // could never run and an unconfigured deployment answered every crawler with a+ // 503 not_configured instead of a share card. Same rule api/og/agent.js follows:+ // a missing bucket domain degrades the image, it never 503s a crawler.+ const CDN_BASE = (process.env.S3_PUBLIC_DOMAIN || '').trim().replace(/\/$/, '') || `${origin}/cdn`;const thumbKey = row.thumbnail_key;const thumbVis = row.visibility;const thumbPublic = thumbVis === 'public' || thumbVis === 'unlisted';diff --git a/api/agent-skill-price.js b/api/agent-skill-price.jsindex 615a6f524..cb3df0ea2 100644--- a/api/agent-skill-price.js+++ b/api/agent-skill-price.js@@ -10,6 +10,7 @@ import { cors, error, json, method, readJson, wrap, rateLimited } from './_lib/himport { requireCsrf } from './_lib/csrf.js';import { clientIp, limits } from './_lib/rate-limit.js';import { invalidateSkillPriceCache } from './_lib/skill-price-cache.js';+import { isUuid } from './_lib/validate.js';import { z } from 'zod';const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;@@ -44,6 +45,10 @@ export default wrap(async (req, res) => {const url = new URL(req.url, 'http://x');const agentId = url.searchParams.get('agentId');if (!agentId) return error(res, 400, 'validation_error', 'agentId query param required');+ // agent_identities.id is a uuid column: a non-uuid throws 22P02 in Postgres and+ // surfaces as a 500 (plus a Sentry event and an ops alert) for what is plainly a+ // client fault. Reject the shape before it reaches the query.+ if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'agentId must be a uuid');const [agent] = await sql`SELECT id, user_id FROM agent_identitiesdiff --git a/api/agent-skills.js b/api/agent-skills.jsindex a6ab59787..dcadae4e6 100644--- a/api/agent-skills.js+++ b/api/agent-skills.js@@ -9,16 +9,28 @@ import { cors, error, json, method, readJson, wrap, rateLimited } from './_lib/himport { requireCsrf } from './_lib/csrf.js';import { clientIp, limits } from './_lib/rate-limit.js';import { invalidateSkillPriceCache } from './_lib/skill-price-cache.js';+import { isUuid } from './_lib/validate.js';import { z } from 'zod';+// The price a buyer is quoted is paid to this mint, so it has to be a real+// base58 address. The sibling entry point (api/agent-skill-price.js) has always+// enforced that; this one accepted any 100-char string and wrote it straight to+// agent_skill_prices, so a typo became an unpayable listing. Same regex, so both+// doors onto the same table agree.+const BASE58_RE = /^[1-9A-HJ-NP-Za-km-z]{32,44}$/;+const setPriceSchema = z.object({skill: z.string().trim().min(1, 'skill required').max(100),amount: z.number().int().min(0, 'amount must be non-negative'),- currency_mint: z.string().trim().min(1, 'currency_mint required').max(100),+ currency_mint: z.string().trim().regex(BASE58_RE, 'invalid mint address'),chain: z.string().trim().min(1, 'chain required').max(20).default('solana'),});export default wrap(async (req, res) => {+ // CORS is settled once, for every action including the unknown-action 404 and+ // the OPTIONS preflight, so a browser caller can always read the answer.+ if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;+const url = new URL(req.url, 'http://x');const agentId = url.searchParams.get('agentId') || url.pathname.split('/').filter(Boolean)[2];const action = url.searchParams.get('action') || url.pathname.split('/').filter(Boolean)[4];@@ -29,7 +41,6 @@ export default wrap(async (req, res) => {});async function handleSetPrice(req, res, agentId) {- if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;const auth = await resolveAuth(req);@@ -41,6 +52,10 @@ async function handleSetPrice(req, res, agentId) {if (!rl.success) return rateLimited(res, rl);if (!agentId) return error(res, 400, 'validation_error', 'agentId required');+ // agent_identities.id is a uuid column: a non-uuid throws 22P02 in Postgres and+ // surfaces as a 500 (plus a Sentry event and an ops alert) for what is plainly a+ // client fault. Reject the shape before it reaches the query.+ if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'agentId must be a uuid');const [agent] = await sql`SELECT id, user_id FROM agent_identitiesdiff --git a/data/changelog.json b/data/changelog.jsonindex 1d2ab9a05..fab492c24 100644--- a/data/changelog.json+++ b/data/changelog.json@@ -1,6 +1,15 @@{"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.","entries": [+ {+ "date": "2026-08-16",+ "title": "Agent share cards survive an unconfigured bucket, and a mistyped payment mint is refused instead of listed",+ "summary": "An audit of the agent endpoints turned up four things worth fixing. A skill price set through /api/agents/:id/skills/set-price accepted any text as its payment mint and saved it, so a typo produced a listing nobody could actually pay; it now has to be a real base58 address, matching the other door onto the same table. The agent share page and its OG image used to answer a social crawler with a hard error whenever object storage was not configured, instead of falling back to the plain card they already knew how to draw. A mistyped agent id in the diary, skill-price and screen-push endpoints came back as a server error rather than the plain \"that is not an agent id\" it is. And an agent screen with no live frame store now tells you the agent is offline right away instead of leaving you on \"Connecting\" for five minutes.",+ "tags": [+ "fix",+ "improvement"+ ]+ },{"date": "2026-08-16","title": "The AWS page stops promising AWS invoicing three.ws does not do, and the GLB optimizer reads compressed avatars again",diff --git a/prompts/swarm-100/api-top-02.md b/prompts/swarm-100/api-top-02.mddeleted file mode 100644index 1013ea241..000000000--- a/prompts/swarm-100/api-top-02.md+++ /dev/null@@ -1,110 +0,0 @@-# API audit: api/*.js batch 02 (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-og.js-- api/agent-reflect-digest.js-- api/agent-screen-active.js-- api/agent-screen-control-drain.js-- api/agent-screen-control.js-- api/agent-screen-push.js-- api/agent-screen-stream.js-- api/agent-share.js-- api/agent-skill-price.js-- api/agent-skills.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-02.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/public/changelog.json b/public/changelog.jsonindex 00efb834e..935e7470a 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-08-16T08:06:17.799Z",+ "generated_at": "2026-08-16T08:12:02.988Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -38,6 +38,17 @@"infra"]},+ {+ "date": "2026-08-16",+ "type": "update",+ "title": "Agent share cards survive an unconfigured bucket, and a mistyped payment mint is refused instead of listed",+ "summary": "An audit of the agent endpoints turned up four things worth fixing. A skill price set through /api/agents/:id/skills/set-price accepted any text as its payment mint and saved it, so a typo produced a listing nobody could actually pay; it now has to be a real base58 address, matching the other door onto the same table. The agent share page and its OG image used to answer a social crawler with a hard error whenever object storage was not configured, instead of falling back to the plain card they already knew how to draw. A mistyped agent id in the diary, skill-price and screen-push endpoints came back as a server error rather than the plain \"that is not an agent id\" it is. And an agent screen with no live frame store now tells you the agent is offline right away instead of leaving you on \"Connecting\" for five minutes.",+ "link": null,+ "tags": [+ "fix",+ "improvement"+ ]+ },{"date": "2026-08-16","type": "update",diff --git a/public/changelog.xml b/public/changelog.xmlindex c9587c90c..26d2132cb 100644--- a/public/changelog.xml+++ b/public/changelog.xml@@ -30,6 +30,14 @@<category>fix</category><description>An agent's on-chain attestation history is indexed by walking Solana signatures newer than the last one we recorded. If that recorded signature aged out of the RPC node's history, the walk failed outright and kept failing: the same dead signature was replayed on every run, so that agent's attestations silently stopped appearing on its profile while the scheduled job still reported success. The crawler now recognises that case, re-scans from the most recent signatures instead, and clears the stale marker, so an agent that fell behind catches up by itself on the next pass.</description></item>+ <item>+ <title>Agent share cards survive an unconfigured bucket, and a mistyped payment mint is refused instead of listed</title>+ <link>https://three.ws/changelog</link>+ <guid isPermaLink="false">2026-08-16:Agent share cards survive an unconfigured bucket, and a mistyped payment mint is refused instead of listed</guid>+ <pubDate>Sun, 16 Aug 2026 12:00:00 GMT</pubDate>+ <category>fix</category>+ <description>An audit of the agent endpoints turned up four things worth fixing. A skill price set through /api/agents/:id/skills/set-price accepted any text as its payment mint and saved it, so a typo produced a listing nobody could actually pay; it now has to be a real base58 address, matching the other door onto the same table. The agent share page and its OG image used to answer a social crawler with a hard error whenever object storage was not configured, instead of falling back to the plain card they already knew how to draw. A mistyped agent id in the diary, skill-price and screen-push endpoints came back as a server error rather than the plain "that is not an agent id" it is. And an agent screen with no live frame store now tells you the agent is offline right away instead of leaving you on "Connecting" for five minutes.</description>+ </item><item><title>An expired X connection now offers to reconnect instead of sending you to the login page</title><link>https://three.ws/walk</link>diff --git a/tests/agent-endpoints-input-guards.test.js b/tests/agent-endpoints-input-guards.test.jsnew file mode 100644index 000000000..84862c49d--- /dev/null+++ b/tests/agent-endpoints-input-guards.test.js@@ -0,0 +1,288 @@+/**+ * Input guards + degraded-config behaviour for the agent-facing api/*.js batch:+ * agent-og, agent-share, agent-reflect-digest, agent-skill-price, agent-skills,+ * agent-screen-push, agent-screen-stream.+ *+ * Every case here is a defect these endpoints actually shipped, found by curling+ * them against a local server on 2026-08-16:+ *+ * 1. agent_identities.id is a uuid column. Four handlers interpolated a+ * caller-supplied agentId straight into it, so `?agentId=notauuid` threw+ * Postgres 22P02 and answered 500 (with a Sentry event and an ops alert per+ * hit) for what is plainly a 400. api/agent-og.js had already documented and+ * fixed the trap; its neighbours had not.+ * 2. /api/agents/:id/skills/set-price accepted ANY 100-char string as+ * currency_mint and wrote it to agent_skill_prices, while the sibling entry+ * point onto the same table enforced base58. A typo became a listing whose+ * quoted price is payable to nothing.+ * 3. Both share surfaces 503'd a crawler when S3_PUBLIC_DOMAIN was unset:+ * agent-share's `env.S3_PUBLIC_DOMAIN || fallback` could never reach the+ * fallback (the getter throws), and agent-og let getAvatar's throw escape.+ * An unconfigured bucket must degrade the image, never the page.+ * 4. agent-screen-stream only emitted `dark` from inside its Redis poll, so+ * with no frame store configured a viewer sat on "Connecting…" for the full+ * 280s instead of being told the agent is offline.+ */++import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';++const sqlMock = vi.fn();+vi.mock('../api/_lib/db.js', () => ({+ sql: (...a) => sqlMock(...a),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+ isStoragePressured: async () => ({ pressured: false }),+}));++const getSessionUserMock = vi.fn();+const authenticateBearerMock = vi.fn();+vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: (...a) => getSessionUserMock(...a),+ authenticateBearer: (...a) => authenticateBearerMock(...a),+ extractBearer: (req) => {+ const h = req?.headers?.authorization || '';+ return h.startsWith('Bearer ') ? h.slice(7) : null;+ },+}));++vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));++vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: {+ apiIp: vi.fn(async () => ({ success: true, reset: 1_000 })),+ authIp: vi.fn(async () => ({ success: true, reset: 1_000 })),+ mcpIp: vi.fn(async () => ({ success: true, reset: 1_000 })),+ },+ clientIp: () => '203.0.113.24',+}));++vi.mock('../api/_lib/skill-price-cache.js', () => ({+ invalidateSkillPriceCache: vi.fn(async () => {}),+}));++const getRedisMock = vi.fn(() => null);+vi.mock('../api/_lib/redis.js', () => ({ getRedis: (...a) => getRedisMock(...a) }));++const getAvatarMock = vi.fn();+vi.mock('../api/_lib/avatars.js', () => ({ getAvatar: (...a) => getAvatarMock(...a) }));++const { default: agentOg } = await import('../api/agent-og.js');+const { default: agentShare } = await import('../api/agent-share.js');+const { default: reflectDigest } = await import('../api/agent-reflect-digest.js');+const { default: skillPrice } = await import('../api/agent-skill-price.js');+const { default: agentSkills } = await import('../api/agent-skills.js');+const { default: screenPush } = await import('../api/agent-screen-push.js');+const { default: screenStream } = await import('../api/agent-screen-stream.js');++const USER = '11111111-1111-4111-8111-111111111111';+const AGENT = 'aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa';+// $THREE, the only coin this platform promotes.+const MINT = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++function mkReq({ url = '/', method = 'GET', headers = {}, body = null } = {}) {+ const hdrs = { ...headers };+ if (body != null && !hdrs['content-type']) hdrs['content-type'] = 'application/json';+ const closers = [];+ return {+ method,+ url,+ headers: hdrs,+ // server/index.mjs pre-parses JSON bodies onto req.body; readJson reads it+ // from there rather than re-draining an already-ended stream.+ body: body == null ? undefined : body,+ on(evt, cb) { if (evt === 'close') closers.push(cb); },+ fireClose() { for (const cb of closers) cb(); },+ destroy() {},+ };+}++function mkRes() {+ return {+ statusCode: 200,+ headers: {},+ body: undefined,+ chunks: [],+ headersSent: false,+ writableEnded: false,+ setHeader(k, v) { this.headers[String(k).toLowerCase()] = v; },+ getHeader(k) { return this.headers[String(k).toLowerCase()]; },+ writeHead(status, hdrs = {}) {+ this.statusCode = status;+ for (const [k, v] of Object.entries(hdrs)) this.setHeader(k, v);+ this.headersSent = true;+ },+ flushHeaders() { this.headersSent = true; },+ write(chunk) { this.chunks.push(String(chunk)); return true; },+ end(b) { if (b != null) this.body = b; this.writableEnded = true; },+ };+}++const parseBody = (res) => (res.body ? JSON.parse(res.body) : undefined);++let s3Before;+beforeEach(() => {+ sqlMock.mockReset().mockResolvedValue([]);+ getSessionUserMock.mockReset().mockResolvedValue(null);+ authenticateBearerMock.mockReset().mockResolvedValue(null);+ getRedisMock.mockReset().mockReturnValue(null);+ getAvatarMock.mockReset().mockResolvedValue(null);+ s3Before = process.env.S3_PUBLIC_DOMAIN;+});+afterEach(() => {+ if (s3Before === undefined) delete process.env.S3_PUBLIC_DOMAIN;+ else process.env.S3_PUBLIC_DOMAIN = s3Before;+});++describe('a malformed agentId is a 400, never a Postgres 22P02 500', () => {+ it('agent-reflect-digest rejects it before the query runs', async () => {+ const res = mkRes();+ await reflectDigest(mkReq({ url: '/api/agent-reflect-digest?agentId=notauuid' }), res);+ expect(res.statusCode).toBe(400);+ expect(parseBody(res).error).toBe('validation_error');+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('agent-skill-price rejects it before the query runs', async () => {+ getSessionUserMock.mockResolvedValue({ id: USER });+ const res = mkRes();+ await skillPrice(mkReq({+ url: '/api/agent-skill-price?agentId=notauuid',+ method: 'POST',+ body: { skill: 's', amount: 1, currency_mint: MINT },+ }), res);+ expect(res.statusCode).toBe(400);+ expect(parseBody(res).error).toBe('validation_error');+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('agent-skills set-price rejects it before the query runs', async () => {+ getSessionUserMock.mockResolvedValue({ id: USER });+ const res = mkRes();+ await agentSkills(mkReq({+ url: '/api/agent-skills?agentId=notauuid&action=set-price',+ method: 'POST',+ body: { skill: 's', amount: 1, currency_mint: MINT },+ }), res);+ expect(res.statusCode).toBe(400);+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('agent-screen-push rejects it before the ownership lookup', async () => {+ getSessionUserMock.mockResolvedValue({ id: USER });+ const res = mkRes();+ await screenPush(mkReq({+ url: '/api/agent-screen-push',+ method: 'POST',+ body: { agentId: 'notauuid', frame: { activity: 'x' } },+ }), res);+ expect(res.statusCode).toBe(400);+ expect(parseBody(res).error).toBe('invalid_agent_id');+ expect(sqlMock).not.toHaveBeenCalled();+ });++ it('still serves a well-formed id', async () => {+ getSessionUserMock.mockResolvedValue({ id: USER });+ sqlMock.mockResolvedValue([]); // no such agent+ const res = mkRes();+ await reflectDigest(mkReq({ url: `/api/agent-reflect-digest?agentId=${AGENT}` }), res);+ expect(res.statusCode).toBe(404);+ expect(sqlMock).toHaveBeenCalled();+ });+});++describe('agent-skills set-price validates the mint it will quote a buyer', () => {+ const req = (mint) => mkReq({+ url: `/api/agent-skills?agentId=${AGENT}&action=set-price`,+ method: 'POST',+ body: { skill: 'render', amount: 5, currency_mint: mint },+ });++ beforeEach(() => {+ getSessionUserMock.mockResolvedValue({ id: USER });+ sqlMock.mockResolvedValue([{ id: AGENT, user_id: USER }]);+ });++ it('refuses a mint that is not a base58 address', async () => {+ const res = mkRes();+ await agentSkills(req('!!! not a mint !!!'), res);+ expect(res.statusCode).toBe(400);+ expect(parseBody(res).error_description).toBe('invalid mint address');+ });++ it('accepts a real base58 mint', async () => {+ const res = mkRes();+ await agentSkills(req(MINT), res);+ expect(res.statusCode).toBe(200);+ expect(parseBody(res)).toEqual({ data: { ok: true } });+ });++ it('answers an unknown action with CORS headers a browser can read', async () => {+ const res = mkRes();+ await agentSkills(mkReq({+ url: '/api/agent-skills?action=bogus',+ headers: { origin: 'https://three.ws' },+ }), res);+ expect(res.statusCode).toBe(404);+ expect(res.getHeader('access-control-allow-methods')).toBe('POST,OPTIONS');+ });+});++describe('an unconfigured bucket degrades the image, never the page', () => {+ beforeEach(() => {+ delete process.env.S3_PUBLIC_DOMAIN;+ });++ it('agent-share renders the card with an origin-relative CDN base', async () => {+ sqlMock.mockResolvedValue([{+ id: AGENT, name: 'Probe', description: 'A probe agent', chain_id: null,+ erc8004_agent_id: null, meta: null,+ thumbnail_key: 'u/owner/thumb.png', storage_key: 'u/owner/model.glb', visibility: 'public',+ }]);+ const res = mkRes();+ await agentShare(mkReq({ url: `/api/agent-share?id=${AGENT}` }), res);+ expect(res.statusCode).toBe(200);+ expect(res.getHeader('content-type')).toContain('text/html');+ expect(res.body).toContain('/cdn/u/owner/thumb.png');+ });++ it('agent-og falls back to the SVG card when the avatar url cannot be built', async () => {+ sqlMock.mockResolvedValue([{ id: AGENT, name: 'Probe', description: 'A probe agent', avatar_id: 'av-1' }]);+ getAvatarMock.mockRejectedValue(new Error('Missing required env var: S3_PUBLIC_DOMAIN'));+ const res = mkRes();+ await agentOg(mkReq({ url: `/api/agent-og?id=${AGENT}` }), res);+ expect(res.statusCode).toBe(200);+ expect(res.getHeader('content-type')).toContain('image/svg+xml');+ expect(res.body).toContain('Probe');+ });++ it('agent-og still 302s to a real thumbnail when one resolves', async () => {+ sqlMock.mockResolvedValue([{ id: AGENT, name: 'Probe', description: '', avatar_id: 'av-1' }]);+ getAvatarMock.mockResolvedValue({ thumbnail_url: 'https://cdn.example/thumb.png' });+ const res = mkRes();+ await agentOg(mkReq({ url: `/api/agent-og?id=${AGENT}` }), res);+ expect(res.statusCode).toBe(302);+ expect(res.getHeader('location')).toBe('https://cdn.example/thumb.png');+ });+});++describe('agent-screen-stream tells a viewer the agent is dark', () => {+ it('emits dark once up front when no frame store is configured', async () => {+ sqlMock.mockResolvedValue([{ name: 'Probe' }]);+ getRedisMock.mockReturnValue(null);+ const req = mkReq({ url: `/api/agent-screen-stream?agentId=${AGENT}` });+ const res = mkRes();+ await screenStream(req, res);+ req.fireClose(); // stop the poll loop the handler left running+ const sse = res.chunks.join('');+ expect(sse).toContain('event: open');+ expect(sse).toContain('event: dark');+ expect(sse.match(/event: dark/g)).toHaveLength(1);+ });++ it('answers a missing agentId through the shared error envelope', async () => {+ const res = mkRes();+ await screenStream(mkReq({ url: '/api/agent-screen-stream' }), res);+ expect(res.statusCode).toBe(400);+ expect(parseBody(res)).toMatchObject({ error: 'validation_error' });+ });+});