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(agents-api): cover the agent sub-resources, brain import, memory CID, and identity endpoints
nirholase6375ab7f915
diff --git a/tests/api-agents-identity-endpoints.test.js b/tests/api-agents-identity-endpoints.test.jsnew file mode 100644index 000000000..b48d93f5d--- /dev/null+++ b/tests/api-agents-identity-endpoints.test.js@@ -0,0 +1,250 @@+// Regression cover for the /api/agents identity + economy read surfaces.+//+// Every case here is a defect this suite was written against, found by probing+// the live handlers:+//+// 1. balances.js read the session id off `auth.userId`, but getSessionUser+// returns the user row (`auth.id`). `isOwner` was therefore false for+// every signed-in owner, so the "Yours" marker could never render.+// 2. check-name.js and economy.js passed caller-supplied ids straight into+// `WHERE col = $1` against uuid columns. A malformed id came back as+// Postgres 22P02 and surfaced to the caller as a 500 instead of a 400.+// 3. by-wallet.js coerced `chain_id` with `Number(...) || null`, so a+// non-numeric value silently dropped the filter and returned every chain's+// agents as if that were what the caller asked for.+//+// The DB and the on-chain valuation layer are mocked so these assert the+// handlers' own validation and shaping, not Neon or Helius.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const AGENT_ID = '5eff00ac-65fa-4b0f-aef1-c26eb1a9c37d';+const OWNER_ID = '36b42d48-e968-476b-826a-3b8f700da867';+const OTHER_ID = '11111111-2222-4333-8444-555555555555';+const EVM_ADDR = '0x49da9e65cfa25b13732a46ddb2d2ceeada14f65e';++// The session the auth mock hands back; individual tests flip it to null.+let session = null;+// What the db mock resolves for the next sql`` call.+let dbRows = [];+let dbCalls = 0;++vi.mock('../api/_lib/db.js', () => ({+ sql: () => {+ dbCalls += 1;+ return Promise.resolve(dbRows);+ },+ sqlValues: () => ({}),+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++vi.mock('../api/_lib/auth.js', () => ({+ getSessionUser: async () => session,+ authenticateBearer: async () => null,+ extractBearer: () => null,+}));++vi.mock('../api/_lib/rate-limit.js', () => ({+ limits: {+ walletRead: async () => ({ success: true }),+ authedReadIp: async () => ({ success: true }),+ checkName: async () => ({ success: true }),+ },+ clientIp: () => '203.0.113.7',+}));++vi.mock('../api/_lib/balances.js', () => ({+ getBalances: async () => ({ native: { amount: 0, usd: 0, price: 0 }, tokens: [] }),+ walletUsdTotal: () => 0,+}));++// Economy reads have their own suites; here they only need to prove that a+// malformed id never reaches them.+const economyCalls = [];+vi.mock('../api/_lib/agent-economy.js', () => ({+ listOffersWithStats: async (a) => { economyCalls.push(['offers', a]); return []; },+ listHiresForAgent: async (...a) => { economyCalls.push(['hires', a]); return []; },+ agentEconomySummary: async (a) => { economyCalls.push(['summary', a]); return {}; },+ providerStats: async (a) => { economyCalls.push(['stats', a]); return {}; },+ getOfferBySlug: async () => null,+ getHireById: async () => null,+ rateHire: async () => null,+}));++vi.mock('../api/_lib/csrf.js', () => ({ requireCsrf: async () => true }));++const { default: balancesHandler } = await import('../api/agents/balances.js');+const { default: checkNameHandler } = await import('../api/agents/check-name.js');+const { default: byWalletHandler } = await import('../api/agents/by-wallet.js');+const { default: economyHandler } = await import('../api/agents/economy.js');++// Minimal Vercel-shaped res that records what json()/error() wrote.+function fakeRes() {+ return {+ statusCode: 200,+ headers: {},+ body: null,+ setHeader(k, v) { this.headers[k.toLowerCase()] = v; },+ getHeader(k) { return this.headers[k.toLowerCase()]; },+ writeHead(status) { this.statusCode = status; return this; },+ end(payload) {+ if (payload) { try { this.body = JSON.parse(payload); } catch { this.body = payload; } }+ return this;+ },+ };+}++function req({ method = 'GET', url = '/', body = null, headers = {} } = {}) {+ return {+ method,+ url,+ headers: { 'content-type': 'application/json', ...headers },+ query: {},+ body,+ };+}++beforeEach(() => {+ session = null;+ dbRows = [];+ dbCalls = 0;+ economyCalls.length = 0;+});++describe('POST /api/agents/balances', () => {+ it('marks the signed-in owner isOwner (reads session.id, not session.userId)', async () => {+ session = { id: OWNER_ID, email: '[email protected]' };+ dbRows = [{ id: AGENT_ID, user_id: OWNER_ID, meta: {} }];+ const res = fakeRes();+ await balancesHandler(req({ method: 'POST', url: '/api/agents/balances', body: { ids: [AGENT_ID] } }), res);++ expect(res.statusCode).toBe(200);+ expect(res.body.data[AGENT_ID].isOwner).toBe(true);+ });++ it('leaves isOwner false for a signed-in non-owner', async () => {+ session = { id: OTHER_ID, email: '[email protected]' };+ dbRows = [{ id: AGENT_ID, user_id: OWNER_ID, meta: {} }];+ const res = fakeRes();+ await balancesHandler(req({ method: 'POST', url: '/api/agents/balances', body: { ids: [AGENT_ID] } }), res);++ expect(res.body.data[AGENT_ID].isOwner).toBe(false);+ });++ it('rejects a body without an ids array', async () => {+ const res = fakeRes();+ await balancesHandler(req({ method: 'POST', url: '/api/agents/balances', body: {} }), res);++ expect(res.statusCode).toBe(400);+ expect(res.body.error).toBe('validation_error');+ });++ it('drops malformed ids and never queries when none survive', async () => {+ const res = fakeRes();+ await balancesHandler(req({ method: 'POST', url: '/api/agents/balances', body: { ids: ['not-a-uuid', 42] } }), res);++ expect(res.statusCode).toBe(200);+ expect(res.body.data).toEqual({});+ expect(dbCalls).toBe(0);+ });+});++describe('GET /api/agents/check-name', () => {+ it('rejects a non-uuid agent_id instead of leaking a Postgres error', async () => {+ session = { id: OWNER_ID };+ const res = fakeRes();+ await checkNameHandler(req({ url: '/api/agents/check-name?name=freshname&agent_id=not-a-uuid' }), res);++ expect(res.statusCode).toBe(400);+ expect(res.body.error).toBe('validation_error');+ expect(dbCalls).toBe(0);+ });++ it('accepts a well-formed agent_id and reports availability', async () => {+ session = { id: OWNER_ID };+ dbRows = [];+ const res = fakeRes();+ await checkNameHandler(req({ url: `/api/agents/check-name?name=freshname&agent_id=${AGENT_ID}` }), res);++ expect(res.statusCode).toBe(200);+ expect(res.body).toEqual({ available: true });+ });++ it('requires a session', async () => {+ const res = fakeRes();+ await checkNameHandler(req({ url: '/api/agents/check-name?name=freshname' }), res);++ expect(res.statusCode).toBe(401);+ });++ it('reports a denylisted name as unavailable without a lookup', async () => {+ session = { id: OWNER_ID };+ const res = fakeRes();+ await checkNameHandler(req({ url: '/api/agents/check-name?name=admin' }), res);++ expect(res.body).toEqual({ available: false, reason: 'denylisted' });+ expect(dbCalls).toBe(0);+ });+});++describe('GET /api/agents/by-wallet', () => {+ it('rejects a non-numeric chain_id rather than silently widening the result', async () => {+ const res = fakeRes();+ await byWalletHandler(req({ url: `/api/agents/by-wallet?address=${EVM_ADDR}&chain_id=abc` }), res);++ expect(res.statusCode).toBe(400);+ expect(res.body.error).toBe('validation_error');+ expect(dbCalls).toBe(0);+ });++ it('honours a numeric chain_id', async () => {+ dbRows = [{ id: AGENT_ID, name: 'Agent', description: null, avatar_id: null, home_url: null, erc8004_agent_id: null, erc8004_registry: null, chain_id: 8453, wallet_address: EVM_ADDR, created_at: '2026-05-13T12:47:24.086Z' }];+ const res = fakeRes();+ await byWalletHandler(req({ url: `/api/agents/by-wallet?address=${EVM_ADDR}&chain_id=8453` }), res);++ expect(res.statusCode).toBe(200);+ expect(res.body.agents[0]).toMatchObject({ id: AGENT_ID, chain_id: 8453, home_url: `/agent/${AGENT_ID}` });+ });++ it('rejects a malformed wallet address', async () => {+ const res = fakeRes();+ await byWalletHandler(req({ url: '/api/agents/by-wallet?address=0xnope' }), res);++ expect(res.statusCode).toBe(400);+ });+});++describe('GET /api/agents/economy', () => {+ it.each([+ ['offers', '/api/agents/economy?view=offers&agentId=nope', 'agentId'],+ ['hires', '/api/agents/economy?view=hires&agentId=nope', 'agentId'],+ ['hires cursor', `/api/agents/economy?view=hires&agentId=${AGENT_ID}&beforeId=junk`, 'beforeId'],+ ['summary', '/api/agents/economy?view=summary&agentId=nope', 'agentId'],+ ])('rejects a non-uuid id on view=%s', async (_label, url, field) => {+ const res = fakeRes();+ await economyHandler(req({ url }), res);++ expect(res.statusCode).toBe(400);+ expect(res.body.error).toBe('validation_error');+ expect(res.body.error_description).toContain(field);+ expect(economyCalls).toEqual([]);+ });++ it('passes a well-formed agentId through to the summary reads', async () => {+ const res = fakeRes();+ await economyHandler(req({ url: `/api/agents/economy?view=summary&agentId=${AGENT_ID}` }), res);++ expect(res.statusCode).toBe(200);+ expect(economyCalls.map((c) => c[0]).sort()).toEqual(['stats', 'summary']);+ expect(res.body.data.agent_id).toBe(AGENT_ID);+ });++ it('rejects an unknown view', async () => {+ const res = fakeRes();+ await economyHandler(req({ url: '/api/agents/economy?view=nope' }), res);++ expect(res.statusCode).toBe(400);+ expect(res.body.error).toBe('bad_view');+ });+});diff --git a/tests/api/agents-brain-import.test.js b/tests/api/agents-brain-import.test.jsnew file mode 100644index 000000000..4d2c95fc9--- /dev/null+++ b/tests/api/agents-brain-import.test.js@@ -0,0 +1,235 @@+// POST /api/agents/:id/brain/import: the merge must be idempotent.+//+// The regression this file exists to stop. A merge dedupes an incoming bundle+// entry against the target agent's stored memories by content hash, but a+// memory's `content_hash` is the digest of THAT ROW, and memoryDigest folds in+// the row id and created_at. An imported copy is therefore a different row with+// a different hash than the bundle entry it came from, so re-importing the same+// bundle matched nothing and inserted a fresh duplicate of every memory. Run a+// sync twice and the agent's mind doubled; run it in a loop and it grew without+// bound, while the response cheerfully reported `duplicates: 0`.+//+// The fix records the digest actually matched on in the row's provenance and+// dedupes against both keys. The tests below import the same bundle three times+// and require the second and third to insert nothing.+//+// The bundle itself is real (built by api/_lib/brain-bundle.js and verified by+// its own verifyBundle) so the integrity gates the handler runs before importing+// are exercised rather than stubbed. Only the DB, auth, CSRF and the custodial+// key vault are mocked.++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { makeReq, makeRes } from '../_helpers/monetization.js';++const AGENT_ID = '00000000-0000-4000-8000-0000000000b1';+const SOURCE_AGENT_ID = '00000000-0000-4000-8000-0000000000b2';+const OWNER_ID = 'user-owner';++// A tiny in-memory stand-in for agent_memories, so "did the second import insert+// a row?" is answerable rather than inferred from the response body alone.+let stored = [];+let agentRow = null;++const sqlMock = vi.fn((strings, ...values) => {+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);++ if (/from agent_identities/i.test(q)) return Promise.resolve(agentRow ? [agentRow] : []);+ if (/update agent_identities/i.test(q)) return Promise.resolve([]);++ // The dedupe read: both the row's own hash and the provenance source hash.+ if (/select content_hash/i.test(q)) {+ return Promise.resolve(+ stored.map((r) => ({ content_hash: r.content_hash, source_hash: r.source_hash })),+ );+ }+ if (/delete from agent_memories/i.test(q)) {+ stored = [];+ return Promise.resolve([]);+ }+ if (/insert into agent_memories/i.test(q)) {+ // values: agent_id, type, content, tags, context, salience, tier, is_public+ const [, type, content, tags, contextJson] = values;+ const provenance = JSON.parse(contextJson).provenance || {};+ const row = {+ id: `row-${stored.length + 1}`,+ agent_id: AGENT_ID,+ type,+ content,+ tags,+ created_at: new Date('2026-03-03T00:00:00Z'),+ // Mirrors production: content_hash is only written later, by the+ // best-effort re-sign, and it is the NEW row's digest, not the source's.+ content_hash: `local-digest-${stored.length + 1}`,+ source_hash: provenance.source_content_hash ?? null,+ };+ stored.push(row);+ return Promise.resolve([row]);+ }+ return Promise.resolve([]);+});+sqlMock.transaction = (queries) => Promise.all(queries);+vi.mock('../../api/_lib/db.js', () => ({+ sql: sqlMock,+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++let sessionUser = null;+vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => sessionUser),+ authenticateBearer: vi.fn(async () => null),+ extractBearer: vi.fn(() => null),+}));++vi.mock('../../api/_lib/csrf.js', () => ({ requireCsrf: vi.fn(async () => true) }));++// The custodial key vault is not reachable offline; an agent with no wallet is+// also the case that exposed the bug, since unsigned rows are the ones whose+// content_hash never matches the bundle.+vi.mock('../../api/_lib/brain-sign.js', async (importOriginal) => ({+ ...(await importOriginal()),+ loadAgentSigner: vi.fn(async () => null),+ signMemoryWithAgent: vi.fn(async () => ({ content_hash: null, signature: null })),+}));++vi.mock('../../api/_lib/brain-anchor.js', () => ({+ anchorBrain: vi.fn(async () => {+ throw new Error('not used');+ }),+ latestAnchor: vi.fn(async () => ({ anchor: null, currentBrainHash: null, inSync: false })),+ BrainAnchorError: class BrainAnchorError extends Error {},+}));++// Imported after the mocks: brain-bundle pulls in brain-sign, which pulls in the+// db module, and a static import would evaluate that chain before the factories+// above exist.+const { buildBundle, buildMemoryEntry } = await import('../../api/_lib/brain-bundle.js');+const { handleBrain } = await import('../../api/agents/_id/brain.js');++async function makeSourceBundle() {+ const rows = [+ {+ id: '11111111-1111-4111-8111-111111111111',+ agent_id: SOURCE_AGENT_ID,+ type: 'reference',+ content: 'Solana is the home chain.',+ tags: ['audit'],+ salience: 0.5,+ tier: 'recall',+ is_public: true,+ content_hash: null,+ signature: null,+ signer_address: null,+ signed_at: null,+ created_at: new Date('2026-02-02T00:00:00Z'),+ },+ {+ id: '22222222-2222-4222-8222-222222222222',+ agent_id: SOURCE_AGENT_ID,+ type: 'project',+ content: 'The promoted coin is $THREE.',+ tags: ['audit'],+ salience: 0.6,+ tier: 'recall',+ is_public: true,+ content_hash: null,+ signature: null,+ signer_address: null,+ signed_at: null,+ created_at: new Date('2026-02-02T00:01:00Z'),+ },+ ];+ return buildBundle({+ agent: { id: SOURCE_AGENT_ID, name: 'Source Agent', description: '', avatar_id: null },+ persona: null,+ memoryEntries: rows.map((r) => buildMemoryEntry(r)),+ anchor: null,+ exportedAt: '2026-02-03T00:00:00.000Z',+ signerPrivKey: null,+ });+}++async function importBundle(bundle, strategy = 'merge') {+ const req = makeReq({+ method: 'POST',+ url: `/api/agents/${AGENT_ID}/brain/import`,+ body: { bundle, strategy },+ });+ const res = makeRes();+ await handleBrain(req, res, AGENT_ID, 'import');+ return { res, json: res.body ? JSON.parse(res.body) : null };+}++beforeEach(() => {+ stored = [];+ sessionUser = { id: OWNER_ID };+ agentRow = {+ id: AGENT_ID,+ user_id: OWNER_ID,+ name: 'Target Agent',+ wallet_address: null,+ memory_storage_mode: 'local',+ persona_prompt_hash: null,+ meta: {},+ };+});++describe('brain import merge', () => {+ it('imports every memory the first time', async () => {+ const bundle = await makeSourceBundle();+ const { res, json } = await importBundle(bundle);+ expect(res.statusCode).toBe(200);+ expect(json.imported).toBe(2);+ expect(json.duplicates).toBe(0);+ expect(stored).toHaveLength(2);+ });++ it('is idempotent: re-importing the same bundle inserts nothing', async () => {+ const bundle = await makeSourceBundle();+ await importBundle(bundle);+ const second = await importBundle(bundle);+ expect(second.res.statusCode).toBe(200);+ expect(second.json.imported).toBe(0);+ expect(second.json.duplicates).toBe(2);+ expect(stored).toHaveLength(2);++ const third = await importBundle(bundle);+ expect(third.json.imported).toBe(0);+ expect(stored).toHaveLength(2);+ });++ it('records the matched digest in provenance so the next import can match it', async () => {+ const bundle = await makeSourceBundle();+ await importBundle(bundle);+ // Every row carries a source hash, and it is the bundle entry's hash, not+ // the local row digest that the re-sign writes.+ for (const row of stored) {+ expect(row.source_hash).toMatch(/^[a-f0-9]{64}$/);+ expect(row.source_hash).not.toBe(row.content_hash);+ }+ const bundleHashes = bundle.memories.map((m) => m.content_hash.toLowerCase()).sort();+ expect(stored.map((r) => r.source_hash).sort()).toEqual(bundleHashes);+ });++ it('rejects a bundle whose brain_hash does not match its memory set', async () => {+ // brain_hash content-addresses the memory hash list, so swapping a memory in+ // or out after export breaks it. Nothing may be written on a failed gate.+ const bundle = await makeSourceBundle();+ bundle.memories.pop();+ const { res, json } = await importBundle(bundle);+ expect(res.statusCode).toBe(422);+ expect(json.error).toBe('integrity_failed');+ expect(stored).toHaveLength(0);+ });++ it('rejects a bundle that fails its own schema before touching the database', async () => {+ // parse() throws a 400-tagged error that wrap() in api/agents/[id].js turns+ // into the {error: validation_error} 400 the endpoint serves. What matters+ // here is that the throw happens before any write.+ await expect(importBundle({ version: 'brain/1' })).rejects.toMatchObject({+ status: 400,+ code: 'validation_error',+ });+ expect(stored).toHaveLength(0);+ });+});diff --git a/tests/api/agents-memory-cid.test.js b/tests/api/agents-memory-cid.test.jsnew file mode 100644index 000000000..65eedd08d--- /dev/null+++ b/tests/api/agents-memory-cid.test.js@@ -0,0 +1,162 @@+// GET /api/agents/:id/memory/:cid: the pinned-memory IPFS read-through proxy.+//+// Two things this route has to get right, and one it used to get wrong.+//+// Right: the CID must be bound to THIS agent's own pin set. Owning the agent is+// not enough, or the route is a general-purpose authenticated IPFS fetch proxy+// for any CID anyone can name.+//+// Wrong, until the fix these tests lock in: when every public gateway refused,+// the helper threw. If a gateway had thrown first, the caller saw that network+// error as a bare 500; if all three merely answered with a non-ok status,+// nothing was ever assigned to `lastErr` and the code threw a synthesized error+// with no cause at all. Either way somebody else's gateway outage was reported+// as a three.ws internal error, and the ops alert that a 5xx raises fired on it.+// It is an upstream failure: 502.++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { makeReq, makeRes } from '../_helpers/monetization.js';++const AGENT_ID = '00000000-0000-4000-8000-0000000000c1';+const OWNER_ID = 'user-owner';+const CID = 'bafkreiauditprobecid';++let agentRow = null;+let pinRow = null;++const sqlMock = vi.fn((strings) => {+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);+ if (/from agent_identities/i.test(q)) return Promise.resolve(agentRow ? [agentRow] : []);+ if (/from agent_memory_pins/i.test(q)) return Promise.resolve(pinRow ? [pinRow] : []);+ return Promise.resolve([]);+});+vi.mock('../../api/_lib/db.js', () => ({+ sql: sqlMock,+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++let sessionUser = null;+vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => sessionUser),+ authenticateBearer: vi.fn(async () => null),+ extractBearer: vi.fn(() => null),+}));++vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: {+ authedReadIp: vi.fn(async () => ({ success: true, reset: Date.now() + 1000, limit: 60, remaining: 59 })),+ },+ clientIp: vi.fn(() => '127.0.0.1'),+}));++const { default: handler } = await import('../../api/agents/_id/memory/[cid].js');++function gatewayOk(bytes) {+ return {+ ok: true,+ status: 200,+ headers: { get: (k) => (k.toLowerCase() === 'content-length' ? String(bytes.length) : null) },+ arrayBuffer: async () => bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength),+ };+}+function gatewayStatus(status) {+ return { ok: false, status, headers: { get: () => null }, arrayBuffer: async () => new ArrayBuffer(0) };+}++async function get(cid = CID, id = AGENT_ID) {+ const req = makeReq({ method: 'GET', url: `/api/agents/${id}/memory/${cid}` });+ const res = makeRes();+ await handler(req, res);+ return res;+}++beforeEach(() => {+ sessionUser = { id: OWNER_ID };+ agentRow = { id: AGENT_ID };+ pinRow = { cid: CID };+ vi.restoreAllMocks();+});++describe('GET /api/agents/:id/memory/:cid', () => {+ it('streams the pinned file back from the first gateway that serves it', async () => {+ const payload = Buffer.from('encrypted-memory-bytes');+ globalThis.fetch = vi.fn(async () => gatewayOk(payload));+ const res = await get();+ expect(res.statusCode).toBe(200);+ expect(res.headers['content-type']).toBe('application/octet-stream');+ expect(globalThis.fetch).toHaveBeenCalledTimes(1);+ });++ it('walks to the next gateway when the first refuses', async () => {+ const payload = Buffer.from('encrypted-memory-bytes');+ let n = 0;+ globalThis.fetch = vi.fn(async () => (++n === 1 ? gatewayStatus(504) : gatewayOk(payload)));+ const res = await get();+ expect(res.statusCode).toBe(200);+ expect(globalThis.fetch).toHaveBeenCalledTimes(2);+ });++ it('502s (never 500) when every gateway answers with a non-ok status', async () => {+ globalThis.fetch = vi.fn(async () => gatewayStatus(404));+ const res = await get();+ expect(res.statusCode).toBe(502);+ expect(JSON.parse(res.body).error).toBe('upstream_error');+ });++ it('502s when every gateway is unreachable', async () => {+ globalThis.fetch = vi.fn(async () => {+ throw new Error('ECONNRESET');+ });+ const res = await get();+ expect(res.statusCode).toBe(502);+ expect(JSON.parse(res.body).error).toBe('upstream_error');+ });++ it('bounds each gateway attempt with a deadline so one hang cannot eat the request', async () => {+ const payload = Buffer.from('x');+ globalThis.fetch = vi.fn(async (_url, init) => {+ expect(init?.signal).toBeDefined();+ return gatewayOk(payload);+ });+ const res = await get();+ expect(res.statusCode).toBe(200);+ });++ it('refuses a CID this agent has not pinned, so the route is not a generic proxy', async () => {+ pinRow = null;+ globalThis.fetch = vi.fn();+ const res = await get();+ expect(res.statusCode).toBe(404);+ expect(globalThis.fetch).not.toHaveBeenCalled();+ });++ it('401s an anonymous caller', async () => {+ sessionUser = null;+ globalThis.fetch = vi.fn();+ const res = await get();+ expect(res.statusCode).toBe(401);+ expect(globalThis.fetch).not.toHaveBeenCalled();+ });++ it('404s when the caller does not own the agent', async () => {+ agentRow = null;+ globalThis.fetch = vi.fn();+ const res = await get();+ expect(res.statusCode).toBe(404);+ expect(globalThis.fetch).not.toHaveBeenCalled();+ });++ it('413s on an over-cap file even when the gateway understates its length', async () => {+ const huge = Buffer.alloc(512 * 1024 + 1, 1);+ globalThis.fetch = vi.fn(async () => ({+ ok: true,+ status: 200,+ headers: { get: () => '10' }, // a lying Content-Length+ arrayBuffer: async () => huge.buffer.slice(huge.byteOffset, huge.byteOffset + huge.byteLength),+ }));+ const res = await get();+ expect(res.statusCode).toBe(413);+ expect(JSON.parse(res.body).error).toBe('payload_too_large');+ });+});diff --git a/tests/api/agents-sub-resources.test.js b/tests/api/agents-sub-resources.test.jsnew file mode 100644index 000000000..240021acd--- /dev/null+++ b/tests/api/agents-sub-resources.test.js@@ -0,0 +1,289 @@+// Behavioural cover for api/agents/_id/_sub.js.+//+// That module is not a route: the underscore prefix makes it unreachable by the+// filesystem router on purpose, and every one of its handlers is reached only by+// the dispatcher in api/agents/[id].js. The tests that mentioned it before this+// file read its SOURCE TEXT (tests/agent-animation-slots.test.js,+// tests/agent-choreography-wiring.test.js) to assert that certain strings appear+// in it, which cannot catch a handler that returns the wrong status or leaks+// another user's data. This file runs the handlers.+//+// What it pins, per handler, is the main path plus the failure that matters:+//+// handleManifest public contract every embed and SDK reads. A malformed id+// is a 400 and a missing agent a 404, never a half-built+// manifest, because consumers cache what they get.+// handleEmbedPolicy GET is deliberately fail-open (a public embed booting on+// an agent with no policy must not log a 404 every load),+// while a write without a session is a 401.+// handleActions the signed action log is owner-only: a signed-in stranger+// gets 403, not somebody else's ledger.+// handleMemories anonymous GET answers an empty list rather than 401 (same+// embed-console reasoning), but writing still needs a user.+//+// DB, auth, CSRF, limiter, avatar resolution and R2 are mocked so the suite runs+// offline; the schema validation, the response shapes and the branching are real.++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { makeReq, makeRes } from '../_helpers/monetization.js';++const AGENT_ID = '00000000-0000-4000-8000-0000000000a1';+const OWNER_ID = 'user-owner';+const STRANGER_ID = 'user-stranger';++// Content-addressed SQL mock: classify by query text, so call order is free.+let agentRow = null;+let actionRows = [];+let memoryRows = [];+const calls = [];++const sqlMock = vi.fn((strings, ...values) => {+ const q = Array.isArray(strings) ? strings.join(' ') : String(strings);+ calls.push({ q, values });+ if (/from agent_identities/i.test(q)) return Promise.resolve(agentRow ? [agentRow] : []);+ if (/from agent_actions/i.test(q)) return Promise.resolve(actionRows);+ if (/from agent_memories/i.test(q)) return Promise.resolve(memoryRows);+ if (/from agent_activations/i.test(q)) return Promise.resolve([]);+ if (/update agent_identities/i.test(q)) return Promise.resolve([{ embed_policy: null }]);+ return Promise.resolve([]);+});+sqlMock.transaction = (queries) => Promise.all(queries);+vi.mock('../../api/_lib/db.js', () => ({+ sql: sqlMock,+ isDbUnavailableError: () => false,+ isDbCapacityError: () => false,+}));++let sessionUser = null;+vi.mock('../../api/_lib/auth.js', () => ({+ getSessionUser: vi.fn(async () => sessionUser),+ 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: {+ authIp: vi.fn(async () => ({ success: true, reset: Date.now() + 1000, limit: 60, remaining: 59 })),+ },+ clientIp: vi.fn(() => '127.0.0.1'),+}));++let storedPolicy = null;+vi.mock('../../api/_lib/embed-policy.js', () => ({+ readEmbedPolicy: vi.fn(async () => storedPolicy),+ validateEmbedPolicy: vi.fn((p) => p),+}));++vi.mock('../../api/_lib/avatars.js', () => ({+ resolveAvatarUrl: vi.fn(async () => ({ url: 'https://cdn.example/agent.glb' })),+}));++vi.mock('../../api/_lib/r2.js', () => ({ publicUrl: vi.fn((k) => `https://cdn.example/${k}`) }));++vi.mock('../../api/_lib/agent-wallet.js', () => ({ recoverAgentKey: vi.fn(async () => null) }));++const sub = await import('../../api/agents/_id/_sub.js');++function ownedAgent(overrides = {}) {+ return {+ id: AGENT_ID,+ user_id: OWNER_ID,+ name: 'Probe Agent',+ description: 'An agent used by the sub-resource tests.',+ wallet_address: null,+ avatar_id: null,+ avatar_db_id: null,+ storage_key: null,+ thumbnail_key: null,+ content_type: null,+ skills: ['chat'],+ meta: {},+ chain_id: null,+ erc8004_agent_id: null,+ erc8004_registry: null,+ registration_cid: null,+ created_at: new Date('2026-01-01T00:00:00Z'),+ voice_provider: null,+ voice_id: null,+ persona_prompt_hash: null,+ persona_tone_tags: null,+ persona_extracted_at: null,+ ...overrides,+ };+}++async function run(handler, { method = 'GET', url = '/', body = null, id = AGENT_ID, extra } = {}) {+ const req = makeReq({ method, url, body });+ const res = makeRes();+ await handler(req, res, id, extra);+ return { res, json: res.body ? JSON.parse(res.body) : null };+}++beforeEach(() => {+ sessionUser = null;+ agentRow = null;+ actionRows = [];+ memoryRows = [];+ storedPolicy = null;+ calls.length = 0;+});++describe('_sub.js handleManifest', () => {+ it('serves the public manifest for a live agent', async () => {+ agentRow = ownedAgent();+ const { res, json } = await run(sub.handleManifest, {+ url: `/api/agents/${AGENT_ID}/manifest`,+ });+ expect(res.statusCode).toBe(200);+ expect(json.spec).toBe('agent-manifest/0.1');+ expect(json.id).toBe(AGENT_ID);+ expect(json.name).toBe('Probe Agent');+ expect(json.skills).toEqual(['chat']);+ expect(json.homeUrl).toContain(`/agent/${AGENT_ID}`);+ // No voice row configured: the manifest still names a provider so an embed+ // always has something to fall back to.+ expect(json.voice.provider).toBe('browser');+ expect(json.registrations).toEqual([]);+ // Public document: cacheable and readable cross-origin.+ expect(res.headers['access-control-allow-origin']).toBe('*');+ expect(res.headers['cache-control']).toContain('max-age');+ });++ it('404s for an agent that does not exist rather than emitting a hollow manifest', async () => {+ agentRow = null;+ const { res, json } = await run(sub.handleManifest, {+ url: `/api/agents/${AGENT_ID}/manifest`,+ });+ expect(res.statusCode).toBe(404);+ expect(json.error).toBe('not_found');+ });++ it('400s on an id that is not a uuid, before touching the database', async () => {+ const { res, json } = await run(sub.handleManifest, {+ url: '/api/agents/not-a-uuid/manifest',+ id: 'not-a-uuid',+ });+ expect(res.statusCode).toBe(400);+ expect(json.error).toBe('invalid_request');+ expect(calls).toHaveLength(0);+ });+});++describe('_sub.js handleEmbedPolicy', () => {+ it('fails open on GET so a public embed boot never logs a 404', async () => {+ storedPolicy = null;+ const { res, json } = await run(sub.handleEmbedPolicy, {+ url: `/api/agents/${AGENT_ID}/embed-policy`,+ });+ expect(res.statusCode).toBe(200);+ expect(json.policy).toBeNull();+ });++ it('returns the stored policy when the agent has one', async () => {+ storedPolicy = { surfaces: ['web'], origins: ['https://example.com'] };+ const { res, json } = await run(sub.handleEmbedPolicy, {+ url: `/api/agents/${AGENT_ID}/embed-policy`,+ });+ expect(res.statusCode).toBe(200);+ expect(json.policy).toEqual(storedPolicy);+ });++ it('401s an unauthenticated write', async () => {+ sessionUser = null;+ const { res, json } = await run(sub.handleEmbedPolicy, {+ method: 'PUT',+ url: `/api/agents/${AGENT_ID}/embed-policy`,+ body: { surfaces: ['web'] },+ });+ expect(res.statusCode).toBe(401);+ expect(json.error).toBe('unauthorized');+ });++ it('403s a signed-in stranger writing another owner policy', async () => {+ sessionUser = { id: STRANGER_ID };+ agentRow = ownedAgent();+ const { res, json } = await run(sub.handleEmbedPolicy, {+ method: 'PUT',+ url: `/api/agents/${AGENT_ID}/embed-policy`,+ body: { surfaces: ['web'] },+ });+ expect(res.statusCode).toBe(403);+ expect(json.error).toBe('forbidden');+ });+});++describe('_sub.js handleActions', () => {+ it('returns the owner signed action log', async () => {+ sessionUser = { id: OWNER_ID };+ agentRow = { id: AGENT_ID, user_id: OWNER_ID, name: 'Probe Agent', wallet_address: null };+ actionRows = [+ {+ id: 7,+ type: 'trade',+ payload: { pair: 'SOL/USDC' },+ source_skill: 'trade',+ signature: null,+ signer_address: null,+ created_at: new Date('2026-02-02T00:00:00Z'),+ },+ ];+ const { res, json } = await run(sub.handleActions, {+ url: `/api/agents/${AGENT_ID}/actions`,+ });+ expect(res.statusCode).toBe(200);+ expect(json.actions).toHaveLength(1);+ expect(json.actions[0].id).toBe('7');+ expect(json.actions[0].sourceSkill).toBe('trade');+ // Unsigned rows report `verified: null`, never a bare `false` that would+ // read as "signature checked and rejected".+ expect(json.actions[0].verified).toBeNull();+ expect(json.nextCursor).toBeNull();+ });++ it('403s a signed-in stranger instead of serving another agent ledger', async () => {+ sessionUser = { id: STRANGER_ID };+ agentRow = { id: AGENT_ID, user_id: OWNER_ID, name: 'Probe Agent', wallet_address: null };+ const { res, json } = await run(sub.handleActions, {+ url: `/api/agents/${AGENT_ID}/actions`,+ });+ expect(res.statusCode).toBe(403);+ expect(json.error).toBe('forbidden');+ // The ledger query never ran.+ expect(calls.some((c) => /from agent_actions/i.test(c.q))).toBe(false);+ });+});++describe('_sub.js handleMemories', () => {+ it('answers an anonymous GET with an empty list, not a 401', async () => {+ sessionUser = null;+ const { res, json } = await run(sub.handleMemories, {+ url: `/api/agents/${AGENT_ID}/memories`,+ });+ expect(res.statusCode).toBe(200);+ expect(json.data).toEqual([]);+ });++ it('401s an anonymous write', async () => {+ sessionUser = null;+ const { res, json } = await run(sub.handleMemories, {+ method: 'POST',+ url: `/api/agents/${AGENT_ID}/memories`,+ body: { type: 'reference', content: 'remember this' },+ });+ expect(res.statusCode).toBe(401);+ expect(json.error).toBe('unauthorized');+ });++ it('requires a memory id to delete', async () => {+ sessionUser = { id: OWNER_ID };+ agentRow = { id: AGENT_ID };+ const { res, json } = await run(sub.handleMemories, {+ method: 'DELETE',+ url: `/api/agents/${AGENT_ID}/memories`,+ });+ expect(res.statusCode).toBe(400);+ expect(json.error).toBe('bad_request');+ });+});