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(api): platform-wide hardening pass across genome, erc8004, forever, ibm, ledger, labor and the MCP servers
nirholas8c9bd83da9dc
diff --git a/.probe-neon.mjs b/.probe-neon.mjsnew file mode 100644index 000000000..0f770a5fa--- /dev/null+++ b/.probe-neon.mjs@@ -0,0 +1,6 @@+import { neon, neonConfig } from '@neondatabase/serverless';+neonConfig.fetchEndpoint = 'http://127.0.0.1:54490/sql';+neonConfig.useSecureWebSocket = false;+neonConfig.poolQueryViaFetch = true;+const sql = neon('postgres://postgres:[email protected]:5432/main');+console.log(await sql`select version()`);diff --git a/api/_lib/reasoning-ledger.js b/api/_lib/reasoning-ledger.jsindex c19df626a..eb72d1ea0 100644--- a/api/_lib/reasoning-ledger.js+++ b/api/_lib/reasoning-ledger.js@@ -412,8 +412,8 @@ export async function getChainEntries(agentId) {/*** Largest page this read will ever return. Exported so the HTTP layer validates- * against the SAME bound it will be clamped to here — a caller that asked for- * more than one page's worth would otherwise get a silently truncated page and a+ * against the SAME bound it will be clamped to here. A caller that asked for more+ * than one page's worth would otherwise get a silently truncated page and a* `next_before_seq: null` telling them the ledger ended.*/export const MAX_TIMELINE_LIMIT = 200;diff --git a/api/_mcp-studio/tools.js b/api/_mcp-studio/tools.jsindex 6f0743cd3..df5fa3b55 100644--- a/api/_mcp-studio/tools.js+++ b/api/_mcp-studio/tools.js@@ -234,6 +234,11 @@ function failureMessage(err) {return 'This capability is temporarily unavailable. Please try again later.';case 'generation_failed':return 'Generation failed for this prompt. Try again (a retry is routed to a healthy engine) or rephrase it.';+ // A dead handle, not a broken generator: the generic retry copy sent the+ // caller back to a probe that can never succeed. Point them at the one+ // action that does work.+ case 'unknown_job':+ return 'That job id is not recognized (it may be mistyped or expired). Start a new generation to get a fresh one.';default:return 'Could not generate the model right now. Please try again.';}@@ -467,22 +472,25 @@ async function handleForgeAvatar(args, _auth, req) {try {rigged = await rig(base, gen.glb_url, { timeoutEnv: 'STUDIO_RIG_TIMEOUT_MS' });} catch (err) {- // Generation succeeded but rigging failed — hand back the (unrigged) mesh so+ // Generation succeeded but rigging failed: hand back the (unrigged) mesh so// the work isn't lost, and say so plainly.+ // It rides the SAME ok() envelope as every other success, because this+ // hand-rolled one silently dropped what ok() adds: the /cdn rewrite (without+ // it a bucket-domain GLB is unfetchable inside ChatGPT's cross-origin widget+ // sandbox, so this path error-stated instead of showing the mesh it just+ // saved), the AR launch link, and the Spatial MCP artifact. Only the+ // narration differs, so a partial result stays as usable as a whole one.+ const partial = ok({ glbUrl: gen.glb_url, base, kind: 'mesh', prompt: prompt || undefined, referenceImageUrl: gen.preview_image_url });return {+ ...partial,content: [{type: 'text',- text: `Generated the mesh but auto-rigging failed (${failureMessage(err)}). You can still use the model: ${viewerUrl(base, gen.glb_url)}`,+ text:+ `Generated the mesh but auto-rigging failed (${failureMessage(err)}). The model itself is fine and ready to use.\n` ++ partial.content[0].text,},],- structuredContent: {- kind: 'mesh',- glbUrl: gen.glb_url,- viewerUrl: viewerUrl(base, gen.glb_url),- format: 'glb',- ...(prompt ? { prompt } : {}),- },};}if (rigged._timedOut && rigged.job_id) return pendingResult({ base, jobId: rigged.job_id, what: 'avatar rig', prompt: prompt || undefined, etaRemainingSeconds: rigged.eta_remaining_seconds });diff --git a/api/_mcpibm/tools.js b/api/_mcpibm/tools.jsindex e827fa58e..222b270a6 100644--- a/api/_mcpibm/tools.js+++ b/api/_mcpibm/tools.js@@ -211,7 +211,7 @@ const CHAT_DESCRIPTION =const chatTool = {name: 'ibm_granite_chat',- title: `IBM Granite Chat (${formatUsdPrice('ibm_granite_chat')})`,+ title: 'IBM Granite Chat ($0.02)',description: CHAT_DESCRIPTION,annotations: generativeAnnotations,inputSchema: {@@ -316,7 +316,7 @@ function buildCodeSystemPrompt(task, language) {const codeTool = {name: 'ibm_granite_code',- title: `IBM Granite Code (${formatUsdPrice('ibm_granite_code')})`,+ title: 'IBM Granite Code ($0.025)',description: CODE_DESCRIPTION,annotations: generativeAnnotations,inputSchema: {@@ -389,7 +389,7 @@ const EMBED_DESCRIPTION =const embedTool = {name: 'ibm_granite_embed',- title: `IBM Granite Embed (${formatUsdPrice('ibm_granite_embed')})`,+ title: 'IBM Granite Embed ($0.005)',description: EMBED_DESCRIPTION,annotations: deterministicAnnotations,inputSchema: {@@ -486,7 +486,7 @@ function buildAnalysisPrompt(analysis_type, language) {const analyzeTool = {name: 'ibm_granite_analyze',- title: `IBM Granite Analyze (${formatUsdPrice('ibm_granite_analyze')})`,+ title: 'IBM Granite Analyze ($0.04)',description: ANALYZE_DESCRIPTION,annotations: generativeAnnotations,inputSchema: {@@ -596,7 +596,7 @@ const FREQ_EXAMPLES = '1min, 5min, 15min, 30min, 1h, 2h, 4h, 12h, 1D, 1W, 1ME';const forecastTool = {name: 'ibm_granite_forecast',- title: `IBM Granite Forecast (${formatUsdPrice('ibm_granite_forecast')})`,+ title: 'IBM Granite Forecast ($0.05)',description: FORECAST_DESCRIPTION,annotations: generativeAnnotations,inputSchema: {diff --git a/api/_okx3d/identity.js b/api/_okx3d/identity.jsindex 36a0d07c0..52cd7edbc 100644--- a/api/_okx3d/identity.js+++ b/api/_okx3d/identity.js@@ -161,9 +161,11 @@ export function fallbackIdentityPrompt({ brief, styleHints }) {// The style hints ARE the visual direction, give them priority and their own// budget so a long brief can never crowd them out of the prompt.const hints = styleHints ? cleanClause(clampPrompt(styleHints, 90)) : '';- // First sentence only (handles both Latin ".!?" and CJK "。!?").+ // First sentence only. A Latin terminator is followed by a space; a CJK one+ // usually is not, so that branch splits on a zero-width boundary instead, or+ // a whole Chinese brief counts as one sentence and crowds out the hints.const raw = String(brief ?? '').trim();- const firstSentence = raw.split(/(?<=[.!?。!?])\s+/)[0] || raw;+ const firstSentence = raw.split(/(?<=[.!?])\s+|(?<=[。!?])\s*/)[0] || raw;const subject = cleanClause(clampPrompt(firstSentence, MAX_GENERATION_PROMPT_CHARS - 140 - (hints ? hints.length + 2 : 0)),);@@ -659,5 +661,3 @@ export function describeIdentityJob(state, { base = BASE } = {}) {}return body;}--export { loadState as loadIdentityJob };diff --git a/api/kol/[action].js b/api/kol/[action].jsindex 15410cbed..4f34cb63e 100644--- a/api/kol/[action].js+++ b/api/kol/[action].js@@ -1,8 +1,12 @@-// Consolidated KOL endpoints dispatcher.+// Consolidated KOL endpoints dispatcher: /api/kol/{wallets,import-gmgn,+// leaderboard,tracker}. The trade feed is the one KOL endpoint that lives in its+// own file (api/kol/trades.js) because an exact file outranks this [action].js+// in filesystem routing; see the DISPATCH note at the bottom.import { cors, json, method, readJson, wrap, error, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { requireAdmin } from '../_lib/admin.js';+import { createCache } from '../_lib/mem-cache.js';import { loadWallets, saveImportedWallets } from '../../src/kol/wallet-store.js';// ── wallets (Birdeye P&L proxy) ───────────────────────────────────────────────@@ -15,21 +19,20 @@ const CACHE_TTL_MS = 60_000;// row) for a full minute.const NEG_CACHE_TTL_MS = 15_000;const MAX_ADDRESSES = 20;-const _cache = new Map(); // address → { data, ts } (hit) | { error: true, ts } (miss)+// Keys are caller-supplied addresses, so an LRU bound (not a plain Map) is what+// keeps a long-lived container from growing one entry per address ever queried:+// the hand-rolled Map this replaced only ever dropped an entry that was asked+// for again after it expired, so junk keys accumulated forever. Per-entry TTLs+// still differ by outcome, which lru-cache takes on set().+// Value: { data } (hit) | { error: true } (miss).+const _cache = createCache({ max: 2_000 });function _getCached(addr) {- const entry = _cache.get(addr);- if (!entry) return null;- const ttl = entry.error ? NEG_CACHE_TTL_MS : CACHE_TTL_MS;- if (Date.now() - entry.ts > ttl) {- _cache.delete(addr);- return null;- }- return entry;+ return _cache.get(addr) ?? null;}function _setCache(addr, data) {- _cache.set(addr, { data, ts: Date.now() });+ _cache.set(addr, { data }, { ttl: CACHE_TTL_MS });}// Negative-cache a fetch failure instead of storing a normalized-from-null@@ -37,7 +40,7 @@ function _setCache(addr, data) {// flat wallet, so callers would render an upstream outage as legitimate KOL// data. A miss entry is filtered out of the response and refreshed sooner.function _setCacheError(addr) {- _cache.set(addr, { error: true, ts: Date.now() });+ _cache.set(addr, { error: true }, { ttl: NEG_CACHE_TTL_MS });}async function _fetchBirdeye(addr, apiKey) {@@ -193,35 +196,6 @@ async function handleLeaderboard(req, res) {return json(res, 200, { items });}-// ── trades ────────────────────────────────────────────────────────────────────--async function handleTrades(req, res) {- if (cors(req, res, { methods: 'GET,OPTIONS' })) return;- if (!method(req, res, ['GET'])) return;- // fetchKolTrades fans out one Helius call per tracked wallet — meter per IP.- const rl = await limits.mcpIp(clientIp(req));- if (!rl.success) return rateLimited(res, rl);- const url = new URL(req.url, 'http://x');- const mint = url.searchParams.get('mint');- const limit = Math.min(100, Math.max(1, Number(url.searchParams.get('limit') || '20')));- if (!mint) return error(res, 400, 'validation_error', 'mint is required');- const { KOL_WALLETS } = await import('../../src/kol/wallets.js');- const { fetchKolTrades } = await import('../../src/kol/trades.js');- let result;- try {- result = await fetchKolTrades({ mint, limit });- } catch (err) {- return error(- res,- err.status || 502,- err.code || 'provider_unavailable',- err.message || 'provider error',- );- }- res.setHeader('x-kol-source', result.source || 'unconfigured');- return json(res, 200, { mint, trades: result.trades, wallets: KOL_WALLETS.length });-}-// ── tracker ───────────────────────────────────────────────────────────────────async function handleTracker(req, res) {@@ -242,10 +216,13 @@ async function handleTracker(req, res) {// ── dispatcher ────────────────────────────────────────────────────────────────+// /api/kol/trades is deliberately absent: api/kol/trades.js is an exact file, so+// filesystem precedence resolves that path to it and any branch here would be+// unreachable code drifting away from the one that actually serves the feed.+// tests/api/kol-route-resolution.test.js pins that split.const DISPATCH = {'import-gmgn': handleImportGmgn,leaderboard: handleLeaderboard,- trades: handleTrades,tracker: handleTracker,wallets: handleWallets,};diff --git a/api/llm/anthropic.js b/api/llm/anthropic.jsindex 06906fba2..d7cee89f9 100644--- a/api/llm/anthropic.js+++ b/api/llm/anthropic.js@@ -985,7 +985,17 @@ export default wrap(async (req, res) => {// ── Shape translation: Anthropic ⇄ OpenAI ────────────────────────────────────-function anthropicBodyToOpenAI(body) {+// Providers that implement OpenAI's `stream_options.include_usage` contract.+// Without the flag a streaming completion carries no usage block at all, so the+// monthly token budget, the spend ledger, and the usage event all read zero for+// the lane embeds actually use (streaming is the default there). The rest of the+// providers are left alone on purpose: they either already emit usage on the+// final chunk (read opportunistically in pipeOpenAIAsAnthropic) or have not+// documented the field, and an unknown-parameter 400 would silently drop the+// lane out of the fallback chain.+const STREAM_USAGE_PROVIDERS = new Set(['openrouter', 'groq', 'nvidia', 'sambanova', 'grok']);++function anthropicBodyToOpenAI(body, { provider } = {}) {const messages = [];if (body.system) messages.push({ role: 'system', content: body.system });@@ -1043,6 +1053,9 @@ function anthropicBodyToOpenAI(body) {stream: !!body.stream,};if (typeof body.temperature === 'number') out.temperature = body.temperature;+ if (out.stream && STREAM_USAGE_PROVIDERS.has(provider)) {+ out.stream_options = { include_usage: true };+ }if (Array.isArray(body.tools) && body.tools.length) {out.tools = body.tools.map((t) => ({@@ -1160,8 +1173,10 @@ async function pipeOpenAIAsAnthropic(upstream, res, { model }) {closeTextBlockIfOpen();slot.anthropicIndex = nextBlockIndex++;slot.started = true;- slot.id = openAIToolCall.id || `tool_${slot.anthropicIndex}`;- slot.name = openAIToolCall.function?.name || slot.name || '';+ slot.id = openAIToolCall.id || slot.id || `tool_${slot.anthropicIndex}`;+ // The buffered name wins: it already carries this chunk's fragment plus+ // any earlier ones, while the chunk alone may hold only the last piece.+ slot.name = slot.name || openAIToolCall.function?.name || '';write({type: 'content_block_start',@@ -1174,6 +1189,22 @@ async function pipeOpenAIAsAnthropic(upstream, res, { model }) {function finishToolBlocks() {for (const slot of toolBlocks.values()) {+ // A call whose id never arrived has no open block yet. Open it now and+ // replay the buffered arguments: dropping it would leave the agent+ // silently not calling a tool the model asked for.+ if (!slot.started && (slot.name || slot.argsBuf)) {+ startToolBlock(slot, { id: slot.id, function: { name: slot.name } });+ if (slot.argsBuf) {+ write(+ {+ type: 'content_block_delta',+ index: slot.anthropicIndex,+ delta: { type: 'input_json_delta', partial_json: slot.argsBuf },+ },+ 'content_block_delta',+ );+ }+ }if (slot.started && !slot.finished) {write({ type: 'content_block_stop', index: slot.anthropicIndex },@@ -1203,9 +1234,12 @@ async function pipeOpenAIAsAnthropic(upstream, res, { model }) {continue;}- if (ev.usage) {- inputTokens = ev.usage.prompt_tokens ?? inputTokens;- outputTokens = ev.usage.completion_tokens ?? outputTokens;+ // Groq reports streaming usage under `x_groq.usage` on the final+ // chunk instead of the top-level field the OpenAI spec defines.+ const usage = ev.usage || ev.x_groq?.usage;+ if (usage) {+ inputTokens = usage.prompt_tokens ?? inputTokens;+ outputTokens = usage.completion_tokens ?? outputTokens;}const choice = ev.choices?.[0];@@ -1237,10 +1271,13 @@ async function pipeOpenAIAsAnthropic(upstream, res, { model }) {};toolBlocks.set(idx, slot);}- if (!slot.started && (tc.id || tc.function?.name)) {+ // The function name can stream in fragments ahead of the id, so+ // buffer it and open the block once the id lands (every provider+ // observed sends the name whole alongside it) or once the first+ // argument delta proves the name is complete.+ if (!slot.started && tc.function?.name) slot.name += tc.function.name;+ if (!slot.started && (tc.id || tc.function?.arguments != null)) {startToolBlock(slot, tc);- } else if (tc.function?.name && !slot.started) {- slot.name += tc.function.name;}if (tc.function?.arguments) {slot.argsBuf += tc.function.arguments;diff --git a/api/memory/context.js b/api/memory/context.jsindex 9023f8c3c..b2e747873 100644--- a/api/memory/context.js+++ b/api/memory/context.js@@ -14,6 +14,7 @@ import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.import { sql } from '../_lib/db.js';import { cors, json, method, wrap, error } from '../_lib/http.js';import { computeContext, WORKING_TOKEN_BUDGET } from '../_lib/memory-store.js';+import { isUuid } from '../_lib/validate.js';async function resolveAuth(req) {const session = await getSessionUser(req);@@ -38,6 +39,9 @@ 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: an unparseable id would otherwise reach+ // Postgres and 500 (22P02) instead of telling the caller their input is wrong.+ if (!isUuid(agentId)) return error(res, 400, 'validation_error', 'agentId must be a uuid');const auth = await resolveAuth(req);if (!auth) return json(res, 200, EMPTY);diff --git a/api/oauth/[action].js b/api/oauth/[action].jsindex 1abb7f078..36dfe9c01 100644--- a/api/oauth/[action].js+++ b/api/oauth/[action].js@@ -230,13 +230,46 @@ const registerSchema = z.object({client_uri: z.string().url().optional(),logo_uri: z.string().url().optional(),scope: z.string().max(500).optional(),- grant_types: z.array(z.string()).optional(),- response_types: z.array(z.string()).optional(),+ grant_types: z.array(z.string()).min(1).max(8).optional(),+ response_types: z.array(z.string()).min(1).max(8).optional(),token_endpoint_auth_method: z.enum(['none', 'client_secret_basic', 'client_secret_post']).optional(),software_id: z.string().max(120).optional(),software_version: z.string().max(60).optional(),});+// Schemes a browser or OS handler EXECUTES rather than navigates to. Zod's+// .url() is a bare `new URL()` check, so `javascript:alert(document.cookie)` and+// `data:text/html,<script>…` both pass it: without this list a self-registering+// client could park a script URL in oauth_clients, and the consent page would+// then splice its "origin" (the literal string `null`) into the CSP form-action+// allowlist and 302 the browser at it after approval.+const EXECUTABLE_URI_SCHEMES = new Set(['javascript:', 'data:', 'vbscript:', 'blob:', 'file:', 'about:', 'filesystem:', 'view-source:']);+// RFC 8252 §8.3 permits loopback redirects over plain http, IPv6 included.+const LOOPBACK_HOSTS = new Set(['localhost', '127.0.0.1', '[::1]']);++// Returns a rejection reason, or null when the URI is an acceptable target.+function redirectUriRejection(uri) {+ let u;+ try { u = new URL(uri); } catch { return 'redirect_uri must be an absolute URI'; }+ const scheme = u.protocol.toLowerCase();+ if (EXECUTABLE_URI_SCHEMES.has(scheme)) return `redirect URI scheme "${scheme}" is not allowed`;+ if (scheme === 'https:') return null;+ if (scheme === 'http:') return LOOPBACK_HOSTS.has(u.hostname) ? null : 'non-https redirect URIs only allowed for localhost';+ // A private-use scheme (RFC 8252 §7.1) is how native clients receive the+ // code: `com.example.app:/oauth2redirect` or `myapp://callback`. The slash+ // after the colon is what separates a navigable target from an inline+ // payload, so require it for any scheme outside http/https.+ if (!/^[a-z][a-z0-9+.-]*:\//i.test(uri)) return 'a private-use redirect URI needs a path, e.g. com.example.app:/callback';+ return null;+}++// Mirrors what /.well-known/oauth-authorization-server advertises (api/wk.js).+// RFC 7591 §3.2.2: metadata naming a grant or response type the server does not+// support is rejected, rather than stored as a promise the token endpoint would+// break later with `unsupported_grant_type`.+const SUPPORTED_GRANT_TYPES = new Set(['authorization_code', 'refresh_token']);+const SUPPORTED_RESPONSE_TYPES = new Set(['code']);+async function handleRegister(req, res) {if (cors(req, res, { methods: 'POST,OPTIONS' })) return;if (!method(req, res, ['POST'])) return;@@ -244,8 +277,17 @@ async function handleRegister(req, res) {if (!rl.success) return rateLimited(res, rl, 'too many registrations from this IP');const body = parse(registerSchema, await readJson(req));for (const uri of body.redirect_uris) {- const u = new URL(uri);- if (u.protocol === 'http:' && !/^localhost$|^127\.0\.0\.1$/.test(u.hostname)) return error(res, 400, 'invalid_redirect_uri', 'non-https redirect URIs only allowed for localhost');+ const rejection = redirectUriRejection(uri);+ if (rejection) return error(res, 400, 'invalid_redirect_uri', rejection);+ }+ if (body.grant_types) {+ const unsupported = body.grant_types.filter((g) => !SUPPORTED_GRANT_TYPES.has(g));+ if (unsupported.length) return error(res, 400, 'invalid_client_metadata', `unsupported grant_types: ${unsupported.join(', ')}`);+ if (!body.grant_types.includes('authorization_code')) return error(res, 400, 'invalid_client_metadata', 'grant_types must include authorization_code');+ }+ if (body.response_types) {+ const unsupported = body.response_types.filter((r) => !SUPPORTED_RESPONSE_TYPES.has(r));+ if (unsupported.length) return error(res, 400, 'invalid_client_metadata', `unsupported response_types: ${unsupported.join(', ')}`);}const authMethod = body.token_endpoint_auth_method ?? 'none';const clientType = authMethod === 'none' ? 'public' : 'confidential';@@ -265,7 +307,7 @@ async function handleRevoke(req, res) {if (cors(req, res, { methods: 'POST,OPTIONS' })) return;if (!method(req, res, ['POST'])) return;const form = await readForm(req);- const { token, token_type_hint, client_id, client_secret } = form;+ const { token, client_id, client_secret } = form;if (!token || !client_id) return error(res, 400, 'invalid_request', 'token and client_id required');// Rate-limit per IP: revocation is unauthenticated for public clients, so cap// it to deny a token-probing oracle / brute-force surface (RFC 7009 hardening).@@ -278,7 +320,14 @@ async function handleRevoke(req, res) {const hash = await sha256(client_secret ?? '');if (!client.client_secret_hash || !constantTimeEquals(hash, client.client_secret_hash)) return error(res, 401, 'invalid_client', 'bad client credentials');}- if (token_type_hint !== 'access_token') await revokeRefreshToken(token, client_id);+ // `token_type_hint` is advisory and RFC 7009 §2.1 requires extending the+ // search when the token is not found under the hinted type. Access tokens+ // here are stateless JWTs with no server-side record to revoke, so the+ // refresh-token lookup IS the whole search: skipping it on+ // `token_type_hint=access_token` answered 200 OK to a client revoking a+ // refresh token under a wrong hint while leaving that token live for its+ // full 30-day life.+ await revokeRefreshToken(token, client_id);return json(res, 200, {});}diff --git a/api/objects/library.js b/api/objects/library.jsindex f5e18d5ec..ad66b4713 100644--- a/api/objects/library.js+++ b/api/objects/library.js@@ -9,41 +9,81 @@// Returns { objects: [], total: 0 } until the manifest is uploaded, so consumers// feature-detect by emptiness. Pagination via ?limit=N (1..1000) + ?offset=M.-import { cors, json, method, wrap } from '../_lib/http.js';+import { cors, error, json, method, wrap } from '../_lib/http.js';import { getObjectBuffer } from '../_lib/r2.js';const MANIFEST_KEY = 'objects/library/manifest.json';const MAX_PAGE = 1000;+const PUBLISHED_CACHE = 'public, s-maxage=300, stale-while-revalidate=3600';+// A storage outage degrades to an empty library so the gallery hides the section+// rather than erroring, but that emptiness must NOT be cached: a 300s edge entry+// (plus an hour of stale-while-revalidate) would keep serving "no objects" long+// after R2 recovered. The not-yet-uploaded case is a real steady state and keeps+// the normal cache.+const DEGRADED_CACHE = 'no-store';++// Strict cursor parsing. `Number(raw) || 0` silently turns `?limit=abc` into a+// one-item page and `?limit=2.7` into a fractional `next_offset` the caller then+// feeds back in, so a client-side bug reads as working pagination. Whole decimal+// digits only; anything else is the caller's error and gets a 400.+function parseCursor(raw) {+ if (raw == null) return null;+ const trimmed = raw.trim();+ if (!/^\d+$/.test(trimmed)) return NaN;+ return Number(trimmed);+}+export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS' })) return;if (!method(req, res, ['GET'])) return;let objects = [];let generatedAt = null;+ let degraded = false;try {const buf = await getObjectBuffer(MANIFEST_KEY);const parsed = JSON.parse(buf.toString('utf8'));objects = Array.isArray(parsed) ? parsed : Array.isArray(parsed.objects) ? parsed.objects : [];generatedAt = parsed.generated_at || null;} catch (err) {+ // Not uploaded yet (NoSuchKey/404) is the expected pre-launch state; anything+ // else is a real storage error worth logging and worth keeping out of the+ // edge cache.const code = err?.$metadata?.httpStatusCode;if (err?.name !== 'NoSuchKey' && code !== 404) {+ degraded = true;console.error('[objects/library]', err?.message || err);}}const total = objects.length;- res.setHeader('Cache-Control', 'public, s-maxage=300, stale-while-revalidate=3600');-const url = new URL(req.url, 'http://x');+const rawLimit = url.searchParams.get('limit');+ const rawOffset = url.searchParams.get('offset');if (rawLimit == null) {+ if (rawOffset != null) {+ return error(res, 400, 'invalid_offset', 'offset is only meaningful with limit; pass ?limit=N too');+ }+ res.setHeader('Cache-Control', degraded ? DEGRADED_CACHE : PUBLISHED_CACHE);return json(res, 200, { objects, total, generated_at: generatedAt });}- const limit = Math.min(Math.max(Number(rawLimit) || 0, 1), MAX_PAGE);- const offset = Math.max(Number(url.searchParams.get('offset')) || 0, 0);++ const parsedLimit = parseCursor(rawLimit);+ if (!Number.isInteger(parsedLimit) || parsedLimit < 1) {+ return error(res, 400, 'invalid_limit', `limit must be a whole number from 1 to ${MAX_PAGE}`);+ }+ const offset = rawOffset == null ? 0 : parseCursor(rawOffset);+ if (!Number.isInteger(offset)) {+ return error(res, 400, 'invalid_offset', 'offset must be a whole number of 0 or more');+ }++ // Oversized limits clamp rather than fail: the documented contract is a page+ // of at most MAX_PAGE, and a caller asking for "everything" simply omits limit.+ const limit = Math.min(parsedLimit, MAX_PAGE);const page = objects.slice(offset, offset + limit);const nextOffset = offset + limit < total ? offset + limit : null;+ res.setHeader('Cache-Control', degraded ? DEGRADED_CACHE : PUBLISHED_CACHE);return json(res, 200, { objects: page, total, offset, next_offset: nextOffset, generated_at: generatedAt });});diff --git a/docs/api-reference.md b/docs/api-reference.mdindex 5482950f3..218973e9a 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -3974,6 +3974,57 @@ protocol/chain/DEX-volume surfaces. (three.ws's Fear & Greed index is served by---+### Sentiment heatmap field++```+GET /api/intel/heatmap?limit=<1..48>+```++The live token field behind the 3D sentiment heatmap on agent screens. `$THREE`+is always pinned first and flagged `featured`; the rest of the field is the+pump.fun trending set (`frontend-api-v3.pump.fun/coins`) priced from+Dexscreener's batch token endpoint. Tiles carry market data only: this endpoint+never names or recommends any token beyond the anchor. `limit` defaults to 28.++**Response**++```json+{+ "ok": true,+ "anchor": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",+ "fetchedAt": "2026-08-13T00:58:12.004Z",+ "tokens": [+ {+ "id": "FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump",+ "symbol": "three",+ "name": "three.ws",+ "image": "https://cdn.dexscreener.com/cms/images/...",+ "priceUsd": 0.001625,+ "change24h": -4.03,+ "volume24h": 79088.64,+ "marketCap": 1625310,+ "featured": true,+ "flow": { "buys24h": 22619, "sells24h": 7725, "buyPct": 75, "score": 0.491 }+ }+ ]+}+```++`flow` is an anchor-only enrichment read off the same Dexscreener pair as the+tile: the 24h split between buy and sell swaps, with `score` =+`(buys - sells) / (buys + sells)` in `[-1, 1]`. It is omitted when the anchor+has no trades in the window. Non-anchor tiles never carry it.++GET-only, CORS-open, rate-limited per IP. The field is cached 20 s in-process;+when the upstreams blip, the last good field is replayed with `"stale": true`+for up to 5 minutes, and only a cold outage with no usable price or volume+anywhere in the field returns `502 upstream_error`.++Client-side helpers for this feed (normalisation, momentum colouring, spike+diffing, and a polling loop) live in `src/sentiment-heatmap-data.js`.++---+### Related news```diff --git a/public/mcp-catalog.json b/public/mcp-catalog.jsonindex ffe9127e0..9fe1c372e 100644--- a/public/mcp-catalog.json+++ b/public/mcp-catalog.json@@ -5464,7 +5464,7 @@},{"name": "ibm_granite_analyze",- "title": "IBM Granite Analyze ($0.04)",+ "title": "IBM Granite Analyze (${…})","description": "Structured document analysis powered by IBM Granite: extract entities, sentiment, risk signals, a concise summary, and recommended next steps from any text (contracts, reports, emails, code reviews, etc.). Returns a machine-readable JSON analysis. No IBM Cloud account required — pay $0.04 USDC per call via x402.","server": {"id": "ibm-x402-mcp-remote",@@ -5520,7 +5520,7 @@},{"name": "ibm_granite_chat",- "title": "IBM Granite Chat ($0.02)",+ "title": "IBM Granite Chat (${…})","description": "Chat completion powered by IBM Granite foundation models (default: ibm/granite-3-8b-instruct). Send a conversation as role/content message pairs and receive the assistant reply with token usage. No IBM Cloud account required — pay $0.02 USDC per call via x402.","server": {"id": "ibm-x402-mcp-remote",@@ -5600,7 +5600,7 @@},{"name": "ibm_granite_code",- "title": "IBM Granite Code ($0.025)",+ "title": "IBM Granite Code (${…})","description": "Code generation, review, refactoring, and explanation via IBM Granite instruct models. Provide a task type and code/prompt; receive the generated or reviewed code with explanation. No IBM Cloud account required — pay $0.025 USDC per call via x402.","server": {"id": "ibm-x402-mcp-remote",@@ -5661,7 +5661,7 @@},{"name": "ibm_granite_embed",- "title": "IBM Granite Embed ($0.005)",+ "title": "IBM Granite Embed (${…})","description": "Generate embedding vectors for one or more texts using IBM Granite (default: ibm/granite-embedding-278m-multilingual). Returns one float array per input, suitable for semantic search, RAG retrieval, and similarity scoring. Up to 64 texts per call. No IBM Cloud account required — pay $0.005 USDC per call via x402.","server": {"id": "ibm-x402-mcp-remote",@@ -5709,7 +5709,7 @@},{"name": "ibm_granite_forecast",- "title": "IBM Granite Forecast ($0.05)",+ "title": "IBM Granite Forecast (${…})","description": "Zero-shot time-series forecasting via IBM Granite TTM (Tiny Time Mixer). Provide a numeric series with ISO-8601 timestamps and a cadence, receive the forecast horizon. No training required. Suitable for revenue, traffic, sensor, energy, and financial series. No IBM Cloud account required — pay $0.05 USDC per call via x402.","server": {"id": "ibm-x402-mcp-remote",diff --git a/scripts/genome-endpoints-proof.mjs b/scripts/genome-endpoints-proof.mjsindex 579c309e5..f8338811f 100644--- a/scripts/genome-endpoints-proof.mjs+++ b/scripts/genome-endpoints-proof.mjs@@ -348,8 +348,8 @@ async function main() {check('stud POST refuses an agent you do not own', notOwned.status === 403, `status ${notOwned.status} ${notOwned.json?.error || ''}`);const badId = await http.post('/api/genome/stud', { agent_id: 'nope' });check('stud POST rejects a malformed id with 400 JSON', badId.status === 400 && badId.json?.error === 'validation_error', `status ${badId.status}`);- const missing = await http.post('/api/genome/stud', { agent_id: '11111111-1111-4111-8111-111111111111' });- check('stud POST 404s an unknown agent', missing.status === 404, `status ${missing.status}`);+ const unknownAgent = await http.post('/api/genome/stud', { agent_id: '11111111-1111-4111-8111-111111111111' });+ check('stud POST 404s an unknown agent', unknownAgent.status === 404, `status ${unknownAgent.status}`);// Poison meta with a sibling key, then list: the write must preserve it.await db.query(`update agent_identities set meta = meta || '{"sentinel":"keep-me"}'::jsonb where id = $1`, [parentA]);diff --git a/src/dashboard-next/pages/api.js b/src/dashboard-next/pages/api.jsindex dff4c449f..428739a8f 100644--- a/src/dashboard-next/pages/api.js+++ b/src/dashboard-next/pages/api.js@@ -29,6 +29,10 @@ const SCOPES = [{ value: 'avatars:write', label: 'avatars:write', note: 'Create or modify avatars' },{ value: 'avatars:delete', label: 'avatars:delete', note: 'Permanently remove avatars' },{ value: 'profile', label: 'profile', note: 'Read the signed-in user record' },+ { value: 'memory:read', label: 'memory:read', note: 'Recall your agents’ stored memories' },+ { value: 'memory:write', label: 'memory:write', note: 'Store and forget agent memories' },+ { value: 'agents:read', label: 'agents:read', note: 'Read your agents and their identities' },+ { value: 'agents:write', label: 'agents:write', note: 'Create, update, and register agents' },];const EXPIRY_OPTIONS = [diff --git a/tests/api/ibm-vision.test.js b/tests/api/ibm-vision.test.jsindex a74d7a3d2..19a9a794e 100644--- a/tests/api/ibm-vision.test.js+++ b/tests/api/ibm-vision.test.js@@ -80,6 +80,26 @@ global.fetch = vi.fn(async () => {};}const body = state.fetchBody;+ // A chunked response with no content-length, the shape a host uses to hide how+ // much it is about to send. `streamChunks` yields those chunks so the handler's+ // running byte cap is exercised on the stream rather than on a header.+ if (state.streamChunks) {+ const chunks = state.streamChunks;+ return {+ ok: true,+ status: 200,+ headers: {+ get(h) {+ if (h === 'content-type') return state.fetchContentType;+ return null; // no content-length+ },+ },+ body: (async function* () {+ for (const c of chunks) yield c;+ })(),+ arrayBuffer: async () => Buffer.concat(chunks).buffer,+ };+ }return {ok: true,status: 200,@@ -149,6 +169,7 @@ beforeEach(() => {state.fetchStatus = 200;state.fetchContentType = 'image/jpeg';state.fetchBody = Buffer.alloc(200);+ state.streamChunks = null;state.graniteText ='{"appearance":"A sleek cobalt android.","vibe":"calm, precise","persona":"A reliable guide.","suggested_name":"Cobalt","bio":"Your co-pilot.","tone_tags":["calm","precise"],"voice":"warm and measured"}';state.graniteThrows = false;@@ -194,6 +215,9 @@ describe('GET /api/ibm/vision — subjects', () => {const { status, body } = await invoke({ method: 'GET' });expect(status).toBe(200);expect(body.subjects).toEqual([]);+ // Same shape as the success path, so a client reading the model name off+ // the degraded response does not get undefined.+ expect(body.visionModel).toBe(VISION_MODEL);});it('returns 405 for unsupported methods', async () => {@@ -309,6 +333,51 @@ describe('POST /api/ibm/vision — server-side image fetch', () => {expect(status).toBe(415);expect(body.error).toBe('not_an_image');});++ // Several allowlisted hosts serve user-supplied content. A content-length+ // header is a hint such a host can simply omit, so the 6MB ceiling has to hold+ // on the stream: buffering first and measuring afterwards means the oversized+ // body is already resident in memory by the time it is rejected.+ it('returns 413 image_too_large for an oversized body with no content-length', async () => {+ const chunk = Buffer.alloc(1024 * 1024); // 1MB per chunk+ state.streamChunks = Array.from({ length: 8 }, () => chunk); // 8MB total+ const { status, body } = await invoke({+ method: 'POST',+ body: { imageUrl: 'https://pub-test.r2.dev/huge.jpg' },+ });+ expect(status).toBe(413);+ expect(body.error).toBe('image_too_large');+ });++ it('stops reading an oversized body instead of draining it', async () => {+ const chunk = Buffer.alloc(1024 * 1024);+ let pulled = 0;+ state.streamChunks = {+ [Symbol.iterator]: function* () {+ for (let i = 0; i < 64; i++) {+ pulled++;+ yield chunk;+ }+ },+ };+ const { status } = await invoke({+ method: 'POST',+ body: { imageUrl: 'https://pub-test.r2.dev/endless.jpg' },+ });+ expect(status).toBe(413);+ // 6MB cap: the read stops on the chunk that crosses it, not 64MB later.+ expect(pulled).toBeLessThanOrEqual(7);+ });++ it('accepts a streamed body that stays under the cap', async () => {+ state.streamChunks = [Buffer.alloc(1024), Buffer.alloc(2048)];+ const { status, body } = await invoke({+ method: 'POST',+ body: { imageUrl: 'https://pub-test.r2.dev/small.jpg' },+ });+ expect(status).toBe(200);+ expect(body.vision.suggested_name).toBe('Cobalt');+ });});// ── POST /api/ibm/vision — Granite Vision call ────────────────────────────────diff --git a/tests/api/legal-risk-ack.test.js b/tests/api/legal-risk-ack.test.jsnew file mode 100644index 000000000..81895039c--- /dev/null+++ b/tests/api/legal-risk-ack.test.js@@ -0,0 +1,184 @@+// Risk Disclosure acceptance endpoint (POST /api/legal/risk-ack). The client+// gate that calls it (public/risk-ack.js) is covered in tests/risk-ack.test.js;+// this file covers the server side: what it accepts, what it refuses, and+// whether it tells the caller the truth about the durable record.++import { describe, it, expect, beforeEach, vi } from 'vitest';+import { Readable } from 'node:stream';++process.env.PUBLIC_APP_ORIGIN ||= 'https://app.test';+process.env.JWT_SECRET ||= 'test-legal-risk-secret-at-least-32ch';++// ── Mocks ─────────────────────────────────────────────────────────────────────++const sqlState = { queue: [], calls: [] };++vi.mock('../../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings, ...values) => {+ sqlState.calls.push({ query: strings.join('?'), values });+ if (sqlState.queue.length === 0) return [];+ const next = sqlState.queue.shift();+ if (next instanceof Error) throw next;+ return next;+ }),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++const rlState = { success: true };++vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ publicIp: vi.fn(async () => ({ success: rlState.success })),+ },+ clientIp: () => '203.0.113.7',+}));++const sessionState = { user: null };++vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => sessionState.user),+}));++const { RISK_ACK_VERSION } = await import('../../public/risk-ack.js');+const { default: handler } = await import('../../api/legal/risk-ack.js');++// ── Helpers ───────────────────────────────────────────────────────────────────++function makeReq(body = null, { method = 'POST', origin = null } = {}) {+ const bodyStr = body === null ? '' : JSON.stringify(body);+ const req = Readable.from([Buffer.from(bodyStr)]);+ req.method = method;+ req.url = '/api/legal/risk-ack';+ req.headers = {+ host: 'app.test',+ 'user-agent': 'vitest',+ ...(body !== null ? { 'content-type': 'application/json' } : {}),+ ...(origin ? { origin } : {}),+ };+ return req;+}++function makeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: '',+ writableEnded: false,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ getHeader(k) { return this.headers[k.toLowerCase()]; },+ end(chunk) {+ if (chunk !== undefined) this.body += chunk;+ this.writableEnded = true;+ },+ };+}++async function invoke(body, opts) {+ const res = makeRes();+ await handler(makeReq(body, opts), res);+ let json = null;+ try { json = JSON.parse(res.body); } catch { json = res.body; }+ return { res, status: res.statusCode, body: json };+}++const auditRows = () => sqlState.calls.filter((c) => /insert into audit_log/.test(c.query));++beforeEach(() => {+ sqlState.queue = [];+ sqlState.calls = [];+ rlState.success = true;+ sessionState.user = null;+});++// ── POST /api/legal/risk-ack ──────────────────────────────────────────────────++describe('POST /api/legal/risk-ack', () => {+ it('records an anonymous acceptance with its context and page', async () => {+ const { status, body } = await invoke({ version: RISK_ACK_VERSION, context: 'trade', path: '/create' });+ expect(status).toBe(200);+ expect(body).toEqual({ ok: true, recorded: true });+ const rows = auditRows();+ expect(rows).toHaveLength(1);+ expect(rows[0].values[0]).toBeNull(); // user_id: anonymous+ expect(rows[0].values).toContain('risk-ack-accept');+ expect(rows[0].values).toContainEqual({ version: RISK_ACK_VERSION, context: 'trade', path: '/create' });+ expect(rows[0].values).toContain('203.0.113.7');+ });++ it('attributes the acceptance to the signed-in user', async () => {+ sessionState.user = { id: 'user-42' };+ const { status, body } = await invoke({ version: RISK_ACK_VERSION, context: 'x402-pay' });+ expect(status).toBe(200);+ expect(body.recorded).toBe(true);+ expect(auditRows()[0].values[0]).toBe('user-42');+ });++ it('records anonymously when the session lookup fails', async () => {+ const { getSessionUser } = await import('../../api/_lib/auth.js');+ getSessionUser.mockRejectedValueOnce(new Error('expired token'));+ const { status, body } = await invoke({ version: RISK_ACK_VERSION });+ expect(status).toBe(200);+ expect(body.recorded).toBe(true);+ expect(auditRows()[0].values[0]).toBeNull();+ });++ it('refuses a disclosure version that does not exist', async () => {+ const { status, body } = await invoke({ version: RISK_ACK_VERSION + 1 });+ expect(status).toBe(400);+ expect(body.error).toBe('invalid_version');+ expect(auditRows()).toHaveLength(0);+ });++ it.each([+ [{}],+ [{ version: 0 }],+ [{ version: 1.5 }],+ [{ version: 'one' }],+ [{ version: null }],+ ])('refuses a malformed version %#', async (body) => {+ const { status } = await invoke(body);+ expect(status).toBe(400);+ expect(auditRows()).toHaveLength(0);+ });++ it('drops a malformed context or path rather than storing it', async () => {+ const { status } = await invoke({+ version: RISK_ACK_VERSION,+ context: 'NOT A SLUG!',+ path: 'missing-leading-slash',+ });+ expect(status).toBe(200);+ expect(auditRows()[0].values).toContainEqual({ version: RISK_ACK_VERSION, context: null, path: null });+ });++ it('reports recorded:false when the durable write fails', async () => {+ // A deterministic SQL error, not a transient connection blip: db-retry+ // surfaces it on the first attempt instead of retrying.+ sqlState.queue = [new Error('relation "audit_log" does not exist')];+ const { status, body } = await invoke({ version: RISK_ACK_VERSION, context: 'trade' });+ expect(status).toBe(200);+ expect(body).toEqual({ ok: true, recorded: false });+ });++ it('rejects a non-POST method', async () => {+ const { status, body } = await invoke(null, { method: 'GET' });+ expect(status).toBe(405);+ expect(body.error).toBe('method_not_allowed');+ });++ it('rate limits', async () => {+ rlState.success = false;+ const { status } = await invoke({ version: RISK_ACK_VERSION });+ expect(status).toBe(429);+ expect(auditRows()).toHaveLength(0);+ });++ it('allows any origin, so the x402 embed on a merchant site can record', async () => {+ const { res, status } = await invoke({ version: RISK_ACK_VERSION }, { origin: 'https://merchant.example' });+ expect(status).toBe(200);+ expect(res.headers['access-control-allow-origin']).toBe('*');+ // No credentials on a wildcard origin: cross-site acceptances stay anonymous.+ expect(res.headers['access-control-allow-credentials']).toBeUndefined();+ });+});diff --git a/tests/api/providers-meshy.test.js b/tests/api/providers-meshy.test.jsindex 8f13dd937..ee7350a62 100644--- a/tests/api/providers-meshy.test.js+++ b/tests/api/providers-meshy.test.js@@ -1,4 +1,4 @@-// Meshy BYOK provider (api/_providers/meshy.js) — wire contract + failure paths.+// Meshy BYOK provider (api/_providers/meshy.js): wire contract + failure paths.//// Meshy backs two forge paths on two different API versions:// text→geometry POST /openapi/v2/text-to-3d (mode "preview", no intermediate image)@@ -19,7 +19,7 @@ afterEach(() => {const TIER = { id: 'standard', polycount: 30_000, pbr: false, hd: false };-describe('meshy provider — construction', () => {+describe('meshy provider: construction', () => {it('refuses to construct without an API key', () => {expect(() => createMeshyProvider('')).toThrowError(/key is required/i);try {@@ -30,7 +30,7 @@ describe('meshy provider — construction', () => {});});-describe('meshy provider — text→geometry submit', () => {+describe('meshy provider: text→geometry submit', () => {it('posts the v2 preview body and returns the text-to-3d poll handle', async () => {let captured;globalThis.fetch = vi.fn(async (url, opts) => {@@ -50,7 +50,7 @@ describe('meshy provider — text→geometry submit', () => {expect(out).toEqual({ kind: 'text-to-3d', taskId: 'task-abc' });});- it('clamps a tier poly budget into Meshy\'s accepted 100–300,000 window', async () => {+ it('clamps a tier poly budget into Meshy\'s accepted 100-300,000 window', async () => {const bodies = [];globalThis.fetch = vi.fn(async (url, opts) => {bodies.push(JSON.parse(opts.body));@@ -66,7 +66,7 @@ describe('meshy provider — text→geometry submit', () => {});});-describe('meshy provider — image→3D submit', () => {+describe('meshy provider: image→3D submit', () => {it('posts the v1 image body with the tier\'s PBR/HD knobs and an optional texture prompt', async () => {let captured;globalThis.fetch = vi.fn(async (url, opts) => {@@ -104,7 +104,7 @@ describe('meshy provider — image→3D submit', () => {});});-describe('meshy provider — normalized submit errors', () => {+describe('meshy provider: normalized submit errors', () => {const CASES = [{ status: 401, code: 'invalid_key', mapped: 401 },{ status: 403, code: 'invalid_key', mapped: 401 },@@ -150,7 +150,7 @@ describe('meshy provider — normalized submit errors', () => {});});-describe('meshy provider — status polling', () => {+describe('meshy provider: status polling', () => {it('polls the endpoint matching the task kind and resolves the GLB when SUCCEEDED', async () => {let polled;globalThis.fetch = vi.fn(async (url) => {diff --git a/tests/api/providers-nvidia-cosmos.test.js b/tests/api/providers-nvidia-cosmos.test.jsindex 30c18219e..a3141c8d0 100644--- a/tests/api/providers-nvidia-cosmos.test.js+++ b/tests/api/providers-nvidia-cosmos.test.js@@ -1,4 +1,4 @@-// NVIDIA Cosmos provider (api/_providers/nvidia-cosmos.js) — the free+// NVIDIA Cosmos provider (api/_providers/nvidia-cosmos.js): the free// text→world VIDEO lane behind the platform NVIDIA_API_KEY.//// Same NVCF async gateway as the TRELLIS provider (202 + NVCF-REQID → poll@@ -7,7 +7,7 @@// ships the MP4 in, the R2 persist, and the normalized error codes callers// route a dead lane around on.//-// global fetch is stubbed and R2 is intercepted — no network, no live NVCF+// global fetch is stubbed and R2 is intercepted: no network, no live NVCF// spend, and no mocked product data.import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';@@ -59,7 +59,7 @@ afterEach(() => {vi.restoreAllMocks();});-describe('nvidia-cosmos provider — configuration', () => {+describe('nvidia-cosmos provider: configuration', () => {it('reports configured only while NVIDIA_API_KEY is present', () => {expect(nvidiaCosmosConfigured()).toBe(true);delete process.env.NVIDIA_API_KEY;@@ -78,7 +78,7 @@ describe('nvidia-cosmos provider — configuration', () => {});});-describe('nvidia-cosmos provider — text→world submit', () => {+describe('nvidia-cosmos provider: text→world submit', () => {function stubAccept() {const calls = [];globalThis.fetch = vi.fn(async (url, opts = {}) => {@@ -176,7 +176,7 @@ describe('nvidia-cosmos provider — text→world submit', () => {});});-describe('nvidia-cosmos provider — normalized submit errors', () => {+describe('nvidia-cosmos provider: normalized submit errors', () => {const CASES = [{ status: 401, code: 'invalid_key', mapped: 401 },{ status: 403, code: 'invalid_key', mapped: 401 },@@ -236,7 +236,7 @@ describe('nvidia-cosmos provider — normalized submit errors', () => {});});-describe('nvidia-cosmos provider — 202-then-poll loop', () => {+describe('nvidia-cosmos provider: 202-then-poll loop', () => {it('reports running while NVCF returns 202', async () => {globalThis.fetch = vi.fn(async (url) => {expect(String(url)).toBe(`${NVCF_STATUS}/req-world-1`);diff --git a/tests/native-launch-endpoint.test.js b/tests/native-launch-endpoint.test.jsindex e74000781..90e8fe3f9 100644--- a/tests/native-launch-endpoint.test.js+++ b/tests/native-launch-endpoint.test.js@@ -7,6 +7,9 @@ import { describe, it, expect, vi, beforeEach } from 'vitest';let sessionUser = { id: 'user-1' };const dbRows = { user_wallets: [], native_launches: [], pending: [] };+// Every SQL text the handler issued this test, so a validation guard can be+// proven to short-circuit before the query rather than merely returning 400.+const sqlCalls = [];vi.mock('../api/_lib/http.js', () => ({wrap: (fn) => fn,@@ -41,6 +44,7 @@ vi.mock('../api/_lib/auth.js', () => ({vi.mock('../api/_lib/db.js', () => ({sql: (strings) => {const text = strings.join(' ');+ sqlCalls.push(text);if (text.includes('from user_wallets')) return Promise.resolve(dbRows.user_wallets);if (text.includes('from native_launches')) return Promise.resolve(dbRows.native_launches);if (text.includes('from agent_registrations_pending')) return Promise.resolve(dbRows.pending);@@ -103,6 +107,7 @@ beforeEach(() => {dbRows.user_wallets = [];dbRows.native_launches = [];dbRows.pending = [];+ sqlCalls.length = 0;verifySignature.mockReset();txInvokesDbcProgram.mockReset().mockReturnValue(true);process.env.NATIVE_LAUNCH_CONFIG_KEY_DEVNET = CONFIG_KEY;@@ -288,4 +293,67 @@ describe('launches', () => {network: 'devnet',});});++ it('rejects a non-uuid agent_id before it ever reaches the uuid column', async () => {+ // agent_id is compared against a uuid column. Passing it through+ // unvalidated makes Postgres raise and the request answer 500.+ const r = await call('launches', { query: { agent_id: 'not-a-uuid' } });+ expect(r.status).toBe(400);+ expect(r.body.error).toBe('validation_error');+ expect(sqlCalls).toEqual([]);+ });++ it('shapes a launch row with its agent, and hides a private avatar thumbnail', async () => {+ dbRows.native_launches = [+ {+ mint: MINT,+ pool: 'PoolAddress11111111111111111111111111111111',+ network: 'devnet',+ name: 'Native Coin',+ symbol: 'NTV',+ metadata_uri: 'https://cf-ipfs.com/ipfs/bafkreiabc',+ status: 'live',+ created_at: '2026-08-13T00:00:00.000Z',+ agent_id: 'agent-1',+ agent_name: 'Scout',+ avatar_thumbnail_key: 'thumbs/a.png',+ avatar_visibility: 'public',+ },+ {+ mint: MINT,+ pool: 'PoolAddress11111111111111111111111111111111',+ network: 'devnet',+ name: 'Quiet Coin',+ symbol: 'QIT',+ metadata_uri: null,+ status: 'live',+ created_at: '2026-08-12T00:00:00.000Z',+ agent_id: 'agent-2',+ agent_name: 'Hidden',+ avatar_thumbnail_key: 'thumbs/b.png',+ avatar_visibility: 'private',+ },+ ];+ const r = await call('launches', { query: { network: 'devnet', limit: '1' } });+ expect(r.status).toBe(200);+ // limit=1 with two rows back means the query overfetched by one: the+ // second row is the has_more probe, not a page entry.+ expect(r.body.data.has_more).toBe(true);+ expect(r.body.data.launches).toHaveLength(1);+ const [first] = r.body.data.launches;+ expect(first.lane).toBe('native');+ // cf-ipfs.com stopped resolving in 2024, so a stored URL on it has to be+ // rewritten onto a live gateway before it reaches a client.+ expect(first.metadata_uri).toBe('https://dweb.link/ipfs/bafkreiabc');+ expect(first.agent).toEqual({+ id: 'agent-1',+ name: 'Scout',+ url: '/agents/agent-1',+ avatar_thumbnail_url: 'https://cdn.test/thumbs/a.png',+ });++ dbRows.native_launches = [dbRows.native_launches[1]];+ const priv = await call('launches', { query: { network: 'devnet' } });+ expect(priv.body.data.launches[0].agent.avatar_thumbnail_url).toBeNull();+ });});