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
test(api): cover the three agent sub-resource handlers and the new gmgn JSON lane
nirholas6b35b5e3b028
diff --git a/docs/ca2x402.md b/docs/ca2x402.mdindex 9b257d980..0d5a815a6 100644--- a/docs/ca2x402.md+++ b/docs/ca2x402.md@@ -125,7 +125,7 @@ The generated x402 service for that exact token:| Field | Value || -------------------------------- | ---------------------------------------------------------------------------- || `name` | `three.ws Token Oracle` |-| `endpoint` | `<origin>/api/x402/token-intel?mint=<MINT_ADDRESS>` |+| `endpoint` | `<APP_ORIGIN>/api/x402/token-intel?mint=<MINT_ADDRESS>` || `method` | `GET` || `price_atomics` / `price_usd` | USDC atomics from `priceFor('token-intel', '10000')`, plus the same value divided by `1e6`. Default is `10000` atomics, which is $0.01. || `asset` | `USDC` |@@ -137,9 +137,16 @@ The generated x402 service for that exact token:| `bazaar_discoverable` | `true` || `snippets` | `{ curl, node, agent }`, see below |-The endpoint origin is derived from the request (`x-forwarded-proto` /-`x-forwarded-host`, falling back to `three.ws`), so a local dev resolve generates-a local endpoint and production generates a production one.+The endpoint origin is always `env.APP_ORIGIN` (set from `PUBLIC_APP_ORIGIN`,+defaulting to `https://three.ws`). It is deliberately NOT derived from the+request's `host` / `x-forwarded-host` headers: those are caller-controlled, and+everything downstream of this URL is a payment instruction, so a spoofed host+would hand the buyer an attacker-owned 402 challenge to settle against. Because+the 200 is CDN-cacheable, a poisoned copy could then be served on to other+visitors. Same reasoning as `resolveResourceUrl()` in+[`api/_lib/x402-spec.js`](../api/_lib/x402-spec.js). A local dev resolve+therefore generates the production endpoint URL, which is the one a buyer+actually settles against.Operators can retune the price at deploy time with`X402_PRICE_TOKEN_INTEL=<atomics>`; a non-integer value logs a warning and fallsdiff --git a/docs/ux-flows/07-crypto-trading-analytics.md b/docs/ux-flows/07-crypto-trading-analytics.mdindex 6c63f8c39..b7ac57081 100644--- a/docs/ux-flows/07-crypto-trading-analytics.md+++ b/docs/ux-flows/07-crypto-trading-analytics.md@@ -235,6 +235,7 @@ coin-intel, pump-visualizer and pump-live: adding a coin on any surface shows up### GMGN Smart Money — `/gmgn`- **Source:** `public/gmgn.html` (pre-built static; ~900 lines); backend `api/agents/gmgn.js`; `vercel.json` rewrite `/gmgn → /gmgn.html`, `/api/agents/gmgn-feed → /api/agents/gmgn?_handler=feed`+- **Two read lanes on one backend:** `GET /api/agents/gmgn-feed` streams SSE (what this page uses); `GET /api/agents/gmgn` returns the same board as one JSON response for callers that cannot hold a stream open (server-side fetches, agent tool calls, curl). Both accept `chain`, `interval`, and `minSmartBuys`; the JSON lane also accepts `limit` (1-50, default 25) and answers `{ data: { chain, interval, min_smart_buys, source, count, items } }` with the same normalized item shape the `smart_entry` events carry.- **Entry point:** nav / direct URL.- **Prerequisites / gates:** None — public live feed. Narration needs browser Web Speech API; "My agents" avatar tab needs auth.- **Steps (N):**diff --git a/prompts/swarm-100/api-agents-06.md b/prompts/swarm-100/api-agents-06.mddeleted file mode 100644index 49b4290c0..000000000--- a/prompts/swarm-100/api-agents-06.md+++ /dev/null@@ -1,110 +0,0 @@-# API audit: api/agents batch 06 (10 files)--How to run: paste this file's repo path into a fresh Claude Code chat in this-repository and say "run this work order". This file is fully self-contained:-it depends on no other prompt file anywhere. If neighboring files in-prompts/swarm-100/ are gone, that work is done; if present, ignore them.-Every claim below rots; step 0 re-measures, and what you measure wins.--## Operating clause (binding)--- Read CLAUDE.md first. Its rules override everything, including this file.-- Finish 100% in this session. Never end the turn with a question, an option- list, or an unexecuted plan. A judgment call goes in one line of the final- report; it never becomes a question that halts work.-- The only permitted stops are the CLAUDE.md stop-and-ask gates: spending real- funds or any irreversible on-chain write, git push or a production deploy,- committing content that references a crypto project other than $THREE, and- destroying unrecoverable data.-- No mocks, no fake data, no placeholder stubs, no unfinished-work markers, no- commented-out code. Real APIs and real integrations only.-- The em-dash and en-dash characters are banned in everything you write.-- Concurrent agents share this worktree: stage explicit paths only (never a- bare add-everything), and commit finished work promptly.-- Before committing, run: npm run check:rules -- --paths <files you touched>.- It must exit 0.--## Step 0: re-derive the current state--1. Confirm each file below still exists; deleted ones are done, skip them.-2. For each, decide routability: grep its path in vercel.json and read how- server/index.mjs maps filesystem handlers. Routed files get an endpoint- audit; internal modules get a code and test audit.-3. Start a local server for endpoint checks: node server/index.mjs with .env- loaded, on a free PORT if 3000 is busy.--## Task: audit these api files, then fix everything found--Files in this batch:--- api/agents/featured.js-- api/agents/gmgn.js-- api/agents/identity-check.js-- api/agents/networth.js-- api/agents/nfts.js-- api/agents/onchain/[action].js-- api/agents/orders.js-- api/agents/patronage.js-- api/agents/payments/[action].js-- api/agents/portfolio.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-agents-06.md-- The shrinking directory is this campaign's only progress ledger; there is- no progress log to update.-4. Final report: what step 0 measured, what changed (file list), evidence per- Definition of done line, and any one-line judgment calls. No trailing- questions, no unexecuted plans.--If a line genuinely cannot pass inside this session (an external party must-respond, or an owner-gated action is the final step), finish everything else,-leave this file in place, and state exactly which line remains and who owns-it. Never delete this file on a partial.diff --git a/tests/agents-subresource-handlers.test.js b/tests/agents-subresource-handlers.test.jsnew file mode 100644index 000000000..f547f4a2c--- /dev/null+++ b/tests/agents-subresource-handlers.test.js@@ -0,0 +1,270 @@+/**+ * Sub-resource handler dispatch + ownership gating for the three agent modules+ * that are never routed directly: api/agents/orders.js and api/agents/portfolio.js+ * (dispatched by api/agents/[id].js) and api/agents/patronage.js (dispatched by+ * api/agents/solana-wallet.js). vercel.json rewrites every+ * /api/agents/<segment>... path to api/agents/[id].js, so these modules are only+ * ever entered as handler(req, res, agentId, action).+ *+ * The engines behind them are covered by orders-engine.test.js, portfolio.test.js,+ * and patronage.test.js. What is pinned here is the layer above: which action maps+ * to which behaviour, and that a visitor can never read or mutate another owner's+ * orders, portfolio, or perk ladder.+ */++import { describe, it, expect, vi, beforeEach } from 'vitest';++const OWNER = 'user-owner';+const AGENT = '11111111-2222-4333-8444-555555555555';+const ORDER = '99999999-8888-4777-8666-555555555555';+// $THREE, the only coin this platform references.+const THREE = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++let sessionUser = { id: OWNER };+let agentRow = { id: AGENT, user_id: OWNER, name: 'Test Agent', meta: { solana_address: THREE } };++vi.mock('../api/_lib/http.js', () => ({+ wrap: (fn) => fn,+ cors: () => false,+ method: (req, res, allowed) => {+ if (allowed.includes(req.method)) return true;+ res._json = { status: 405, body: { error: 'method_not_allowed' } };+ return false;+ },+ readJson: async (req) => req.body ?? {},+ rateLimited: (res) => {+ res._json = { status: 429, body: { error: 'rate_limited' } };+ return res;+ },+ error: (res, status, code, message, extra = {}) => {+ res._json = { status, body: { error: code, error_description: message, ...extra } };+ return res;+ },+ json: (res, status, body) => {+ res._json = { status, body };+ return res;+ },+ serverError: (res, status, code) => {+ res._json = { status, body: { error: code } };+ return res;+ },+}));++vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: {+ walletRead: vi.fn(async () => ({ success: true })),+ tradePerUser: vi.fn(async () => ({ success: true })),+ agentProfileIp: vi.fn(async () => ({ success: true })),+ },+ clientIp: () => '1.2.3.4',+}));++vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => sessionUser),+ authenticateBearer: vi.fn(async () => null),+ extractBearer: vi.fn(() => null),+}));++vi.mock('../api/_lib/db.js', () => ({+ sql: (strings) => {+ const text = strings.join(' ');+ if (/from agent_identities/i.test(text)) return Promise.resolve(agentRow ? [agentRow] : []);+ return Promise.resolve([]);+ },+}));++vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));++// Orders dependencies. The pure model (normalizeOrder, describeOrder) stays real+// so the 422 case below exercises the actual validator.+vi.mock('../api/_lib/orders.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ listOrders: vi.fn(async () => []),+ ordersSummary: vi.fn(async () => ({ total: 0, active: 0 })),+ getOrder: vi.fn(async () => null),+ listFills: vi.fn(async () => []),+ createOrder: vi.fn(async () => ({ id: ORDER })),+ updateOrder: vi.fn(async () => null),+ cancelOrder: vi.fn(async () => null),+ cancelAllOrders: vi.fn(async () => 0),+ };+});+vi.mock('../api/_lib/agent-wallet.js', () => ({+ getSolanaAddressBalances: vi.fn(async () => ({ sol: 0 })),+}));+vi.mock('../api/_lib/agent-trade-guards.js', () => ({+ getSpendLimits: () => ({ per_tx_usd: 10, daily_usd: 50, frozen: false }),+ getTradeLimits: () => ({ kill_switch: false, per_trade_sol: 1, daily_budget_sol: 5 }),+}));+vi.mock('../api/_lib/pump.js', () => ({ getPumpTradeClient: vi.fn(async () => ({ connection: {} })) }));+vi.mock('../api/_lib/trade-firewall.js', () => ({ assessTradeSafety: vi.fn(async () => null) }));+vi.mock('../workers/agent-orders/market.js', () => ({+ getSignals: vi.fn(async () => ({ market: null, signals: {} })),+ metricValue: vi.fn(() => null),+}));++// Portfolio dependencies.+const portfolioSnapshot = { t: 1, sol_usd: 75, net_worth: { sol: 0, usd: 0 }, holdings: [] };+vi.mock('../api/_lib/portfolio.js', () => ({+ getPortfolio: vi.fn(async () => portfolioSnapshot),+}));++// Patronage dependencies. The tier ladder and entitlement math stay real.+vi.mock('../api/_lib/patronage.js', async (importOriginal) => {+ const actual = await importOriginal();+ return {+ ...actual,+ aggregatePatrons: vi.fn(async () => []),+ patronTotals: vi.fn(async () => ({ patrons: 0, usd: 0, supports: 0 })),+ patronStanding: vi.fn(async () => ({+ usd: 0, supportCount: 0, firstAt: null, lastAt: null, level: null,+ progress: { pct: 0, next: null, remainingUsd: 10 },+ })),+ listPerks: vi.fn(async () => []),+ resolvePatronName: vi.fn(async () => null),+ hiddenWallets: vi.fn(async () => new Set()),+ };+});+vi.mock('../api/_lib/siws.js', () => ({ verifySiwsSignature: vi.fn(() => false) }));+vi.mock('../api/_lib/audit.js', () => ({ logAudit: vi.fn() }));++const ordersHandler = (await import('../api/agents/orders.js')).default;+const portfolioHandler = (await import('../api/agents/portfolio.js')).default;+const patronageHandler = (await import('../api/agents/patronage.js')).default;++function mkReq(method = 'GET', url = `/api/agents/${AGENT}/orders`, body) {+ return { method, url, headers: {}, body, on: () => {} };+}+function mkRes() {+ return { _json: null, setHeader() {}, writeHead() {}, flushHeaders() {}, write() {}, end() {} };+}++beforeEach(() => {+ sessionUser = { id: OWNER };+ agentRow = { id: AGENT, user_id: OWNER, name: 'Test Agent', meta: { solana_address: THREE } };+});++describe('api/agents/orders.js dispatch', () => {+ it('lists the owner orders with the live summary (main path)', async () => {+ const res = mkRes();+ await ordersHandler(mkReq('GET'), res, AGENT, undefined);+ expect(res._json.status).toBe(200);+ expect(res._json.body.data.orders).toEqual([]);+ expect(res._json.body.data.summary.frozen).toBe(false);+ expect(res._json.body.data.summary.kill_switch).toBe(false);+ });++ it('serves the closed condition vocabulary on /schema', async () => {+ const res = mkRes();+ await ordersHandler(mkReq('GET'), res, AGENT, 'schema');+ expect(res._json.status).toBe(200);+ expect(res._json.body.data.order_types).toContain('conditional');+ expect(res._json.body.data.number_ops).toContain('gte');+ });++ it('refuses a visitor who is not the owner (failure path)', async () => {+ sessionUser = { id: 'someone-else' };+ const res = mkRes();+ await ordersHandler(mkReq('GET'), res, AGENT, undefined);+ expect(res._json.status).toBe(403);+ expect(res._json.body.error).toBe('forbidden');+ });++ it('refuses an anonymous caller before touching the agent row', async () => {+ sessionUser = null;+ const res = mkRes();+ await ordersHandler(mkReq('GET'), res, AGENT, undefined);+ expect(res._json.status).toBe(401);+ });++ it('404s an unknown sub-resource rather than falling through to the list', async () => {+ const res = mkRes();+ await ordersHandler(mkReq('GET'), res, AGENT, 'not-a-real-action');+ expect(res._json.status).toBe(404);+ expect(res._json.body.error_description).toMatch(/unknown orders sub-resource/);+ });++ it('rejects an unsupported method on a single order', async () => {+ const res = mkRes();+ await ordersHandler(mkReq('PATCH'), res, AGENT, ORDER);+ expect(res._json.status).toBe(405);+ });++ it('422s an order the engine cannot validate', async () => {+ const res = mkRes();+ await ordersHandler(mkReq('POST', `/api/agents/${AGENT}/orders`, { type: 'limit' }), res, AGENT, undefined);+ expect(res._json.status).toBe(422);+ });+});++describe('api/agents/portfolio.js dispatch', () => {+ it('returns the owner snapshot when no action is given (main path)', async () => {+ const res = mkRes();+ await portfolioHandler(mkReq('GET', `/api/agents/${AGENT}/portfolio`), res, AGENT, undefined);+ expect(res._json.status).toBe(200);+ expect(res._json.body.data).toBe(portfolioSnapshot);+ });++ it('404s an unknown sub-resource (failure path)', async () => {+ const res = mkRes();+ await portfolioHandler(mkReq('GET'), res, AGENT, 'bogus');+ expect(res._json.status).toBe(404);+ });++ it('never exposes another owner attribution ledger', async () => {+ sessionUser = { id: 'someone-else' };+ const res = mkRes();+ await portfolioHandler(mkReq('GET'), res, AGENT, undefined);+ expect(res._json.status).toBe(403);+ });+});++describe('api/agents/patronage.js dispatch', () => {+ it('serves the public ladder and wall on GET (main path)', async () => {+ sessionUser = null;+ const res = mkRes();+ await patronageHandler(mkReq('GET', `/api/agents/${AGENT}/solana/patronage`), res, AGENT);+ expect(res._json.status).toBe(200);+ expect(res._json.body.data.is_owner).toBe(false);+ expect(res._json.body.data.levels.map((l) => l.key)).toContain('benefactor');+ expect(res._json.body.data.wall).toEqual([]);+ });++ it('marks the owner so the editor can render its own payloads', async () => {+ const res = mkRes();+ await patronageHandler(mkReq('GET', `/api/agents/${AGENT}/solana/patronage`), res, AGENT);+ expect(res._json.status).toBe(200);+ expect(res._json.body.data.is_owner).toBe(true);+ });++ it('rejects an unknown POST op (failure path)', async () => {+ const res = mkRes();+ await patronageHandler(+ mkReq('POST', `/api/agents/${AGENT}/solana/patronage`, { op: 'nope' }),+ res,+ AGENT,+ );+ expect(res._json.status).toBe(400);+ expect(res._json.body.error_description).toMatch(/unknown op/);+ });++ it('will not unlock a perk without a wallet signature', async () => {+ const res = mkRes();+ await patronageHandler(+ mkReq('POST', `/api/agents/${AGENT}/solana/patronage`, { op: 'unlock', wallet: THREE }),+ res,+ AGENT,+ );+ expect(res._json.status).toBe(401);+ expect(res._json.body.error_description).toMatch(/missing signature/);+ });++ it('404s a patronage read for an agent that does not exist', async () => {+ agentRow = null;+ const res = mkRes();+ await patronageHandler(mkReq('GET', `/api/agents/${AGENT}/solana/patronage`), res, AGENT);+ expect(res._json.status).toBe(404);+ });+});diff --git a/tests/gmgn-snapshot.test.js b/tests/gmgn-snapshot.test.jsnew file mode 100644index 000000000..64ea7d247--- /dev/null+++ b/tests/gmgn-snapshot.test.js@@ -0,0 +1,106 @@+/**+ * gmgnSmartMoneySnapshot backs the JSON lane of /api/agents/gmgn: the same live+ * smart-money board the SSE lane streams, read one-shot. Pinned here: the+ * minSmartBuys floor, the limit cap, the normalized item shape, and the two+ * degraded paths (Cloudflare 403 failing over to DexScreener, and a dead upstream+ * reporting ok:false instead of throwing).+ *+ * fetch is stubbed at the network boundary so the test exercises the real+ * failover and normalization code without depending on a third party being up.+ */++import { describe, it, expect, vi, afterEach } from 'vitest';+import { gmgnSmartMoneySnapshot } from '../api/_lib/gmgn-feed.js';++// $THREE, the only coin this platform references.+const THREE = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';++const realFetch = globalThis.fetch;+afterEach(() => { globalThis.fetch = realFetch; vi.restoreAllMocks(); });++function jsonResponse(body, status = 200) {+ return { ok: status >= 200 && status < 300, status, json: async () => body };+}++describe('gmgnSmartMoneySnapshot', () => {+ it('returns normalized items above the smart-buy floor (main path)', async () => {+ globalThis.fetch = vi.fn(async () => jsonResponse({+ data: {+ rank: [+ { address: THREE, symbol: 'THREE', name: 'three.ws', price: 0.5, market_cap: 1000, smart_buy_24h: 7 },+ { address: 'QuietMint1111111111111111111111111111111111', symbol: 'QUIET', smart_buy_24h: 1 },+ ],+ },+ }));++ const snap = await gmgnSmartMoneySnapshot({ minSmartBuys: 2 });+ expect(snap.ok).toBe(true);+ expect(snap.source).toBe('gmgn');+ expect(snap.items).toHaveLength(1);+ expect(snap.items[0]).toMatchObject({+ address: THREE,+ symbol: 'THREE',+ smart_buy_24h: 7,+ // A one-shot read has no prior snapshot, so the whole count is the delta.+ smart_buy_delta: 7,+ is_new: true,+ chain: 'sol',+ interval: '1h',+ source: 'gmgn',+ });+ });++ it('caps the result at the requested limit', async () => {+ const rank = Array.from({ length: 10 }, (_, i) => ({+ address: `Mint${i}1111111111111111111111111111111111111`,+ symbol: `M${i}`,+ smart_buy_24h: 5,+ }));+ globalThis.fetch = vi.fn(async () => jsonResponse({ data: { rank } }));++ const snap = await gmgnSmartMoneySnapshot({ limit: 3 });+ expect(snap.items).toHaveLength(3);+ });++ it('skips entries with no address', async () => {+ globalThis.fetch = vi.fn(async () => jsonResponse({+ data: { rank: [{ symbol: 'GHOST', smart_buy_24h: 99 }] },+ }));++ const snap = await gmgnSmartMoneySnapshot();+ expect(snap.ok).toBe(true);+ expect(snap.items).toEqual([]);+ });++ it('reports ok:false when every upstream is down (failure path)', async () => {+ globalThis.fetch = vi.fn(async () => jsonResponse({}, 500));++ const snap = await gmgnSmartMoneySnapshot();+ expect(snap.ok).toBe(false);+ expect(snap.status).toBe(500);+ expect(snap.items).toEqual([]);+ expect(snap.source).toBe(null);+ });++ it('fails over to the DexScreener board when Cloudflare returns 403', async () => {+ globalThis.fetch = vi.fn(async (url) => {+ if (String(url).includes('gmgn.ai')) return jsonResponse({}, 403);+ if (String(url).includes('token-boosts')) {+ return jsonResponse([{ chainId: 'solana', tokenAddress: THREE, totalAmount: 100 }]);+ }+ return jsonResponse([{+ baseToken: { address: THREE, symbol: 'THREE', name: 'three.ws' },+ priceUsd: '0.5',+ marketCap: 1000,+ volume: { h24: 42 },+ liquidity: { usd: 100 },+ txns: { h1: { buys: 9, sells: 1 } },+ }]);+ });++ const snap = await gmgnSmartMoneySnapshot({ minSmartBuys: 1 });+ expect(snap.ok).toBe(true);+ expect(snap.source).toBe('dexscreener');+ expect(snap.items[0].address).toBe(THREE);+ });+});