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.

feat(x402): serve any public agent as a paid endpoint at /api/x402/agents/:id

nirholasbca757e2aeb8
diff --git a/api/agents/[id]/api-service.js b/api/agents/[id]/api-service.js
new file mode 100644
index 000000000..707f97486
--- /dev/null
+++ b/api/agents/[id]/api-service.js
@@ -0,0 +1,112 @@
+// GET|PUT /api/agents/:id/api-service
+//
+// Owner switch for selling a whole agent as a paid x402 API (the Earn tab's
+// "Sell this agent as an API" card). GET returns the stored config, the stable
+// endpoint URL, where the money settles, whether the agent can be sold (and if
+// not, why, in plain sentences), and the service's earnings from
+// agent_revenue_events. PUT validates and stores { active, price_usd,
+// description } on meta.api_service. Activation is refused, with the reason,
+// when the agent is private, has no brain, or has no Solana payout address.
+
+import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
+import { cors, error, json, readJson, respondError, wrap } from '../../_lib/http.js';
+import { requireCsrf } from '../../_lib/csrf.js';
+import { isUuid } from '../../_lib/validate.js';
+import { getFeeBps } from '../../_lib/fee.js';
+import {
+ AgentServiceError,
+ CALL_INPUT_SCHEMA,
+ DESCRIPTION_MAX,
+ MAX_PRICE_USD,
+ MIN_PRICE_USD,
+ agentApiEarnings,
+ agentServiceUrl,
+ loadServiceAgent,
+ readServiceConfig,
+ resolveServicePayTo,
+ saveServiceConfig,
+ sellability,
+ validateServiceConfig,
+} from '../../_lib/agent-api-service.js';
+
+async function resolveAuth(req) {
+ const session = await getSessionUser(req);
+ if (session) return { userId: session.id };
+ const bearer = await authenticateBearer(extractBearer(req));
+ if (bearer) return { userId: bearer.userId };
+ return null;
+}
+
+async function snapshot(agent) {
+ const [payTo, earnings] = await Promise.all([
+ resolveServicePayTo(agent.id),
+ agentApiEarnings(agent.id),
+ ]);
+ return {
+ service: readServiceConfig(agent),
+ endpoint_url: agentServiceUrl(agent.id),
+ pay_to: payTo,
+ sellable: sellability(agent, { solanaPayTo: payTo.solana }),
+ limits: {
+ min_price_usd: MIN_PRICE_USD,
+ max_price_usd: MAX_PRICE_USD,
+ description_max: DESCRIPTION_MAX,
+ fee_bps: getFeeBps(),
+ },
+ input_schema: CALL_INPUT_SCHEMA,
+ earnings,
+ };
+}
+
+export default wrap(async (req, res) => {
+ if (cors(req, res, { methods: 'GET,PUT,OPTIONS', credentials: true })) return;
+ if (req.method !== 'GET' && req.method !== 'PUT') {
+ res.setHeader('allow', 'GET,PUT,OPTIONS');
+ return error(res, 405, 'method_not_allowed', 'use GET or PUT');
+ }
+
+ const url = new URL(req.url, 'http://x');
+ const id = req.query?.id || url.searchParams.get('id') || url.pathname.split('/').filter(Boolean)[2];
+
+ const auth = await resolveAuth(req);
+ if (!auth) return error(res, 401, 'unauthorized', 'sign in required');
+ if (!isUuid(id)) return error(res, 404, 'not_found', 'agent not found');
+ if (req.method === 'PUT' && !(await requireCsrf(req, res, auth.userId))) return;
+
+ let agent;
+ try {
+ agent = await loadServiceAgent(id);
+ } catch (err) {
+ return respondError(res, 502, 'agent_lookup_failed', err);
+ }
+ // A non-owner learns nothing about whether the agent exists.
+ if (!agent || String(agent.user_id) !== String(auth.userId)) {
+ return error(res, 404, 'not_found', 'agent not found');
+ }
+
+ if (req.method === 'GET') {
+ return json(res, 200, await snapshot(agent), { 'cache-control': 'private, no-store' });
+ }
+
+ let next;
+ try {
+ next = validateServiceConfig(await readJson(req, 8 * 1024));
+ } catch (err) {
+ if (err instanceof AgentServiceError) return error(res, err.status, err.code, err.message);
+ if (err?.status) return error(res, err.status, 'invalid_body', err.message);
+ throw err;
+ }
+
+ if (next.active) {
+ const payTo = await resolveServicePayTo(agent.id);
+ const sell = sellability(agent, { solanaPayTo: payTo.solana });
+ if (!sell.ok) {
+ return error(res, 409, 'not_sellable', sell.reasons[0], { reasons: sell.reasons });
+ }
+ }
+
+ const saved = await saveServiceConfig(agent.id, next);
+ if (!saved) return error(res, 404, 'not_found', 'agent not found');
+ const fresh = await loadServiceAgent(agent.id);
+ return json(res, 200, await snapshot(fresh || agent), { 'cache-control': 'private, no-store' });
+});
diff --git a/api/x402/agents.js b/api/x402/agents.js
new file mode 100644
index 000000000..606783a2d
--- /dev/null
+++ b/api/x402/agents.js
@@ -0,0 +1,185 @@
+// A whole agent, sold as a paid x402 API.
+//
+// POST /api/x402/agents/<agentId> { "message": "...", "history": [] }
+// -> 402 with the price the owner set, payTo = the agent's own Solana
+// payout wallet (USDC on Solana first); pay and retry with the
+// payment header -> { "reply", "model", "usage", "agent_id" }
+// GET /api/x402/agents free JSON list of every agent on sale
+//
+// The owner turns this on from the agent wallet's Earn tab (stored as
+// meta.api_service, validated by PUT /api/agents/:id/api-service). The agent id
+// arrives as ?agent=<id> through the vercel.json rewrite. Only public agents
+// whose embed policy leaves them a brain and that have a Solana payout address
+// can be sold; everything else 404s before any challenge is issued.
+//
+// Default paidEndpoint mode runs the turn BEFORE settlement, so a turn that
+// fails (every LLM provider down, a provider error) answers 502/503 and the
+// buyer is never charged. The body is parsed and bounded before the payment is
+// verified, so a malformed call never reaches the facilitator either.
+
+import { cors, error, json, readBody, respondError } from '../_lib/http.js';
+import { paidEndpoint } from '../_lib/x402-paid-endpoint.js';
+import { buildBazaarSchema, NETWORK_SOLANA_MAINNET } from '../_lib/x402-spec.js';
+import { withService } from '../_lib/x402/bazaar-helpers.js';
+import { isUuid } from '../_lib/validate.js';
+import { runAgentTurn } from '../_lib/agent-turn.js';
+import {
+ AgentServiceError,
+ BODY_MAX_BYTES,
+ CALL_INPUT_EXAMPLE,
+ CALL_INPUT_SCHEMA,
+ CALL_OUTPUT_EXAMPLE,
+ CALL_OUTPUT_SCHEMA,
+ agentServiceUrl,
+ listActiveAgentServices,
+ loadServiceAgent,
+ parseCallBody,
+ readServiceConfig,
+ recordAgentApiSale,
+ resolveServicePayTo,
+ sellability,
+ serviceNameFor,
+ usdToAtomics,
+} from '../_lib/agent-api-service.js';
+
+const EVM_ADDRESS = /^0x[0-9a-fA-F]{40}$/;
+
+const BAZAAR = {
+ discoverable: true,
+ info: {
+ input: { type: 'http', method: 'POST', bodyType: 'json', body: CALL_INPUT_EXAMPLE },
+ output: { type: 'json', example: CALL_OUTPUT_EXAMPLE },
+ },
+ schema: buildBazaarSchema({
+ method: 'POST',
+ bodyType: 'json',
+ bodySchema: CALL_INPUT_SCHEMA,
+ outputSchema: CALL_OUTPUT_SCHEMA,
+ }),
+};
+
+function agentRefFromReq(req) {
+ const fromQuery = req.query?.agent;
+ if (fromQuery) return String(Array.isArray(fromQuery) ? fromQuery[0] : fromQuery);
+ const url = new URL(req.url, 'http://x');
+ const q = url.searchParams.get('agent');
+ if (q) return q;
+ const m = url.pathname.match(/\/api\/x402\/agents\/([^/?]+)/);
+ return m ? decodeURIComponent(m[1]) : null;
+}
+
+async function listServices(req, res) {
+ if (req.method !== 'GET' && req.method !== 'HEAD') {
+ res.setHeader('allow', 'GET,HEAD,OPTIONS');
+ return error(res, 405, 'method_not_allowed', 'GET lists agents on sale; POST to /api/x402/agents/<agentId> to call one');
+ }
+ let services;
+ try {
+ services = await listActiveAgentServices({ limit: 200 });
+ } catch (err) {
+ return respondError(res, 502, 'catalog_unavailable', err);
+ }
+ return json(
+ res,
+ 200,
+ {
+ count: services.length,
+ input_schema: CALL_INPUT_SCHEMA,
+ output_schema: CALL_OUTPUT_SCHEMA,
+ services,
+ },
+ { 'cache-control': 'public, max-age=60, stale-while-revalidate=300' },
+ );
+}
+
+export default async function handler(req, res) {
+ // paidEndpoint answers CORS itself, but the not-found / inactive branches
+ // below respond before one is built, and a payment header always triggers a
+ // preflight, so answer it here too.
+ if (cors(req, res, { methods: 'GET,POST,OPTIONS', origins: '*' })) return;
+
+ const ref = agentRefFromReq(req);
+ if (!ref) return listServices(req, res);
+ if (!isUuid(ref)) return error(res, 404, 'agent_not_found', 'no agent with that id');
+
+ let agent;
+ let payTo;
+ try {
+ agent = await loadServiceAgent(ref);
+ payTo = agent ? await resolveServicePayTo(agent.id) : null;
+ } catch (err) {
+ return respondError(res, 502, 'agent_lookup_failed', err);
+ }
+ if (!agent) return error(res, 404, 'agent_not_found', 'no agent with that id');
+
+ const config = readServiceConfig(agent);
+ if (!config.active || !config.price_usd) {
+ return error(res, 404, 'service_inactive', 'this agent is not sold as an API; its owner can turn it on from the Earn tab');
+ }
+ const sell = sellability(agent, { solanaPayTo: payTo.solana });
+ if (!sell.ok) {
+ return error(res, 404, 'service_unavailable', sell.reasons[0], { reasons: sell.reasons });
+ }
+
+ // Bound and validate the body before the payment is ever verified, and only
+ // when a payment is attached: an unpaid probe gets the 402 challenge (which
+ // carries the input schema) whatever it sent.
+ const paymentPresent = Boolean(req.headers['x-payment'] || req.headers['payment-signature']);
+ let call = null;
+ if (paymentPresent && req.method === 'POST') {
+ try {
+ call = parseCallBody(await readBody(req, BODY_MAX_BYTES + 1));
+ } catch (err) {
+ if (err instanceof AgentServiceError) return error(res, err.status, err.code, err.message);
+ if (err?.status === 413) return error(res, 413, 'payload_too_large', `body must be at most ${BODY_MAX_BYTES} bytes`);
+ throw err;
+ }
+ // Hand the parsed body back to anything downstream that reads it again
+ // (readJson / readBody reconstruct from req.body once the stream is drained).
+ req.body = call;
+ }
+
+ const override = { solana: payTo.solana };
+ const networks = ['solana'];
+ if (payTo.base && EVM_ADDRESS.test(payTo.base)) {
+ override.base = payTo.base;
+ networks.push('base');
+ }
+
+ const priceAtomics = usdToAtomics(config.price_usd);
+ const route = `/api/x402/agents/${agent.id}`;
+ const inner = paidEndpoint({
+ route,
+ method: 'POST',
+ priceAtomics,
+ networks,
+ payTo: override,
+ // The $THREE accept is a fixed env amount; an owner-set price varies per
+ // agent, so a token accept would sell every agent at one flat price.
+ acceptThree: false,
+ description: `${config.description} (one turn with ${agent.name} on three.ws)`.slice(0, 500),
+ mimeType: 'application/json',
+ bazaar: BAZAAR,
+ service: withService({
+ serviceName: serviceNameFor(agent),
+ tags: ['agent', 'chat', 'pay-per-call', 'solana'],
+ }),
+ resourceUrlBuilder: () => agentServiceUrl(agent.id),
+ // Revenue lands on the agent's own ledger, net of PLATFORM_FEE_BPS, once
+ // the buyer's payment has settled. Fire-and-forget by contract.
+ onSettled: ({ payer, network, txHash, amountAtomics, asset }) =>
+ recordAgentApiSale({ agent, payer, network, txHash, amountAtomics: amountAtomics ?? priceAtomics, asset }),
+ async handler({ payer, requirement }) {
+ const turn = await runAgentTurn({
+ agent,
+ message: call.message,
+ history: call.history,
+ // Patronage keys on a Solana wallet; a Base payer has none here.
+ callerWallet: requirement?.network === NETWORK_SOLANA_MAINNET ? payer || null : null,
+ tool: 'agent.api',
+ });
+ return { reply: turn.text, model: turn.model, usage: turn.usage, agent_id: agent.id };
+ },
+ });
+ return inner(req, res);
+}
diff --git a/tests/_helpers/pglite-sql.js b/tests/_helpers/pglite-sql.js
new file mode 100644
index 000000000..014f86f19
--- /dev/null
+++ b/tests/_helpers/pglite-sql.js
@@ -0,0 +1,55 @@
+// An in-process Postgres (PGlite) behind the same tagged-template `sql` shape
+// api/_lib/db.js exports, for tests that must exercise real SQL semantics:
+// check constraints, partial unique indexes, ON CONFLICT inference, jsonb
+// operators. Mock api/_lib/db.js with `{ ...actual, sql: db.sql }` and create
+// only the tables the code under test touches.
+//
+// Like the production wrapper, a query is lazy (it runs when awaited) and an
+// interpolated sql`...` fragment is inlined with its placeholders renumbered,
+// so modules that build column lists or WHERE clauses as fragments work here.
+
+import { PGlite } from '@electric-sql/pglite';
+
+const FRAGMENT = Symbol('pglite-sql-fragment');
+
+function compile(fragment, params) {
+ let text = '';
+ fragment.strings.forEach((part, i) => {
+ text += part;
+ if (i >= fragment.values.length) return;
+ const v = fragment.values[i];
+ if (v && v[FRAGMENT]) {
+ text += compile(v, params);
+ } else {
+ params.push(v instanceof Date ? v.toISOString() : v);
+ text += `$${params.length}`;
+ }
+ });
+ return text;
+}
+
+export function createPgliteSql() {
+ const state = { pg: new PGlite(), calls: [] };
+ const run = async (fragment) => {
+ const params = [];
+ const text = compile(fragment, params);
+ state.calls.push(text);
+ const out = await state.pg.query(text, params);
+ return out.rows;
+ };
+ const sql = (strings, ...values) => {
+ const fragment = { [FRAGMENT]: true, strings, values };
+ let promise = null;
+ const settle = () => (promise ??= run(fragment));
+ fragment.then = (onOk, onErr) => settle().then(onOk, onErr);
+ fragment.catch = (onErr) => settle().catch(onErr);
+ fragment.finally = (fn) => settle().finally(fn);
+ return fragment;
+ };
+ return {
+ sql,
+ exec: (ddl) => state.pg.exec(ddl),
+ query: (text, params) => state.pg.query(text, params).then((r) => r.rows),
+ calls: state.calls,
+ };
+}
diff --git a/tests/api/x402-agent-api.test.js b/tests/api/x402-agent-api.test.js
new file mode 100644
index 000000000..7e8ae8d44
--- /dev/null
+++ b/tests/api/x402-agent-api.test.js
@@ -0,0 +1,440 @@
+// Sell a whole agent as a paid x402 API: POST /api/x402/agents/:id.
+//
+// Drives the real route (api/x402/agents.js) through the real paidEndpoint()
+// wrapper against an in-process Postgres (PGlite) holding the tables it reads
+// and writes, so the revenue insert, its ON CONFLICT against the partial unique
+// index, and the spent-payment guard all run as real SQL. The only mocked seams
+// are the facilitator (verifyPayment / settlePayment), the LLM chain, and the
+// notification + audit sinks.
+
+import { Readable } from 'node:stream';
+import { Keypair } from '@solana/web3.js';
+import { beforeAll, beforeEach, afterAll, describe, it, expect, vi } from 'vitest';
+
+const holder = vi.hoisted(() => ({ db: null }));
+
+vi.mock('../../api/_lib/db.js', async (importActual) => {
+ const actual = await importActual();
+ return { ...actual, sql: (...args) => holder.db.sql(...args) };
+});
+
+const verifyPayment = vi.fn();
+const settlePayment = vi.fn();
+vi.mock('../../api/_lib/x402-spec.js', async (importActual) => {
+ const actual = await importActual();
+ return { ...actual, verifyPayment, settlePayment };
+});
+
+const llmComplete = vi.fn();
+vi.mock('../../api/_lib/llm.js', async (importActual) => {
+ const actual = await importActual();
+ return { ...actual, llmComplete };
+});
+
+const notifications = [];
+vi.mock('../../api/_lib/notify.js', () => ({
+ insertNotification: (userId, type, payload) => notifications.push({ userId, type, payload }),
+}));
+vi.mock('../../api/_lib/x402/audit-log.js', async (importActual) => ({
+ ...(await importActual()),
+ logPaymentEvent: () => {},
+}));
+vi.mock('../../api/_lib/patronage.js', () => ({
+ patronStanding: async () => ({ usd: 0 }),
+ listPerks: async () => [],
+ entitledPerks: () => [],
+ patronChatContext: async () => null,
+}));
+vi.mock('@coinbase/x402', () => ({ createCdpAuthHeaders: vi.fn(async () => ({})) }));
+const authState = vi.hoisted(() => ({ session: null }));
+vi.mock('../../api/_lib/auth.js', () => ({
+ getSessionUser: async () => authState.session,
+ authenticateBearer: async () => null,
+ extractBearer: () => null,
+}));
+vi.mock('../../api/_lib/csrf.js', () => ({ requireCsrf: async () => true }));
+
+const SOLANA = 'solana:5eykt4UsFv8P8NJdTREpY1vzqKqZKvdp';
+const USDC = 'EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v';
+const OWNER = '11111111-1111-4111-8111-111111111111';
+const AGENT = '22222222-2222-4222-8222-222222222222';
+const AGENT_WALLET = Keypair.generate().publicKey.toBase58();
+const PAYOUT_WALLET = Keypair.generate().publicKey.toBase58();
+const BUYER = Keypair.generate().publicKey.toBase58();
+const FEE_PAYER = Keypair.generate().publicKey.toBase58();
+
+const DDL = `
+ create table agent_identities (
+ id uuid primary key, user_id uuid, name text, description text, meta jsonb,
+ skills text[], embed_policy jsonb, is_public boolean, deleted_at timestamptz,
+ avatar_url text, profile_image_url text, wallet_address text,
+ updated_at timestamptz default now()
+ );
+ create table agent_payout_wallets (
+ id serial primary key, agent_id uuid, user_id uuid, chain text, address text,
+ is_default boolean default false, created_at timestamptz default now()
+ );
+ create table agent_skill_prices (agent_id uuid, skill text, is_active boolean);
+ create table agent_revenue_events (
+ id uuid primary key default gen_random_uuid(), agent_id uuid, intent_id text, skill text,
+ gross_amount bigint, fee_amount bigint, net_amount bigint, currency_mint text, chain text,
+ payer_address text, created_at timestamptz default now(),
+ platform_fee_amount bigint not null default 0, owner_user_id uuid,
+ settled_to_wallet boolean not null default false,
+ check (gross_amount = fee_amount + net_amount + platform_fee_amount)
+ );
+ create unique index agent_revenue_events_intent_uniq on agent_revenue_events (intent_id) where intent_id is not null;
+ create table x402_spent_payments (
+ payment_hash text primary key, endpoint text, amount_atomics text, created_at timestamptz default now()
+ );
+`;
+
+function mockReqRes({ method = 'POST', headers = {}, url = `/api/x402/agents/${AGENT}`, body } = {}) {
+ const lower = {};
+ for (const [k, v] of Object.entries(headers)) lower[k.toLowerCase()] = v;
+ const req = Object.assign(new Readable({ read() {} }), {
+ method,
+ url,
+ headers: lower,
+ query: {},
+ connection: { remoteAddress: '127.0.0.1' },
+ socket: { remoteAddress: '127.0.0.1' },
+ });
+ if (body !== undefined) req.push(Buffer.from(typeof body === 'string' ? body : JSON.stringify(body)));
+ req.push(null);
+ const chunks = [];
+ const resHeaders = {};
+ const res = {
+ statusCode: 200,
+ writableEnded: false,
+ headersSent: false,
+ setHeader(k, v) {
+ resHeaders[k.toLowerCase()] = v;
+ },
+ getHeader(k) {
+ return resHeaders[k.toLowerCase()];
+ },
+ end(b) {
+ if (b !== undefined) chunks.push(b);
+ res.writableEnded = true;
+ },
+ write(c) {
+ chunks.push(c);
+ },
+ get body() {
+ return chunks.join('');
+ },
+ };
+ return { req, res };
+}
+
+function paymentHeader(salt) {
+ return Buffer.from(
+ JSON.stringify({ x402Version: 2, scheme: 'exact', network: SOLANA, payload: { transaction: `tx-${salt}` } }),
+ ).toString('base64');
+}
+
+function challengeOf(res) {
+ return JSON.parse(Buffer.from(String(res.getHeader('payment-required')), 'base64').toString('utf8'));
+}
+
+async function seedAgent({ service, isPublic = true, embedPolicy = null, payout = true, solanaAddress = AGENT_WALLET } = {}) {
+ await holder.db.query(
+ `insert into agent_identities (id, user_id, name, description, meta, skills, embed_policy, is_public, wallet_address)
+ values ($1, $2, 'Oracle Ada', 'A research agent', $3, '{}', $4, $5, '0x49da9e65CfA25B13732A46ddB2D2cEEADa14F65e')`,
+ [
+ AGENT,
+ OWNER,
+ JSON.stringify({
+ solana_address: solanaAddress,
+ brain: { instructions: 'You are Ada.' },
+ ...(service ? { api_service: service } : {}),
+ }),
+ embedPolicy ? JSON.stringify(embedPolicy) : null,
+ isPublic,
+ ],
+ );
+ if (payout) {
+ await holder.db.query(
+ `insert into agent_payout_wallets (agent_id, user_id, chain, address, is_default) values ($1, $2, 'solana', $3, true)`,
+ [AGENT, OWNER, PAYOUT_WALLET],
+ );
+ }
+}
+
+const ACTIVE = { active: true, price_usd: 0.25, description: 'Ask Ada anything about on-chain research.' };
+
+let handler;
+let ownerHandler;
+let cacheMod;
+const ORIG_ENV = { ...process.env };
+
+beforeAll(async () => {
+ const { createPgliteSql } = await import('../_helpers/pglite-sql.js');
+ holder.db = createPgliteSql();
+ await holder.db.exec(DDL);
+ process.env.X402_ALLOW_MEMORY_FALLBACK = '1';
+ handler = (await import('../../api/x402/agents.js')).default;
+ ownerHandler = (await import('../../api/agents/[id]/api-service.js')).default;
+ cacheMod = await import('../../api/_lib/x402/idempotency-cache.js');
+});
+
+beforeEach(async () => {
+ await holder.db.exec(
+ 'truncate agent_identities, agent_payout_wallets, agent_skill_prices, agent_revenue_events, x402_spent_payments',
+ );
+ process.env.X402_ASSET_MINT_SOLANA = USDC;
+ process.env.X402_FEE_PAYER_SOLANA = FEE_PAYER;
+ delete process.env.X402_PAY_TO_BASE;
+ delete process.env.X402_ACCEPT_THREE_SOLANA;
+ delete process.env.X402_BUILDER_CODE_APP;
+ cacheMod._resetMemoryStore();
+ notifications.length = 0;
+ authState.session = null;
+ verifyPayment.mockReset();
+ settlePayment.mockReset();
+ llmComplete.mockReset();
+ verifyPayment.mockImplementation(async ({ requirements }) => ({
+ paymentPayload: {},
+ requirement: requirements[0],
+ payer: BUYER,
+ }));
+ settlePayment.mockImplementation(async () => ({
+ success: true,
+ transaction: 'SettleSig111111111111111111111111111111111111',
+ network: SOLANA,
+ payer: BUYER,
+ }));
+ llmComplete.mockImplementation(async () => ({
+ text: 'Hello from Ada.',
+ model: 'claude-haiku-4-5-20251001',
+ usage: { input_tokens: 12, output_tokens: 4 },
+ }));
+});
+
+afterAll(() => {
+ for (const k of Object.keys(process.env)) if (!(k in ORIG_ENV)) delete process.env[k];
+ Object.assign(process.env, ORIG_ENV);
+});
+
+// onSettled is fire-and-forget; let its insert land before asserting on it.
+async function flushHooks() {
+ for (let i = 0; i < 20; i++) await new Promise((r) => setImmediate(r));
+}
+
+describe('POST /api/x402/agents/:id without payment', () => {
+ it('answers 402 with Solana USDC first, the agent payout wallet as payTo, and the configured price', async () => {
+ await seedAgent({ service: ACTIVE });
+ const { req, res } = mockReqRes({ body: 'message=hi', headers: { 'content-type': 'application/x-www-form-urlencoded' } });
+ await handler(req, res);
+ expect(res.statusCode).toBe(402);
+ const challenge = challengeOf(res);
+ expect(challenge.accepts[0].network.startsWith('solana:')).toBe(true);
+ expect(challenge.accepts[0].asset).toBe(USDC);
+ expect(challenge.accepts[0].payTo).toBe(PAYOUT_WALLET);
+ expect(challenge.accepts[0].amount).toBe('250000');
+ // No $THREE accept on a per-agent price, no Base leg without a Base payout.
+ expect(challenge.accepts.every((a) => a.asset === USDC)).toBe(true);
+ expect(llmComplete).not.toHaveBeenCalled();
+ });
+
+ it("falls back to the agent's own Solana wallet, never its EVM wallet_address", async () => {
+ await seedAgent({ service: ACTIVE, payout: false });
+ const { req, res } = mockReqRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(402);
+ expect(challengeOf(res).accepts[0].payTo).toBe(AGENT_WALLET);
+ });
+
+ it('404s an agent that is not on sale, private, brainless, or has no Solana wallet', async () => {
+ const cases = [
+ { service: { ...ACTIVE, active: false }, code: 'service_inactive' },
+ { service: ACTIVE, isPublic: false, code: 'service_unavailable' },
+ { service: ACTIVE, embedPolicy: { brain: { mode: 'none' } }, code: 'service_unavailable' },
+ { service: ACTIVE, payout: false, solanaAddress: null, code: 'service_unavailable' },
+ ];
+ for (const c of cases) {
+ await holder.db.exec('truncate agent_identities, agent_payout_wallets');
+ await seedAgent(c);
+ const { req, res } = mockReqRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(404);
+ expect(JSON.parse(res.body).error).toBe(c.code);
+ }
+ });
+});
+
+describe('POST /api/x402/agents/:id with payment', () => {
+ it('runs one turn, settles, returns { reply, model, usage } and records revenue net of the platform fee', async () => {
+ await seedAgent({ service: ACTIVE });
+ const { req, res } = mockReqRes({
+ headers: { 'content-type': 'application/json', 'x-payment': paymentHeader('ok') },
+ body: { message: 'hi', history: [{ role: 'user', content: 'earlier' }, { role: 'assistant', content: 'noted' }] },
+ });
+ await handler(req, res);
+ expect(res.statusCode).toBe(200);
+ const out = JSON.parse(res.body);
+ expect(out).toMatchObject({ reply: 'Hello from Ada.', model: 'claude-haiku-4-5-20251001', agent_id: AGENT });
+ expect(out.usage).toEqual({ input_tokens: 12, output_tokens: 4 });
+ expect(settlePayment).toHaveBeenCalledTimes(1);
+ // The turn saw the persona and the folded history.
+ const call = llmComplete.mock.calls[0][0];
+ expect(call.system).toContain('You are Ada.');
+ expect(call.user).toContain('User: earlier');
+ expect(call.user).toContain('Assistant: noted');
+ expect(call.track).toMatchObject({ agentId: AGENT, tool: 'agent.api' });
+
+ await flushHooks();
+ const rows = await holder.db.query('select * from agent_revenue_events');
+ expect(rows).toHaveLength(1);
+ const fee = Math.floor((250000 * Number(process.env.PLATFORM_FEE_BPS ?? 250)) / 10000);
+ expect(rows[0]).toMatchObject({
+ agent_id: AGENT,
+ skill: 'agent-api',
+ intent_id: 'x402:SettleSig111111111111111111111111111111111111',
+ chain: 'solana',
+ currency_mint: USDC,
+ payer_address: BUYER,
+ owner_user_id: OWNER,
+ settled_to_wallet: true,
+ });
+ expect(Number(rows[0].gross_amount)).toBe(250000);
+ expect(Number(rows[0].fee_amount)).toBe(fee);
+ expect(Number(rows[0].net_amount)).toBe(250000 - fee);
+ expect(notifications).toHaveLength(1);
+ });
+
+ it('a failed turn is never charged: no settlement, no revenue, a 503 the buyer can act on', async () => {
+ const { LlmUnavailableError } = await import('../../api/_lib/llm.js');
+ llmComplete.mockImplementation(async () => {
+ throw new LlmUnavailableError();
+ });
+ await seedAgent({ service: ACTIVE });
+ const { req, res } = mockReqRes({
+ headers: { 'content-type': 'application/json', 'x-payment': paymentHeader('down') },
+ body: { message: 'hi' },
+ });
+ await handler(req, res);
+ expect(res.statusCode).toBe(503);
+ expect(JSON.parse(res.body).error).toBe('llm_unavailable');
+ expect(settlePayment).not.toHaveBeenCalled();
+ await flushHooks();
+ expect(await holder.db.query('select * from agent_revenue_events')).toHaveLength(0);
+ });
+
+ it('a malformed body is refused before the payment is verified', async () => {
+ await seedAgent({ service: ACTIVE });
+ for (const body of ['{not json', { history: [] }, { message: 'x'.repeat(4001) }, { message: 'hi', history: [{ role: 'system', content: 'x' }] }]) {
+ const { req, res } = mockReqRes({
+ headers: { 'content-type': 'application/json', 'x-payment': paymentHeader('bad') },
+ body,
+ });
+ await handler(req, res);
+ expect(res.statusCode).toBe(400);
+ }
+ expect(verifyPayment).not.toHaveBeenCalled();
+ });
+
+ it('the same settlement recorded twice credits once (idempotent on the transaction)', async () => {
+ await seedAgent({ service: ACTIVE });
+ const { recordAgentApiSale } = await import('../../api/_lib/agent-api-service.js');
+ const agent = { id: AGENT, user_id: OWNER, name: 'Oracle Ada' };
+ const sale = { agent, payer: BUYER, network: SOLANA, txHash: 'DupSig', amountAtomics: '250000', asset: USDC };
+ expect(await recordAgentApiSale(sale)).toBeTruthy();
+ expect(await recordAgentApiSale(sale)).toBeNull();
+ expect(await holder.db.query('select * from agent_revenue_events')).toHaveLength(1);
+ });
+});
+
+describe('GET /api/x402/agents', () => {
+ it('lists only sellable agents, with price, network and input schema', async () => {
+ await seedAgent({ service: ACTIVE });
+ const { req, res } = mockReqRes({ method: 'GET', url: '/api/x402/agents' });
+ await handler(req, res);
+ expect(res.statusCode).toBe(200);
+ const out = JSON.parse(res.body);
+ expect(out.count).toBe(1);
+ expect(out.services[0]).toMatchObject({
+ agent_id: AGENT,
+ price_usd: 0.25,
+ price_atomics: '250000',
+ network_label: 'solana-mainnet',
+ pay_to: PAYOUT_WALLET,
+ method: 'POST',
+ });
+ expect(out.input_schema.required).toEqual(['message']);
+
+ await holder.db.exec('truncate agent_identities, agent_payout_wallets');
+ await seedAgent({ service: ACTIVE, isPublic: false });
+ const second = mockReqRes({ method: 'GET', url: '/api/x402/agents' });
+ await handler(second.req, second.res);
+ expect(JSON.parse(second.res.body).count).toBe(0);
+ });
+});
+
+describe('GET|PUT /api/agents/:id/api-service (owner switch)', () => {
+ async function owner(method, body) {
+ const { req, res } = mockReqRes({
+ method,
+ url: `/api/agents/${AGENT}/api-service?id=${AGENT}`,
+ headers: body ? { 'content-type': 'application/json' } : {},
+ body,
+ });
+ req.query = { id: AGENT };
+ await ownerHandler(req, res);
+ return { status: res.statusCode, body: JSON.parse(res.body) };
+ }
+
+ it('hides the agent from anyone but its owner', async () => {
+ await seedAgent({});
+ expect((await owner('GET')).status).toBe(401);
+ authState.session = { id: '33333333-3333-4333-8333-333333333333' };
+ expect((await owner('GET')).status).toBe(404);
+ });
+
+ it('returns the endpoint, payout, sellability and zeroed earnings for a fresh agent', async () => {
+ await seedAgent({});
+ authState.session = { id: OWNER };
+ const { status, body } = await owner('GET');
+ expect(status).toBe(200);
+ expect(body.service.active).toBe(false);
+ expect(body.endpoint_url).toMatch(new RegExp(`/api/x402/agents/${AGENT}$`));
+ expect(body.pay_to.solana).toBe(PAYOUT_WALLET);
+ expect(body.sellable).toEqual({ ok: true, reasons: [] });
+ expect(body.earnings.calls).toBe(0);
+ expect(body.limits.min_price_usd).toBeGreaterThan(0);
+ });
+
+ it('validates the price and description server-side', async () => {
+ await seedAgent({});
+ authState.session = { id: OWNER };
+ expect((await owner('PUT', { active: true, price_usd: 0, description: 'Long enough text' })).body.error).toBe('invalid_price');
+ expect((await owner('PUT', { active: true, price_usd: 999, description: 'Long enough text' })).body.error).toBe('invalid_price');
+ expect((await owner('PUT', { active: true, price_usd: 0.1, description: 'short' })).body.error).toBe('invalid_description');
+ });
+
+ it('refuses to activate a private agent and says why', async () => {
+ await seedAgent({ isPublic: false });
+ authState.session = { id: OWNER };
+ const { status, body } = await owner('PUT', ACTIVE);
+ expect(status).toBe(409);
+ expect(body.error).toBe('not_sellable');
+ expect(body.reasons[0]).toMatch(/private/);
+ });
+
+ it('stores an active config on meta.api_service and the paid route picks it up', async () => {
+ await seedAgent({});
+ authState.session = { id: OWNER };
+ const { status, body } = await owner('PUT', { active: true, price_usd: 0.05, description: ' Ask Ada anything. ' });
+ expect(status).toBe(200);
+ expect(body.service).toMatchObject({ active: true, price_usd: 0.05, description: 'Ask Ada anything.' });
+ const [row] = await holder.db.query('select meta from agent_identities where id = $1', [AGENT]);
+ expect(row.meta.solana_address).toBe(AGENT_WALLET);
+ expect(row.meta.api_service.active).toBe(true);
+
+ const { req, res } = mockReqRes();
+ await handler(req, res);
+ expect(res.statusCode).toBe(402);
+ expect(challengeOf(res).accepts[0].amount).toBe('50000');
+ });
+});
diff --git a/vercel.json b/vercel.json
index 7ef3ff63e..8b76261f2 100644
--- a/vercel.json
+++ b/vercel.json
@@ -718,6 +718,10 @@
"src": "/api/agents/([^/]+)/skills-pricing",
"dest": "/api/agents/[id]/skills-pricing?id=$1"
},
+ {
+ "src": "/api/agents/([^/]+)/api-service",
+ "dest": "/api/agents/[id]/api-service?id=$1"
+ },
{
"src": "/api/agents/([^/]+)/skills/price",
"dest": "/api/agent-skill-price.js?agentId=$1"
@@ -5398,6 +5402,10 @@
"src": "/api/x402/service/([^/?]+)",
"dest": "/api/x402/service.js?slug=$1"
},
+ {
+ "src": "/api/x402/agents/([^/?]+)/?",
+ "dest": "/api/x402/agents.js?agent=$1"
+ },
{
"src": "/api/(.*)",
"dest": "/api/$1"