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(agents): stop a bad value from deleting an agent's trade cap, and log the failures these endpoints used to swallow
nirholas11f7ce66cca3
diff --git a/api/agents/agent-strategy-objects.js b/api/agents/agent-strategy-objects.jsindex 8400e311e..a6a451c6e 100644--- a/api/agents/agent-strategy-objects.js+++ b/api/agents/agent-strategy-objects.js@@ -270,6 +270,9 @@ async function handleClose(req, res, id) {try {result = await closeStrategyPositionNow({ positionId: body.position_id, ownerId: owned.auth.userId, agentId: id });} catch (err) {+ // A force-close moves real funds; swallowing the cause left nothing to+ // diagnose from when one failed.+ console.error('[agents/strategies] close failed', body.position_id, err?.message || err);return error(res, 500, 'internal_error', 'unexpected error closing the position');}if (!result.ok) return error(res, result.status || 500, result.code || 'error', result.message || 'could not close the position');diff --git a/api/agents/agent-trade.js b/api/agents/agent-trade.jsindex c45813698..5b792efd9 100644--- a/api/agents/agent-trade.js+++ b/api/agents/agent-trade.js@@ -21,7 +21,7 @@import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { sql } from '../_lib/db.js';-import { cors, json, method, error, readJson, rateLimited, serverError } from '../_lib/http.js';+import { cors, json, method, error, readJson, rateLimited } from '../_lib/http.js';import { limits, clientIp } from '../_lib/rate-limit.js';import { requireCsrf } from '../_lib/csrf.js';import { ensureAgentWallet, recoverSolanaAgentKeypair } from '../_lib/agent-wallet.js';@@ -449,6 +449,7 @@ export async function executeAgentTrade({ id, userId, meta, input, req = null, stry {address = (await ensureAgentWallet(id, userId, { reason: custodyReason })).address;} catch (e) {+ console.error('[agents/agent-trade] wallet prepare failed', e?.message);return fail(500, 'wallet_unavailable', 'could not prepare the agent wallet — try again');}const ownerPk = new PublicKey(address);@@ -474,6 +475,7 @@ export async function executeAgentTrade({ id, userId, meta, input, req = null, stry {ctx = await getPumpTradeClient({ network });} catch (e) {+ console.error('[agents/agent-trade] trade RPC unavailable', e?.message);return fail(502, 'rpc_error', 'could not connect to the trade RPC — try again');}const conn = ctx.connection;@@ -502,6 +504,7 @@ export async function executeAgentTrade({ id, userId, meta, input, req = null, stry {blocked = await runGuards({ id, side, tradeLimits, prep, walletLamports, network, meta, mintPk: input.mintPk, ownerPk, userId });} catch (e) {+ console.error('[agents/agent-trade] guard check failed', e?.message);return fail(502, 'guard_check_failed', 'could not verify the trade guardrails — try again');}if (blocked) return fail(blocked.status, blocked.code, blocked.message, blocked.detail);@@ -587,6 +590,7 @@ export async function executeAgentTrade({ id, userId, meta, input, req = null, smeta: { mint: input.mint, network, venue: prep.venue, custody_event_id: claimId, ...(isStrategy ? { strategy_id: sourceMeta?.strategy_id ?? null, equip_id: sourceMeta?.equip_id ?? null } : {}) },});} catch (e) {+ console.error('[agents/agent-trade] key recover failed', e?.message);await updateCustodyEvent(claimId, { status: 'failed', meta: { error: 'key_recover_failed' } }).catch(() => {});return fail(500, 'key_recover_failed', 'could not access the agent wallet key — no funds were moved');}diff --git a/api/agents/alpha.js b/api/agents/alpha.jsindex ad06385c3..ff63d67d2 100644--- a/api/agents/alpha.js+++ b/api/agents/alpha.js@@ -213,7 +213,6 @@ async function gatherSignals(mint, network, { agentId, meta, owner }) {owner ? getDailySpendLamports(agentId, network).catch(() => 0n) : Promise.resolve(0n),]);- const solPrice = num(coin?.usd_market_cap) && num(coin?.market_cap) ? coin.usd_market_cap / coin.market_cap : null;const createdSec = num(coin?.created_timestamp) ? Math.floor(coin.created_timestamp / 1000) : null;const liquiditySol = curve ? round3(Number(BigInt(curve.realSolReserves)) / 1e9) : null;const gradPct = num(grad?.progress) != null ? Math.round(num(grad.progress) * 100) : (curve?.complete ? 100 : null);@@ -316,6 +315,7 @@ async function handleRead(req, res, id) {try {({ signals, context, hasData } = await gatherSignals(mint, network, { agentId: id, meta, owner }));} catch (e) {+ console.error('[agents/alpha] signal gather failed', mint, e?.message || e);return error(res, 502, 'signal_error', 'could not read live signals for this launch — try again');}diff --git a/prompts/swarm-100/api-agents-04.md b/prompts/swarm-100/api-agents-04.mddeleted file mode 100644index ff8cf71ad..000000000--- a/prompts/swarm-100/api-agents-04.md+++ /dev/null@@ -1,110 +0,0 @@-# API audit: api/agents batch 04 (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/a2a-call.js-- api/agents/a2a-cart-verify.js-- api/agents/a2a-hire.js-- api/agents/a2a-mandate.js-- api/agents/a2a-paid.js-- api/agents/agent-mirror.js-- api/agents/agent-strategy-objects.js-- api/agents/agent-trade.js-- api/agents/alpha.js-- api/agents/autopilot.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-04.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/a2a-hire-handler.test.js b/tests/a2a-hire-handler.test.jsnew file mode 100644index 000000000..f9fc4e01f--- /dev/null+++ b/tests/a2a-hire-handler.test.js@@ -0,0 +1,211 @@+// POST /api/agents/a2a-hire - the handler itself.+//+// The hire visualizer's pure phase/cap helpers had tests (a2a-hire-phases,+// a2a-hire-visualizer) but the endpoint that calls them had none, so a shadowed+// binding went unnoticed: a `const limits = getSpendLimits(...)` declared in the+// handler body shadowed the `limits` rate-limiter imported at module scope, which+// put the earlier `await limits.mcpAgentPay(...)` in a temporal dead zone. Every+// authenticated hire 500'd with "Cannot access 'limits' before initialization":+// the whole agent-to-agent hire path was dead, while unauthenticated probes+// (which return 401 before that line) looked perfectly healthy.+//+// These tests walk the handler past that line on every entry path, so any future+// shadowing or reordering fails here instead of in production.++import { beforeEach, describe, expect, it, vi } from 'vitest';++const rateLimitCalls = [];++vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => ({ id: 'owner-1' })),+ authenticateBearer: vi.fn(async () => null),+ extractBearer: vi.fn(() => null),+}));++vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));++vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: {+ mcpAgentPay: vi.fn(async (key) => {+ rateLimitCalls.push(key);+ return { success: true };+ }),+ },+ clientIp: () => '127.0.0.1',+}));++const dbState = { hirer: null };+vi.mock('../api/_lib/db.js', () => ({+ sql: vi.fn(async (strings) => {+ const q = (typeof strings === 'string' ? strings : strings.join('?')).toLowerCase();+ if (/from agent_identities/.test(q)) return dbState.hirer ? [dbState.hirer] : [];+ return [];+ }),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++const offerState = { offer: null };+vi.mock('../api/_lib/agent-economy.js', () => ({+ atomicsToUsdc: (a) => Number(a) / 1e6,+ getOfferBySlug: vi.fn(async () => offerState.offer),+ recordHire: vi.fn(async () => ({ row: { id: 'hire-1', status: 'pending' }, existing: false })),+ updateHire: vi.fn(async () => ({ id: 'hire-1', status: 'failed' })),+}));++// Spend policy, screen frames, and the payment rails: the hire never reaches the+// settlement leg in these tests, but every import still has to resolve.+vi.mock('../api/_lib/agent-trade-guards.js', () => ({+ SpendLimitError: class SpendLimitError extends Error {},+ reserveSpendUsd: vi.fn(async () => ({ reservationId: 'res-1', dailySpentUsd: 0 })),+ releaseSpendReservation: vi.fn(async () => {}),+ updateCustodyEvent: vi.fn(async () => {}),+ recordCustodyEvent: vi.fn(async () => {}),+ getSpendLimits: vi.fn(() => ({ per_tx_usd: 5, daily_usd: 25 })),+}));++vi.mock('../api/_lib/agent-screen-frame.js', () => ({ writeScreenFrame: vi.fn(async () => {}) }));+vi.mock('../api/_lib/x402-user-payer.js', () => ({+ payExternalX402: vi.fn(async () => { throw Object.assign(new Error('not reached'), { code: 'payment_failed' }); }),+ resolveSpendEnabled: vi.fn(() => true),+}));+vi.mock('../api/_lib/agent-paid-services.js', () => ({ serviceResourceUrl: (slug) => `https://three.ws/api/x402/service/${slug}` }));+vi.mock('../api/_lib/agent-wallet.js', () => ({ recoverSolanaAgentKeypair: vi.fn(async () => ({})) }));+vi.mock('../api/_lib/agent-invocation-onchain.js', () => ({ recordInvocationReceipt: vi.fn(async () => ({ signature: 'sig' })) }));++const { default: handler } = await import('../api/agents/a2a-hire.js');++const HIRER_ID = '22222222-2222-4222-8222-222222222222';+const WALLET = 'So11111111111111111111111111111111111111112';++function makeReq(body) {+ return {+ method: 'POST',+ url: '/api/agents/a2a-hire',+ headers: { 'content-type': 'application/json', origin: 'https://three.ws', 'x-csrf-token': 't' },+ body,+ };+}++function makeRes() {+ return {+ statusCode: 0,+ payload: null,+ headers: {},+ setHeader(k, v) { this.headers[String(k).toLowerCase()] = v; },+ getHeader(k) { return this.headers[String(k).toLowerCase()]; },+ removeHeader(k) { delete this.headers[String(k).toLowerCase()]; },+ writeHead(code) { this.statusCode = code; return this; },+ get headersSent() { return false; },+ get writableEnded() { return false; },+ end(chunk) {+ if (chunk) { try { this.payload = JSON.parse(String(chunk)); } catch { this.payload = String(chunk); } }+ return this;+ },+ };+}++async function post(body) {+ const res = makeRes();+ await handler(makeReq(body), res);+ return res;+}++function ownedHirer() {+ return { id: HIRER_ID, user_id: 'owner-1', name: 'Mine', meta: { solana_address: WALLET, encrypted_solana_secret: 'ENC' } };+}++beforeEach(() => {+ rateLimitCalls.length = 0;+ dbState.hirer = null;+ offerState.offer = null;+ vi.clearAllMocks();+});++describe('POST /api/agents/a2a-hire', () => {+ it('rate-limits the authenticated caller instead of crashing on a shadowed binding', async () => {+ const res = await post({});+ expect(res.statusCode).toBe(400);+ expect(res.payload.error).toBe('validation_error');+ // The temporal-dead-zone crash happened on this exact call. A 500 here, or an+ // empty list, means the shadowing is back.+ expect(rateLimitCalls).toEqual(['owner-1']);+ });++ it('requires a serviceSlug', async () => {+ const res = await post({ hirerAgentId: HIRER_ID });+ expect(res.statusCode).toBe(400);+ expect(res.payload.error_description).toMatch(/serviceSlug/);+ });++ it('404s when the hiring agent does not exist', async () => {+ const res = await post({ hirerAgentId: HIRER_ID, serviceSlug: 'inspect-glb' });+ expect(res.statusCode).toBe(404);+ expect(res.payload.error).toBe('not_found');+ });++ it('403s when the caller does not own the hiring agent', async () => {+ dbState.hirer = { id: HIRER_ID, user_id: 'someone-else', name: 'Theirs', meta: {} };+ const res = await post({ hirerAgentId: HIRER_ID, serviceSlug: 'inspect-glb' });+ expect(res.statusCode).toBe(403);+ expect(res.payload.error).toBe('forbidden');+ });++ it('409s when the hiring agent has no wallet to pay from', async () => {+ dbState.hirer = { id: HIRER_ID, user_id: 'owner-1', name: 'Mine', meta: {} };+ const res = await post({ hirerAgentId: HIRER_ID, serviceSlug: 'inspect-glb' });+ expect(res.statusCode).toBe(409);+ expect(res.payload.error).toBe('no_wallet');+ });++ // Past the spend-policy read at the top of the wallet-bearing path: that read is+ // the statement that shadowed the rate limiter, so it has to be exercised too.+ it('reads the agent spend policy and reports an unknown offer as 404', async () => {+ dbState.hirer = ownedHirer();+ const res = await post({ hirerAgentId: HIRER_ID, serviceSlug: 'no-such-offer' });+ expect(res.statusCode).toBe(404);+ expect(res.payload.error).toBe('offer_not_found');++ const { getSpendLimits } = await import('../api/_lib/agent-trade-guards.js');+ expect(getSpendLimits).toHaveBeenCalled();+ });++ it('refuses an agent hiring its own service before any spend is reserved', async () => {+ dbState.hirer = ownedHirer();+ offerState.offer = {+ slug: 'self', name: 'Self skill', service_id: 's1', price_atomics: '1000',+ network: 'solana', method: 'POST',+ provider: { id: HIRER_ID, name: 'Mine', is_public: true, solana_address: WALLET },+ };+ const res = await post({ hirerAgentId: HIRER_ID, serviceSlug: 'self' });+ expect(res.statusCode).toBe(400);+ expect(res.payload.error).toBe('self_hire');++ const { reserveSpendUsd } = await import('../api/_lib/agent-trade-guards.js');+ expect(reserveSpendUsd).not.toHaveBeenCalled();+ });++ it('rejects a hire priced above the caller-supplied per-call ceiling', async () => {+ dbState.hirer = ownedHirer();+ offerState.offer = {+ slug: 'pricey', name: 'Pricey skill', service_id: 's2', price_atomics: '5000000',+ network: 'solana', method: 'POST',+ provider: { id: 'provider-1', name: 'Them', is_public: true, solana_address: WALLET },+ };+ const res = await post({ hirerAgentId: HIRER_ID, serviceSlug: 'pricey', maxUsd: 0.5 });+ expect(res.statusCode).toBe(402);+ expect(res.payload.error).toBe('over_cap');++ const { reserveSpendUsd } = await import('../api/_lib/agent-trade-guards.js');+ expect(reserveSpendUsd).not.toHaveBeenCalled();+ });++ it('401s an unauthenticated caller', async () => {+ const auth = await import('../api/_lib/auth.js');+ auth.getSessionUser.mockResolvedValueOnce(null);+ auth.authenticateBearer.mockResolvedValueOnce(null);+ const res = await post({});+ expect(res.statusCode).toBe(401);+ expect(res.payload.error).toBe('unauthorized');+ });+});diff --git a/tests/a2a-paid-endpoint.test.js b/tests/a2a-paid-endpoint.test.jsnew file mode 100644index 000000000..57e37edbb--- /dev/null+++ b/tests/a2a-paid-endpoint.test.js@@ -0,0 +1,70 @@+// POST /api/agents/a2a-paid - JSON-RPC request body parsing.+//+// The A2A server used to re-read the raw request stream itself, which hangs+// forever once Express has already drained it on Cloud Run. The fix was to+// delegate to the shared readBody() in api/_lib/http.js, which prefers the+// pre-parsed body the server captured. The delegation landed but the import did+// not, so every JSON-RPC POST answered+// {"error":{"code":-32700,"message":"readBody is not defined"}}+// and the paid A2A skill was unreachable for every calling agent. Both the agent+// card (GET) and unauthenticated probes kept working, so nothing surfaced it.+//+// These tests pin the parse: a body that reaches the handler must be judged on+// its CONTENT (-32600 invalid request, -32601 unknown method), never rejected as+// unparseable (-32700).++import { describe, expect, it } from 'vitest';+import { Readable } from 'node:stream';++const { default: handler } = await import('../api/agents/a2a-paid.js');++function makeReq(body, { raw = null } = {}) {+ const payload = raw != null ? raw : JSON.stringify(body);+ const req = Readable.from([Buffer.from(payload)]);+ req.method = 'POST';+ req.url = '/api/agents/a2a-paid';+ req.headers = { 'content-type': 'application/json', origin: 'https://three.ws' };+ return req;+}++function makeRes() {+ return {+ statusCode: 200,+ _body: '',+ _headers: {},+ setHeader(k, v) { this._headers[String(k).toLowerCase()] = v; },+ getHeader(k) { return this._headers[String(k).toLowerCase()]; },+ removeHeader(k) { delete this._headers[String(k).toLowerCase()]; },+ writeHead(code) { this.statusCode = code; return this; },+ get headersSent() { return false; },+ get writableEnded() { return false; },+ end(chunk) { this._body = chunk ? String(chunk) : ''; return this; },+ get json() { try { return JSON.parse(this._body); } catch { return null; } },+ };+}++async function post(body, opts) {+ const res = makeRes();+ await handler(makeReq(body, opts), res);+ return res;+}++describe('POST /api/agents/a2a-paid - body parsing', () => {+ it('parses the body and rejects it on content, not as unparseable', async () => {+ const res = await post({});+ expect(res.json.error.code).toBe(-32600);+ expect(res.json.error.message).not.toMatch(/is not defined/);+ });++ it('routes a well-formed envelope to method dispatch', async () => {+ const res = await post({ jsonrpc: '2.0', id: 7, method: 'bogus/method', params: {} });+ expect(res.json.error.code).toBe(-32601);+ expect(res.json.id).toBe(7);+ });++ it('reports genuinely malformed JSON as a parse error', async () => {+ const res = await post(null, { raw: '{not json' });+ expect(res.json.error.code).toBe(-32700);+ expect(res.json.error.message).toMatch(/invalid JSON/i);+ });+});diff --git a/tests/agent-trade-endpoint.test.js b/tests/agent-trade-endpoint.test.jsindex eb178a1e8..6751cfab2 100644--- a/tests/agent-trade-endpoint.test.js+++ b/tests/agent-trade-endpoint.test.js@@ -526,6 +526,9 @@ describe('PUT /api/agents/:id/trade/limits: input validation', () => {expect(set.json.data.limits.daily_budget_sol).toBe(2);expect(set.json.data.limits.max_concurrent).toBe(3);expect(set.json.data.limits.kill_switch).toBe(true);+ // Proves savedLimits() is not vacuously null in the rejection cases above:+ // an accepted patch really does reach the meta write.+ expect(savedLimits().per_trade_sol).toBe(0.5);const cleared = await putLimits({ per_trade_sol: null });expect(cleared.statusCode).toBe(200);