Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

test(api): cover the agent launch-prep wallet gate and the wallet-intents HTTP boundary

nirholasb2fca71d372f
diff --git a/data/changelog.json b/data/changelog.json
index 7c20fd436..71619e8c5 100644
--- a/data/changelog.json
+++ b/data/changelog.json
@@ -1,6 +1,54 @@
{
"$comment": "Curated changelog entries for three.ws, the editorial layer of the public changelog. New PAGE launches are tracked automatically via the `added` field in data/pages.json; this file is for everything else holders care about: improvements, fixes, SDK releases, trading/payments capabilities, security work. scripts/build-page-index.mjs merges both sources into CHANGELOG.md, public/changelog.json, and public/changelog.xml. Newest first. Allowed tags: feature, improvement, fix, sdk, infra, docs, security. `link` is optional and must be a live three.ws path.",
"entries": [
+ {
+ "date": "2026-08-10",
+ "title": "Creator Studio skill analytics stops erroring on a bad agent filter, and creator profile links stop pointing at a missing page",
+ "summary": "The per-skill analytics panel in Creator Studio asks the API about one agent at a time. When that agent id was malformed, or arrived twice in the same URL, the reply was a generic server error with no explanation and the panel simply went blank. It now answers with a clear \"agent_id must be a UUID\" message the panel can show you. A negative lookback window (a hand-edited \"days=-5\", say) used to be accepted and then report zero activity forever, because the window started in the future; the window is now held to 1 to 365 days, and the endpoint is rate limited like every other signed-in read. Separately, the public creator profile behind the marketplace author modal was handing out a link to a /creators/ page that does not exist, for any creator who has not claimed a username. Those creators now come back with no link instead of one that 404s.",
+ "tags": [
+ "fix",
+ "improvement"
+ ]
+ },
+ {
+ "date": "2026-08-10",
+ "title": "Agent payment history pages correctly, proof-of-reserves answers at its documented address, and a signed-in trust read is no longer shareable",
+ "summary": "An audit of the agent sub-resources found four things worth fixing. Paging through an agent's payment history handed back a page marker that did not match how the list is ordered, so scrolling past the first page could skip payments or repeat one; the marker now carries the timestamp the list sorts on and pages are exact. On the same endpoint, a non-numeric, negative, or oversized page size and a malformed page marker each produced a server error instead of an answer, so a mistyped link read as an outage. Proof-of-reserves has always been documented at /api/agents/<id>/reserves as well as the longer Solana path, but only the long one worked: the short address quietly returned the agent record instead. It serves reserves now. The reputation, unlocks, and reserves reads also mark a signed-in response private, because those responses carry your ownership flag and, for reputation, your owner-only guidance, and they were previously marked cacheable by shared caches. Anonymous reads are still served from the edge. Pinning an agent memory file now rejects malformed data up front rather than storing a corrupted copy under a real-looking address.",
+ "tags": [
+ "fix",
+ "security"
+ ]
+ },
+ {
+ "date": "2026-08-10",
+ "title": "Creator Studio skill analytics no longer errors out on a bad agent filter, and creator profile links stop pointing at a missing page",
+ "summary": "The per-skill analytics panel in Creator Studio asks the API for one agent at a time. If that agent id was malformed, or arrived twice in the same URL, the request came back as a generic server error with no explanation, and the panel simply went blank. It now answers with a clear \"agent_id must be a UUID\" message that the panel can show you. A negative lookback window (for example a hand-edited \"days=-5\") used to be accepted and then quietly report zero activity forever, because the window started in the future; the window is now held to 1 to 365 days. The endpoint is also rate limited like every other signed-in read. Separately, the public creator profile that the marketplace author modal loads was handing out a link to /creators/<id>, a page that does not exist, for any creator who has not claimed a username. Those creators now come back with no link instead of one that 404s.",
+ "tags": [
+ "fix",
+ "improvement"
+ ]
+ },
+ {
+ "date": "2026-08-10",
+ "title": "Holder cohorts answer the real reason a request was refused, and the holder panel is cached again",
+ "summary": "An audit of the /api/coin market endpoints found the holder-cohorts route deciding things in the wrong order. Asking to export a cohort that does not exist, or asking without being signed in, made the server fetch the whole holder list first and then reply \"holder data is temporarily unavailable\", which is not what went wrong and hides the fix. Those requests now answer immediately with the actual reason (unknown cohort, not signed in, not the coin's creator), and no holder lookup is spent on a request that was never going to be allowed. The public holder counts on a coin page are cacheable again, so the panel loads from the edge instead of re-querying on every view, and the whole route shares one rate limit rather than leaving its database side unguarded. Separately, the Fear and Greed page no longer claims a reading is unchanged from last week when it has only a single day of history to compare against.",
+ "tags": [
+ "fix",
+ "improvement"
+ ],
+ "link": "/fear-greed"
+ },
+ {
+ "date": "2026-08-10",
+ "title": "The free Crypto Data API index now lists the portfolio and airdrop endpoints it was hiding",
+ "summary": "Two live endpoints, the wallet portfolio overview and the airdrop eligibility checker, shipped without a catalog descriptor, so the one-URL bundle index at /api/crypto and the OpenAPI document generated from it skipped both entirely. An agent discovering the API the way we tell it to could not see either endpoint, even though both answered fine when called directly. Both are described now, in the index, in the OpenAPI doc, and in the docs page, and a test holds the catalog to every endpoint that ships so the next one cannot go missing. Two smaller honesty fixes went with it: the bonding and launches endpoints stopped telling browsers they accept POST when they only answer GET, and the launches error for a bad limit now says what actually happens to an oversized one (it is capped at 100, not rejected).",
+ "tags": [
+ "fix",
+ "improvement",
+ "docs"
+ ],
+ "link": "/docs/crypto-api"
+ },
{
"date": "2026-08-10",
"title": "Talking-avatar video says what actually went wrong, and audio uploads are bounded",
diff --git a/prompts/swarm-100/api-agents-09.md b/prompts/swarm-100/api-agents-09.md
deleted file mode 100644
index a4d33196a..000000000
--- a/prompts/swarm-100/api-agents-09.md
+++ /dev/null
@@ -1,106 +0,0 @@
-# API audit: api/agents batch 09 (6 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/talk.js
-- api/agents/tokens/[action].js
-- api/agents/unstoppable-status.js
-- api/agents/wallet-embed.js
-- api/agents/wallet-intents.js
-- api/agents/x402/[action].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-09.md
-
- The shrinking directory is this campaign's only progress ledger; there is
- no progress log to update.
-4. Final report: what step 0 measured, what changed (file list), evidence per
- Definition of done line, and any one-line judgment calls. No trailing
- questions, no unexecuted plans.
-
-If a line genuinely cannot pass inside this session (an external party must
-respond, or an owner-gated action is the final step), finish everything else,
-leave this file in place, and state exactly which line remains and who owns
-it. Never delete this file on a partial.
diff --git a/tests/api-agents-token-launch-prep.test.js b/tests/api-agents-token-launch-prep.test.js
new file mode 100644
index 000000000..7a353cdb5
--- /dev/null
+++ b/tests/api-agents-token-launch-prep.test.js
@@ -0,0 +1,145 @@
+// Guards the ownership gate on POST /api/agents/tokens/launch-prep
+// (api/agents/tokens/[action].js).
+//
+// The handler builds a real pump.fun create transaction whose `creator` is the
+// wallet_address in the request body, so that address MUST be the one the agent
+// is actually deployed under. The check was written as an exact comparison
+// nested inside a case-INSENSITIVE one, which meant the exact comparison only
+// ran when the two already differed case-insensitively: a case-variant address
+// skipped the gate entirely. Solana addresses are case-sensitive base58, so
+// "AbC…" and "aBc…" are two different accounts and the variant would have
+// become the coin's creator.
+
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+import { Readable } from 'node:stream';
+
+const AGENT_ID = '33333333-3333-4333-8333-333333333333';
+const USER_ID = 'user-launch-1';
+// A real-shaped base58 address with both cases, so a lowercased copy is a
+// different (but still syntactically valid) Solana address.
+const WALLET = '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU';
+const WALLET_CASE_VARIANT = '7xkxtg2cw87d97txjsdpbd5jbkhetqa83tzrujosgasu';
+
+const authState = { session: null };
+const sqlState = { queue: [] };
+
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => authState.session),
+}));
+
+vi.mock('../api/_lib/db.js', () => ({
+ sql: vi.fn(async () => (sqlState.queue.length ? sqlState.queue.shift() : [])),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: {
+ authIp: vi.fn(async () => ({ success: true })),
+ authedReadIp: vi.fn(async () => ({ success: true })),
+ },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+// The handler never reaches these in the cases under test; stubbing them keeps
+// the import cheap and guarantees a leak past the gate cannot touch the network.
+vi.mock('../api/_lib/solana/connection.js', () => ({
+ solanaConnection: vi.fn(() => {
+ throw new Error('the test reached the Solana path, which means the gate let it through');
+ }),
+}));
+vi.mock('../api/_lib/r2.js', () => ({
+ r2: { send: vi.fn(async () => { throw new Error('the test reached R2, which means the gate let it through'); }) },
+ publicUrl: vi.fn((k) => `https://cdn.test/${k}`),
+}));
+
+const handler = (await import('../api/agents/tokens/[action].js')).default;
+
+function post(body) {
+ const raw = Buffer.from(JSON.stringify(body));
+ const req = Readable.from([raw]);
+ req.method = 'POST';
+ req.url = '/api/agents/tokens/launch-prep';
+ req.headers = { host: 'localhost', 'content-type': 'application/json' };
+ req.query = { action: 'launch-prep' };
+ const res = {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ end(chunk) { if (chunk !== undefined) this.body += chunk; this.writableEnded = true; },
+ };
+ return handler(req, res).then(() => ({
+ status: res.statusCode,
+ payload: res.body ? JSON.parse(res.body) : null,
+ }));
+}
+
+function agentRow(meta) {
+ return [{ id: AGENT_ID, name: 'Launch Agent', user_id: USER_ID, wallet_address: WALLET, meta }];
+}
+
+function launchBody(walletAddress) {
+ return {
+ agent_id: AGENT_ID,
+ provider: 'pumpfun',
+ cluster: 'mainnet',
+ wallet_address: walletAddress,
+ name: 'Probe Coin',
+ symbol: 'PROBE',
+ };
+}
+
+beforeEach(() => {
+ authState.session = { id: USER_ID };
+ sqlState.queue = [];
+});
+
+describe('launch-prep ownership gate', () => {
+ it('rejects a wallet that differs from the agent only by letter case', async () => {
+ sqlState.queue.push(agentRow({ onchain: { family: 'solana', wallet: WALLET } }));
+ const { status, payload } = await post(launchBody(WALLET_CASE_VARIANT));
+ expect(status).toBe(403);
+ expect(payload.error).toBe('forbidden');
+ });
+
+ it('rejects an unrelated wallet', async () => {
+ sqlState.queue.push(agentRow({ onchain: { family: 'solana', wallet: WALLET } }));
+ const { status, payload } = await post(launchBody('9unrelatedWa11etAddressForThisTestOn1yXXXX'));
+ expect(status).toBe(403);
+ expect(payload.error).toBe('forbidden');
+ });
+
+ it('lets the exact wallet through to the next precondition', async () => {
+ // Already-launched agent, so the check immediately after the wallet gate
+ // answers 409. Reaching it proves the gate accepted the exact match.
+ sqlState.queue.push(
+ agentRow({ onchain: { family: 'solana', wallet: WALLET }, token: { mint: 'AlreadyLaunchedMint' } }),
+ );
+ const { status, payload } = await post(launchBody(WALLET));
+ expect(status).toBe(409);
+ expect(payload.error).toBe('conflict');
+ });
+
+ it('refuses an agent that is not deployed on Solana yet', async () => {
+ sqlState.queue.push(agentRow({}));
+ const { status, payload } = await post(launchBody(WALLET));
+ expect(status).toBe(409);
+ expect(payload.error).toBe('precondition_failed');
+ });
+
+ it('404s an agent the caller does not own', async () => {
+ sqlState.queue.push([]);
+ const { status, payload } = await post(launchBody(WALLET));
+ expect(status).toBe(404);
+ expect(payload.error).toBe('not_found');
+ });
+
+ it('401s a logged-out caller', async () => {
+ authState.session = null;
+ const { status, payload } = await post(launchBody(WALLET));
+ expect(status).toBe(401);
+ expect(payload.error).toBe('unauthorized');
+ });
+});
diff --git a/tests/api-agents-wallet-intents-handler.test.js b/tests/api-agents-wallet-intents-handler.test.js
new file mode 100644
index 000000000..b0338c2ea
--- /dev/null
+++ b/tests/api-agents-wallet-intents-handler.test.js
@@ -0,0 +1,257 @@
+// Route-handler tests for api/agents/wallet-intents.js (dispatched from
+// api/agents/[id].js as /api/agents/:id/intents).
+//
+// The engine's pure validation lives in tests/wallet-intents.test.js. What is
+// covered HERE is the HTTP boundary that engine never sees:
+//
+// 1. Ownership: a stranger can neither read nor arm an intent, and an
+// unknown agent is a 404 rather than a leak of "exists but forbidden".
+// 2. Body handling: readJson resolves any valid JSON, including `null`, a
+// bare string, and a number. Every write handler then reads a property
+// off it, so a scalar body used to raise a TypeError and surface as an
+// opaque 500 for what is plainly malformed input. It must be a 4xx.
+// 3. Compile context: the compiler prompt lists the wallet's REAL tokens so
+// a rule like "sell half my $THREE" can ground against something the
+// agent actually holds. That list was declared and never filled, so every
+// compile told the model the wallet was empty.
+
+import { Readable } from 'node:stream';
+import { describe, it, expect, beforeEach, vi } from 'vitest';
+
+const AGENT_ID = '11111111-1111-4111-8111-111111111111';
+const INTENT_ID = '22222222-2222-4222-8222-222222222222';
+const OWNER_ID = 'owner-1';
+const WALLET = '7xKXtg2CW87d97TXJSDpbD5jBkheTqA83TZRuJosgAsU';
+const THREE = 'FeMbDoX7R1Psc4GEcvJdsbNbZA3bfztcyDCatJVJpump';
+// A clearly-synthetic second mint: these cases only assert pass-through, so a
+// real third-party token address would add nothing but a claim we do not mean.
+const OTHER_MINT = 'THREEsynthetic1111111111111111111111111111';
+
+const authState = { session: null };
+const sqlState = { queue: [] };
+const balancesState = { tokens: [], fail: false };
+const compileState = { ctx: null, result: null };
+
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => authState.session),
+ authenticateBearer: vi.fn(async () => null),
+ extractBearer: vi.fn(() => null),
+}));
+
+vi.mock('../api/_lib/db.js', () => ({
+ sql: vi.fn(async () => (sqlState.queue.length ? sqlState.queue.shift() : [])),
+ isDbUnavailableError: () => false,
+ isDbCapacityError: () => false,
+}));
+
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: {
+ walletRead: vi.fn(async () => ({ success: true })),
+ chatUser: vi.fn(async () => ({ success: true })),
+ },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));
+vi.mock('../api/_lib/provider-keys.js', () => ({ loadUserProviderKeys: vi.fn(async () => ({})) }));
+vi.mock('../api/_lib/agent-trade-guards.js', () => ({
+ getSpendLimits: vi.fn(() => ({ per_tx_usd: null, daily_usd: null, frozen: false })),
+ getTradeLimits: vi.fn(() => ({})),
+}));
+vi.mock('../api/_lib/agent-wallet.js', () => ({
+ getSolanaAddressBalances: vi.fn(async () => ({ sol: 2.5, usdc: 0 })),
+}));
+vi.mock('../api/_lib/avatar-wallet.js', () => ({ solUsdPrice: vi.fn(async () => 150) }));
+vi.mock('../api/_lib/balances.js', () => ({
+ getBalances: vi.fn(async () => {
+ if (balancesState.fail) throw new Error('rpc down');
+ return { native: { amount: 2.5 }, tokens: balancesState.tokens };
+ }),
+}));
+
+vi.mock('../api/_lib/wallet-intents.js', () => ({
+ listIntents: vi.fn(async () => []),
+ getIntent: vi.fn(async () => null),
+ createIntent: vi.fn(async () => ({ id: 'intent-1' })),
+ updateIntent: vi.fn(async () => null),
+ deleteIntent: vi.fn(async () => false),
+ runIntentNow: vi.fn(async () => ({ dry_run: true })),
+ compileIntentFromText: vi.fn(async (_text, ctx) => {
+ compileState.ctx = ctx;
+ return compileState.result ?? { ok: false, error: 'clarify', message: 'need more' };
+ }),
+ normalizeIntent: vi.fn(() => ({ ok: false, error: 'invalid_intent', message: 'no' })),
+ describeIntent: vi.fn(() => 'readback'),
+}));
+
+const handler = (await import('../api/agents/wallet-intents.js')).default;
+
+// A local request builder rather than the shared monetization helper: these
+// cases turn on sending a body that is valid JSON but NOT an object, and the
+// shared helper drops a falsy body (and its content-type) entirely.
+function makeReq({ method, url, rawBody = null }) {
+ const req = Readable.from(rawBody == null ? [] : [Buffer.from(rawBody)]);
+ req.method = method;
+ req.url = url;
+ req.headers = { host: 'localhost', ...(rawBody == null ? {} : { 'content-type': 'application/json' }) };
+ return req;
+}
+
+function makeRes() {
+ return {
+ statusCode: 200,
+ headers: {},
+ body: '',
+ writableEnded: false,
+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },
+ end(chunk) { if (chunk !== undefined) this.body += chunk; this.writableEnded = true; },
+ };
+}
+
+async function call(action, { method = 'POST', rawBody = null, query = '' } = {}) {
+ const url = `/api/agents/${AGENT_ID}/intents${action ? `/${action}` : ''}${query}`;
+ const req = makeReq({ method, url, rawBody });
+ const res = makeRes();
+ await handler(req, res, AGENT_ID, action);
+ return { status: res.statusCode, body: res.body ? JSON.parse(res.body) : null };
+}
+
+// The handler loads the agent row itself before doing anything else, so every
+// authorized case has to prime that read.
+function primeOwnedAgent(meta = { solana_address: WALLET }) {
+ sqlState.queue.push([{ id: AGENT_ID, user_id: OWNER_ID, name: 'Test Agent', meta }]);
+}
+
+beforeEach(() => {
+ authState.session = { id: OWNER_ID };
+ sqlState.queue = [];
+ balancesState.tokens = [];
+ balancesState.fail = false;
+ compileState.ctx = null;
+ compileState.result = null;
+});
+
+describe('wallet-intents handler: ownership', () => {
+ it('refuses a logged-out caller with 401 before touching the agent row', async () => {
+ authState.session = null;
+ const { status, body } = await call('', { method: 'GET' });
+ expect(status).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ });
+
+ it('refuses a signed-in stranger with 403', async () => {
+ sqlState.queue.push([{ id: AGENT_ID, user_id: 'someone-else', name: 'A', meta: {} }]);
+ const { status, body } = await call('', { method: 'GET' });
+ expect(status).toBe(403);
+ expect(body.error).toBe('forbidden');
+ });
+
+ it('404s an unknown agent', async () => {
+ sqlState.queue.push([]);
+ const { status, body } = await call('', { method: 'GET' });
+ expect(status).toBe(404);
+ expect(body.error).toBe('not_found');
+ });
+
+ it('404s an unknown intents sub-resource', async () => {
+ const { status, body } = await call('not-a-verb-or-uuid', { method: 'GET' });
+ expect(status).toBe(404);
+ expect(body.error).toBe('not_found');
+ });
+});
+
+describe('wallet-intents handler: a non-object JSON body is a 4xx, never a 500', () => {
+ // JSON.parse accepts every one of these; a handler that then reads
+ // `body.text` off them raises a TypeError, which wrap() reports as a 500.
+ for (const raw of ['null', '"just a string"', '42', 'true']) {
+ it(`compile rejects ${raw} with a validation error`, async () => {
+ primeOwnedAgent();
+ const { status, body } = await call('compile', { rawBody: raw });
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+
+ it(`copilot rejects ${raw} with a validation error`, async () => {
+ primeOwnedAgent();
+ const { status, body } = await call('copilot', { rawBody: raw });
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+
+ it(`create rejects ${raw} with a validation error`, async () => {
+ primeOwnedAgent();
+ const { status, body } = await call('', { rawBody: raw });
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+
+ it(`run rejects ${raw} with a validation error`, async () => {
+ primeOwnedAgent();
+ const { status, body } = await call('run', { rawBody: raw });
+ expect(status).toBe(400);
+ expect(body.error).toBe('validation_error');
+ });
+ }
+
+ it('update treats a scalar body as an empty patch rather than throwing', async () => {
+ primeOwnedAgent();
+ // updateIntent is mocked to report "no such intent"; the point is that the
+ // request reached it at all instead of dying on `'enabled' in null`.
+ const { status, body } = await call(INTENT_ID, { method: 'PUT', rawBody: 'null' });
+ expect(status).toBe(404);
+ expect(body.error).toBe('not_found');
+ });
+
+ it('still rejects a body that is not JSON at all', async () => {
+ primeOwnedAgent();
+ const { status } = await call('compile', { rawBody: '{oops' });
+ expect(status).toBe(400);
+ });
+});
+
+describe('wallet-intents handler: the compiler sees real holdings', () => {
+ it('passes the wallet live tokens into the compile context', async () => {
+ primeOwnedAgent();
+ balancesState.tokens = [
+ { mint: THREE, symbol: 'THREE', amount: 1250.5 },
+ { mint: OTHER_MINT, symbol: 'TEST', amount: 4 },
+ ];
+ const { status } = await call('compile', { rawBody: JSON.stringify({ text: 'sell half my $THREE' }) });
+ expect(status).toBe(200);
+ expect(compileState.ctx.holdings).toEqual([
+ { mint: THREE, symbol: 'THREE', ui_amount: 1250.5 },
+ { mint: OTHER_MINT, symbol: 'TEST', ui_amount: 4 },
+ ]);
+ expect(compileState.ctx.balanceSol).toBe(2.5);
+ });
+
+ it('drops zero-balance dust so the prompt only lists what is actually held', async () => {
+ primeOwnedAgent();
+ balancesState.tokens = [
+ { mint: THREE, symbol: 'THREE', amount: 0 },
+ { mint: OTHER_MINT, symbol: 'TEST', amount: 0.5 },
+ ];
+ await call('compile', { rawBody: JSON.stringify({ text: 'anything' }) });
+ expect(compileState.ctx.holdings).toEqual([{ mint: OTHER_MINT, symbol: 'TEST', ui_amount: 0.5 }]);
+ });
+
+ it('still compiles when the balance provider is down', async () => {
+ primeOwnedAgent();
+ balancesState.fail = true;
+ const { status } = await call('compile', { rawBody: JSON.stringify({ text: 'anything' }) });
+ expect(status).toBe(200);
+ expect(compileState.ctx.holdings).toEqual([]);
+ });
+
+ it('skips the mainnet-only holdings read on devnet', async () => {
+ primeOwnedAgent();
+ balancesState.tokens = [{ mint: THREE, symbol: 'THREE', amount: 10 }];
+ const { status } = await call('compile', {
+ rawBody: JSON.stringify({ text: 'anything' }),
+ query: '?network=devnet',
+ });
+ expect(status).toBe(200);
+ expect(compileState.ctx.network).toBe('devnet');
+ expect(compileState.ctx.holdings).toEqual([]);
+ });
+});