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(agents): agent-skills a2a payments, agent detail/market updates, admin + directory refinements

nirholase0d2965e4826
diff --git a/api/admin/[resource].js b/api/admin/[resource].js
index 964e9fd1a..92822aec2 100644
--- a/api/admin/[resource].js
+++ b/api/admin/[resource].js
@@ -84,6 +84,121 @@ export default wrap(async (req, res) => {
return json(res, 200, { users, total, page, limit });
}
+ // LLM spend ledger — what the platform's inference (incl. Anthropic credits)
+ // is costing, and where it's going. Cost is micro-USD ($0.000001); the UI
+ // divides by 1e6. Free providers (groq/openrouter) price to 0 by design, so
+ // `paid_calls` vs `total_calls` shows the paid-vs-free split.
+ if (resource === 'llm-spend') {
+ const [totals] = await sql`
+ select
+ count(*)::int as total_calls,
+ count(*) filter (where created_at > now() - interval '24 hours')::int as calls_24h,
+ count(*) filter (where created_at > now() - interval '7 days')::int as calls_7d,
+ coalesce(sum(cost_micro_usd),0)::bigint as cost_micro_usd_30d,
+ coalesce(sum(cost_micro_usd) filter (where created_at > now() - interval '24 hours'),0)::bigint as cost_micro_usd_24h,
+ coalesce(sum(cost_micro_usd) filter (where created_at > now() - interval '7 days'),0)::bigint as cost_micro_usd_7d,
+ count(*) filter (where coalesce(cost_micro_usd,0) > 0)::int as paid_calls,
+ coalesce(sum(input_tokens),0)::bigint as input_tokens,
+ coalesce(sum(output_tokens),0)::bigint as output_tokens
+ from usage_events
+ where kind = 'llm' and created_at > now() - interval '30 days'
+ `;
+
+ const byProvider = await sql`
+ select coalesce(provider,'unknown') as provider,
+ count(*)::int as calls,
+ coalesce(sum(cost_micro_usd),0)::bigint as cost_micro_usd,
+ coalesce(sum(input_tokens),0)::bigint as input_tokens,
+ coalesce(sum(output_tokens),0)::bigint as output_tokens
+ from usage_events
+ where kind = 'llm' and created_at > now() - interval '30 days'
+ group by provider order by cost_micro_usd desc, calls desc
+ `;
+
+ const byModel = await sql`
+ select coalesce(model,'unknown') as model,
+ count(*)::int as calls,
+ coalesce(sum(cost_micro_usd),0)::bigint as cost_micro_usd
+ from usage_events
+ where kind = 'llm' and created_at > now() - interval '30 days'
+ group by model order by cost_micro_usd desc, calls desc limit 20
+ `;
+
+ const byDay = await sql`
+ select date_trunc('day', created_at)::date as day,
+ count(*)::int as calls,
+ coalesce(sum(cost_micro_usd),0)::bigint as cost_micro_usd
+ from usage_events
+ where kind = 'llm' and created_at > now() - interval '30 days'
+ group by 1 order by 1
+ `;
+
+ return json(res, 200, { totals, byProvider, byModel, byDay });
+ }
+
+ // Feature adoption — which capabilities users actually exercise, by event
+ // kind and tool, plus a daily activity trend across all event kinds.
+ if (resource === 'features') {
+ const byKind = await sql`
+ select kind, count(*)::int as events,
+ count(distinct user_id)::int as users,
+ count(distinct agent_id)::int as agents
+ from usage_events
+ where created_at > now() - interval '30 days'
+ group by kind order by events desc
+ `;
+
+ const byTool = await sql`
+ select coalesce(tool,'(none)') as tool, kind, count(*)::int as events
+ from usage_events
+ where created_at > now() - interval '30 days' and tool is not null
+ group by tool, kind order by events desc limit 25
+ `;
+
+ const byDay = await sql`
+ select date_trunc('day', created_at)::date as day, kind, count(*)::int as events
+ from usage_events
+ where created_at > now() - interval '30 days'
+ group by 1, 2 order by 1
+ `;
+
+ return json(res, 200, { byKind, byTool, byDay });
+ }
+
+ // x402 payment activity — the revenue side. amount_atomics is raw token
+ // units (text); we sum as numeric. The UI converts to USDC (6 decimals).
+ if (resource === 'x402') {
+ const [totals] = await sql`
+ select
+ count(*) filter (where event_type = 'payment_settled')::int as settled,
+ count(*) filter (where event_type = 'payment_failed')::int as failed,
+ count(distinct payer) filter (where event_type = 'payment_settled')::int as unique_payers,
+ coalesce(sum((amount_atomics)::numeric) filter (where event_type = 'payment_settled'),0)::text as volume_atomics
+ from x402_audit_log
+ where created_at > now() - interval '30 days'
+ `;
+
+ const byRoute = await sql`
+ select coalesce(route,'(unknown)') as route,
+ count(*)::int as payments,
+ coalesce(sum((amount_atomics)::numeric),0)::text as volume_atomics
+ from x402_audit_log
+ where event_type = 'payment_settled' and created_at > now() - interval '30 days'
+ group by route order by payments desc limit 20
+ `;
+
+ const byDay = await sql`
+ select date_trunc('day', created_at)::date as day,
+ count(*)::int as payments,
+ coalesce(sum((amount_atomics)::numeric),0)::text as volume_atomics
+ from x402_audit_log
+ where event_type = 'payment_settled' and created_at > now() - interval '30 days'
+ group by 1 order by 1
+ `;
+
+ return json(res, 200, { totals, byRoute, byDay });
+ }
+
res.statusCode = 404;
return res.end();
});
diff --git a/pages/agent-detail.html b/pages/agent-detail.html
index 87003dcdf..02549f548 100644
--- a/pages/agent-detail.html
+++ b/pages/agent-detail.html
@@ -151,6 +151,15 @@
<div id="ad-desc-skeleton" class="skeleton" style="width: 80%; height: 48px; margin-top: 8px; display: none;"></div>
<div class="ad-hero-trust" id="ad-trust-pills"></div>
<div class="ad-hero-actions">
+ <a
+ id="ad-see-3d"
+ class="ad-btn ad-btn-primary"
+ href="/play"
+ aria-label="See this agent's 3D avatar in the three.ws world"
+ >
+ <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true" style="margin-right:6px"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg>
+ See in 3D
+ </a>
<button
type="button"
id="ad-share-btn"
diff --git a/public/agents/index.html b/public/agents/index.html
index f4accffda..0f4a06dd3 100644
--- a/public/agents/index.html
+++ b/public/agents/index.html
@@ -210,6 +210,41 @@
font-size: 0.75rem;
}
+ .card-actions {
+ margin-top: 0.75rem;
+ display: flex;
+ }
+
+ .card-see3d {
+ display: inline-flex;
+ align-items: center;
+ gap: 0.4rem;
+ padding: 0.4rem 0.7rem;
+ font-size: 0.78rem;
+ font-weight: 600;
+ color: #00d9ff;
+ background: rgba(0, 217, 255, 0.08);
+ border: 1px solid rgba(0, 217, 255, 0.3);
+ border-radius: 6px;
+ text-decoration: none;
+ transition: background 0.18s ease, border-color 0.18s ease, transform 0.18s ease;
+ }
+
+ .card-see3d:hover {
+ background: rgba(0, 217, 255, 0.16);
+ border-color: rgba(0, 217, 255, 0.6);
+ transform: translateY(-1px);
+ }
+
+ .card-see3d:focus-visible {
+ outline: 2px solid #00d9ff;
+ outline-offset: 2px;
+ }
+
+ .card-see3d svg {
+ opacity: 0.9;
+ }
+
.chain-badge {
background: rgba(255, 255, 255, 0.08);
border: 1px solid rgba(255, 255, 255, 0.2);
diff --git a/scripts/avatar-pos.mjs b/scripts/avatar-pos.mjs
index f320c62da..05004a66b 100644
--- a/scripts/avatar-pos.mjs
+++ b/scripts/avatar-pos.mjs
@@ -1,13 +1,17 @@
import puppeteer from 'puppeteer';
-const b = await puppeteer.launch({ args:['--no-sandbox','--use-gl=swiftshader','--enable-webgl'] });
+const b = await puppeteer.launch({ args:['--no-sandbox','--use-gl=swiftshader','--enable-webgl','--enable-unsafe-swiftshader'] });
const p = await b.newPage();
+p.on('console', m=>console.log('PAGE>', m.type(), m.text()));
+p.on('pageerror', e=>console.log('PAGEERR>', e.message));
await p.setViewport({ width:1440, height:900 });
await p.goto('http://localhost:3001/login.html', { waitUntil:'networkidle2' });
-await new Promise(r=>setTimeout(r,3000));
+await new Promise(r=>setTimeout(r,3500));
+const info = await p.evaluate(()=>({ hasAgent: !!window.__agent, hasAvatar: !!(window.__agent&&window.__agent.avatar) }));
+console.log('INFO', JSON.stringify(info));
const read = ()=>p.evaluate(()=>{
const a=window.__agent; if(!a||!a.avatar) return {err:'no agent/avatar'};
const s=a.worldToScreen(a.avatar.position.x, a.avatar.position.y);
- return { scrollY:window.scrollY, avatarScreenX:Math.round(s.x), avatarScreenY:Math.round(s.y), wx:+a.avatar.position.x.toFixed(3), wy:+a.avatar.position.y.toFixed(3) };
+ return { scrollY:window.scrollY, avatarScreenX:Math.round(s.x), avatarScreenY:Math.round(s.y) };
});
await p.evaluate(()=>window.scrollTo(0,0)); await new Promise(r=>setTimeout(r,400));
console.log('scroll0 ', JSON.stringify(await read()));
diff --git a/scripts/vanity-controls-probe.mjs b/scripts/vanity-controls-probe.mjs
new file mode 100644
index 000000000..d89304993
--- /dev/null
+++ b/scripts/vanity-controls-probe.mjs
@@ -0,0 +1,62 @@
+// One-off probe: verify vanity-wallet core selector + pause/resume/stop.
+// Usage: node scripts/vanity-controls-probe.mjs [baseUrl]
+import { chromium } from 'playwright';
+
+const base = process.argv[2] || 'http://localhost:3002';
+const browser = await chromium.launch();
+const page = await browser.newPage();
+
+const errors = [];
+page.on('console', (m) => { if (m.type() === 'error') errors.push(m.text()); });
+page.on('pageerror', (e) => errors.push('pageerror: ' + e.message));
+
+await page.goto(`${base}/vanity-wallet.html`, { waitUntil: 'networkidle' });
+
+const hwMax = await page.locator('#core-max').textContent();
+const sliderMax = await page.locator('#core-count').getAttribute('max');
+const startVal = await page.locator('#core-count-val').textContent();
+console.log(`cores: default=${startVal} max=${hwMax} sliderMax=${sliderMax} presets=${await page.locator('#core-ticks button').count()}`);
+
+// Pick a 1-char prefix so it resolves fast, force 2 cores via slider.
+await page.fill('#prefix', 'A');
+await page.locator('#core-count').fill('2');
+console.log('after slider set 2 ->', await page.locator('#core-count-val').textContent());
+
+await page.click('#grind');
+await page.waitForSelector('#pause:not([hidden])');
+await page.waitForFunction(() => Number(document.getElementById('attempts').textContent.replace(/,/g,'')) > 0, { timeout: 10000 });
+
+// Pause and confirm attempts freeze.
+await page.click('#pause');
+await page.waitForSelector('#paused-tag:not([hidden])');
+const a1 = await page.locator('#attempts').textContent();
+await page.waitForTimeout(600);
+const a2 = await page.locator('#attempts').textContent();
+console.log(`paused: btn="${await page.locator('#pause').textContent()}" attempts ${a1} -> ${a2} (frozen=${a1 === a2})`);
+console.log('cores slider disabled while running:', await page.locator('#core-count').isDisabled());
+
+// Resume and confirm progress continues.
+await page.click('#pause');
+await page.waitForTimeout(500);
+const a3 = await page.locator('#attempts').textContent();
+console.log(`resumed: attempts -> ${a3} (advanced=${a3 !== a2})`);
+
+// Wait for the 1-char result (near-instant), verify address + cores.
+await page.waitForSelector('.result', { timeout: 15000 });
+const addr = await page.locator('.result .addr').textContent();
+const meta = await page.locator('.result .meta').textContent();
+console.log('result addr:', addr.trim().slice(0, 12), '| meta:', meta.replace(/\s+/g,' ').trim());
+console.log('cores re-enabled after result:', !(await page.locator('#core-count').isDisabled()));
+
+// Stop path: start again, stop mid-grind with a 3-char prefix.
+await page.fill('#prefix', 'zzz');
+await page.click('#grind');
+await page.waitForSelector('#stop:not([hidden])');
+await page.waitForFunction(() => Number(document.getElementById('attempts').textContent.replace(/,/g,'')) > 0, { timeout: 10000 });
+await page.click('#stop');
+await page.waitForTimeout(400);
+console.log('after stop: progress hidden =', await page.locator('#progress').isHidden(), '| grind visible =', await page.locator('#grind').isVisible());
+
+console.log('CONSOLE ERRORS:', errors.length ? errors : 'none');
+await browser.close();
+process.exit(errors.length ? 1 : 0);
diff --git a/src/agent-detail-market.js b/src/agent-detail-market.js
index c89ad28cc..35af73acb 100644
--- a/src/agent-detail-market.js
+++ b/src/agent-detail-market.js
@@ -36,6 +36,7 @@ import {
USDC_MAINNET_MINT,
} from './shared/skill-purchase.js';
import { log } from './shared/log.js';
+import { seeInWorldHref, hasCustomAvatar } from './shared/agent-3d.js';
const API = '/api';
const $ = (id) => document.getElementById(id);
@@ -103,6 +104,7 @@ export async function enrichAgentDetail(baseAgent) {
});
render3DAvatar(market);
+ upgradeSee3d(market);
renderMeta(market);
renderHeroActions(baseAgent, market);
renderSalePanel(baseAgent, market);
@@ -172,6 +174,16 @@ function render3DAvatar(a) {
img.replaceWith(mv);
}
+// Upgrade the always-present "See in 3D" link once the marketplace record (with
+// its custom avatar_glb_url) is in hand — so agents that ship their own avatar
+// walk into the world as themselves rather than the base mannequin.
+function upgradeSee3d(a) {
+ const see3d = $('ad-see-3d');
+ if (!see3d) return;
+ see3d.href = seeInWorldHref(a);
+ if (hasCustomAvatar(a)) see3d.setAttribute('title', `See ${a.name || 'this agent'} in the three.ws world`);
+}
+
// ── Hero metadata ─────────────────────────────────────────────────────────────
function renderMeta(a) {
diff --git a/src/agent-detail.js b/src/agent-detail.js
index 721c1ae8f..7310edab5 100644
--- a/src/agent-detail.js
+++ b/src/agent-detail.js
@@ -26,6 +26,7 @@ const solanaWeb3 = {
};
import { openSwapModal } from './swap-jupiter.js';
import { onchainBadgeEl } from './shared/onchain-badge.js';
+import { seeInWorldHref } from './shared/agent-3d.js';
import { renderError as renderAsyncError } from './shared/async-state.js';
import { openCoinLaunch } from './shared/agent-coin.js';
import { Modal } from './shared/modal.js';
@@ -286,6 +287,13 @@ function render(agent) {
};
$('ad-name').textContent = agent.name;
+ // "See in 3D" drops this agent's avatar into the live $three world. Every
+ // agent has one — its own GLB if attached, the base mannequin otherwise — so
+ // the button is always live. Marketplace enrichment upgrades the href to a
+ // richer custom GLB if the agent ships one.
+ const see3d = $('ad-see-3d');
+ if (see3d) see3d.href = seeInWorldHref(agent);
+
const status = $('ad-status');
status.textContent = agent.active ? 'Active' : 'Inactive';
status.classList.toggle('ad-status-inactive', !agent.active);
diff --git a/src/agent-skills-a2a.js b/src/agent-skills-a2a.js
new file mode 100644
index 000000000..eaad30934
--- /dev/null
+++ b/src/agent-skills-a2a.js
@@ -0,0 +1,144 @@
+/**
+ * Agent-to-Agent payment skill
+ * ----------------------------
+ * Lets an agent autonomously discover, pay, and call a peer agent's paid A2A
+ * skill — under a signed Intent Mandate the user issued ahead of time. The
+ * payment is not invisible JSON: it flows through the protocol bus as
+ * PAY_INTENT → PAY_SETTLED / PAY_FAILED so the avatar performs it. On success
+ * the agent celebrates and speaks the result; on failure it shows concern and
+ * explains what went wrong.
+ *
+ * Backend: POST /api/agents/a2a-call enforces the mandate, budget ledger, and
+ * (optionally) the peer's ERC-8004 reputation before any USDC moves.
+ */
+
+import { ACTION_TYPES } from './agent-protocol.js';
+
+// USDC and the other supported stablecoins are 6-decimal — render atomic units
+// as a human dollar amount for speech and logging.
+function formatAtomicUsd(atomics) {
+ const n = Number(atomics);
+ if (!Number.isFinite(n)) return String(atomics);
+ return `$${(n / 1e6).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 4 })}`;
+}
+
+export function registerA2APaymentSkills(skills) {
+ skills.register({
+ name: 'pay-agent',
+ description:
+ 'Pay and call another agent’s paid skill over the A2A x402 protocol, under an Intent Mandate',
+ instruction:
+ 'Discover the peer’s price, pay it under the active mandate if within budget and the peer is trusted, then return the result. Show the payment happening.',
+ animationHint: 'present',
+ voicePattern: 'Paying {{endpoint}} for that skill…',
+ mcpExposed: true,
+ inputSchema: {
+ type: 'object',
+ required: ['endpoint', 'mandate'],
+ properties: {
+ endpoint: { type: 'string', description: 'Peer agent A2A endpoint URL' },
+ mandate: { type: 'string', description: 'Signed Intent Mandate (compact JWS)' },
+ text: { type: 'string', description: 'Message / task to send the peer' },
+ network: { type: 'string', description: 'Preferred settlement network (CAIP-2)' },
+ reputationAgentId: { type: 'string', description: 'Peer on-chain agentId for reputation gating' },
+ reputationChainId: { type: 'number', description: 'Chain to read reputation on' },
+ minAverage: { type: 'number', description: 'Minimum acceptable peer reputation average' },
+ minCount: { type: 'number', description: 'Minimum acceptable peer review count' },
+ },
+ },
+ handler: async (args, ctx) => {
+ const { endpoint, mandate, text } = args;
+ if (!endpoint || !mandate) {
+ return {
+ success: false,
+ output: 'I need both a peer endpoint and a signed mandate to pay another agent.',
+ sentiment: -0.3,
+ };
+ }
+
+ const agentId = ctx.identity?.id || 'default';
+
+ // Announce intent — the avatar can lean toward the payee and gesture.
+ if (ctx.isBrowser) {
+ ctx.protocol.emit({
+ type: ACTION_TYPES.PAY_INTENT,
+ payload: { endpoint },
+ agentId,
+ });
+ }
+
+ const reputation =
+ args.reputationAgentId !== undefined
+ ? {
+ agentId: args.reputationAgentId,
+ chainId: args.reputationChainId,
+ minAverage: args.minAverage,
+ minCount: args.minCount,
+ }
+ : undefined;
+
+ let res, data;
+ try {
+ res = await fetch('/api/agents/a2a-call', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({
+ endpoint,
+ mandate,
+ text: text || 'Initiate paid skill.',
+ networkPreference: args.network ? [args.network] : undefined,
+ reputation,
+ }),
+ });
+ data = await res.json();
+ } catch (err) {
+ if (ctx.isBrowser) {
+ ctx.protocol.emit({ type: ACTION_TYPES.PAY_FAILED, payload: { endpoint, error: err.message }, agentId });
+ ctx.protocol.emit({ type: ACTION_TYPES.EMOTE, payload: { trigger: 'concern', weight: 0.8 }, agentId });
+ }
+ return { success: false, output: `I couldn’t reach the payment service: ${err.message}`, sentiment: -0.5 };
+ }
+
+ if (!res.ok || !data?.ok) {
+ const reason = data?.error_description || data?.error || `HTTP ${res.status}`;
+ if (ctx.isBrowser) {
+ ctx.protocol.emit({ type: ACTION_TYPES.PAY_FAILED, payload: { endpoint, error: reason, code: data?.error }, agentId });
+ ctx.protocol.emit({ type: ACTION_TYPES.EMOTE, payload: { trigger: 'concern', weight: 0.8 }, agentId });
+ }
+ return { success: false, output: `Payment didn’t go through: ${reason}`, sentiment: -0.5, data };
+ }
+
+ const tx = data.receipts?.[0]?.transaction || null;
+ if (ctx.isBrowser) {
+ ctx.protocol.emit({
+ type: ACTION_TYPES.PAY_SETTLED,
+ payload: {
+ endpoint,
+ amount: data.amount,
+ network: data.network,
+ currency: data.currency,
+ payer: data.payer,
+ transaction: tx,
+ mandateId: data.mandate_id,
+ artifacts: data.artifacts || [],
+ },
+ agentId,
+ });
+ // Settlement is a win — perform it.
+ ctx.protocol.emit({ type: ACTION_TYPES.EMOTE, payload: { trigger: 'celebrate', weight: 0.9 }, agentId });
+ }
+
+ const amountUsd = formatAtomicUsd(data.amount);
+ const artifactNote = data.artifacts?.length
+ ? ` I received ${data.artifacts.length} artifact${data.artifacts.length === 1 ? '' : 's'} back.`
+ : '';
+ return {
+ success: true,
+ output: `Paid ${amountUsd} on ${data.network} and called the peer skill.${artifactNote}`,
+ sentiment: 0.7,
+ data,
+ };
+ },
+ });
+}
diff --git a/src/agent-skills.js b/src/agent-skills.js
index eda0743de..94c44292c 100644
--- a/src/agent-skills.js
+++ b/src/agent-skills.js
@@ -23,6 +23,7 @@ import { registerNftSkills } from './agent-skills-nfts.js';
import { registerSceneSkills } from './agent-skills-scene.js';
import { registerSentimentSkills } from './agent-skills-sentiment.js';
import { registerAgentPaymentSkills } from './agent-skills-agent-payments.js';
+import { registerA2APaymentSkills } from './agent-skills-a2a.js';
import { registerAixbtSkills } from './agent-skills-aixbt.js';
/**
@@ -76,6 +77,7 @@ export class AgentSkills {
registerSceneSkills(this);
registerSentimentSkills(this);
registerAgentPaymentSkills(this);
+ registerA2APaymentSkills(this);
registerAixbtSkills(this);
}
diff --git a/src/agents-directory.js b/src/agents-directory.js
index dcf75946a..1e35ba3a9 100644
--- a/src/agents-directory.js
+++ b/src/agents-directory.js
@@ -14,6 +14,7 @@ import {
import { CHAIN_META } from './erc8004/chain-meta.js';
import { REGISTRY_DEPLOYMENTS } from './erc8004/abi.js';
import { onchainBadgeHTML } from './shared/onchain-badge.js';
+import { seeInWorldHref, hasCustomAvatar } from './shared/agent-3d.js';
import { log } from './shared/log.js';
const CACHE_TTL_MS = 60000;
@@ -288,6 +289,11 @@ export class AgentsDirectory {
// ERC-8004 shape uses `id`/`chainId`; map `id` → `agentId` for detection.
const onchainBadge = onchainBadgeHTML({ ...agent, agentId: agent.id });
+ // "See in 3D" drops this agent's avatar into the live $three world — its own
+ // GLB if it ships one, the base mannequin otherwise — so every card has it.
+ const see3dHref = this._escapeHtml(seeInWorldHref(agent));
+ const see3dLabel = hasCustomAvatar(agent) ? 'See in 3D' : 'View in 3D';
+
return `
<div class="agent-card" data-agent-id="${agent.id}" data-chain-id="${agent.chainId}">
<div class="card-head">
@@ -315,6 +321,12 @@ export class AgentsDirectory {
? `<div class="card-owner"><span class="owner-addr" data-copy="${ownerFull}" title="${ownerFull}">${this._escapeHtml(ownerShort)}</span><button class="owner-copy" data-copy="${ownerFull}" aria-label="Copy address">⎘</button></div>`
: ''
}
+ <div class="card-actions">
+ <a class="card-see3d" href="${see3dHref}" aria-label="${see3dLabel}: ${cleanName} in the three.ws world">
+ <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><path d="M21 16V8a2 2 0 0 0-1-1.73l-7-4a2 2 0 0 0-2 0l-7 4A2 2 0 0 0 3 8v8a2 2 0 0 0 1 1.73l7 4a2 2 0 0 0 2 0l7-4A2 2 0 0 0 21 16z"/><polyline points="3.27 6.96 12 12.01 20.73 6.96"/><line x1="12" y1="22.08" x2="12" y2="12"/></svg>
+ <span>${see3dLabel}</span>
+ </a>
+ </div>
</div>
`;
}
@@ -333,9 +345,10 @@ export class AgentsDirectory {
_attachEventListeners() {
this.container.querySelectorAll('.agent-card').forEach((card) => {
card.addEventListener('click', (e) => {
- // Let the on-chain badge open the block explorer without also
- // triggering card navigation.
+ // Let the on-chain badge open the block explorer, and the "See in 3D"
+ // link open the world, without also triggering card navigation.
if (e.target.closest('a.tws-ocb')) return;
+ if (e.target.closest('a.card-see3d')) return;
const copyTarget = e.target.closest('[data-copy]');
if (copyTarget) {
e.stopPropagation();
diff --git a/src/shared/agent-3d.js b/src/shared/agent-3d.js
index cccd2b5b0..4808a5f63 100644
--- a/src/shared/agent-3d.js
+++ b/src/shared/agent-3d.js
@@ -25,10 +25,12 @@ export function agentAvatarGlb(agent) {
const direct = agent.avatar_glb_url || agent.base_model_url || agent.glb_url || agent.model_url;
if (typeof direct === 'string' && GLB_RE.test(direct)) return direct;
- // ERC-8004 on-chain agents expose their model through registration metadata.
+ // ERC-8004 on-chain agents expose their model through registration metadata
+ // (surfaced as `metadata` on the directory, `rawMetadata` on the detail page).
try {
- if (agent.metadata) {
- const fromMeta = findAvatar3D(agent.metadata);
+ const meta = agent.metadata || agent.rawMetadata;
+ if (meta) {
+ const fromMeta = findAvatar3D(meta);
if (fromMeta) return fromMeta;
}
} catch { /* metadata malformed — fall through to the base avatar */ }
diff --git a/tests/agent-a2a-payments.test.js b/tests/agent-a2a-payments.test.js
new file mode 100644
index 000000000..7b5761934
--- /dev/null
+++ b/tests/agent-a2a-payments.test.js
@@ -0,0 +1,425 @@
+// Tests for autonomous agent-to-agent payments: Intent Mandates, the spend
+// ledger that enforces total budget, the ERC-8004 reputation gate, and the
+// /api/agents/a2a-call endpoint that composes all three before paying a peer.
+
+import { beforeEach, describe, expect, it, vi } from 'vitest';
+
+// Mandate signing reads env lazily; set the secret before anything imports it.
+process.env.JWT_SECRET = process.env.JWT_SECRET || 'test-jwt-secret';
+process.env.A2A_MANDATE_SECRET = 'test-a2a-mandate-secret';
+
+import {
+ assertMandateAllows,
+ issueIntentMandate,
+ MandateError,
+ verifyIntentMandate,
+} from '../api/_lib/a2a/mandate.js';
+import { assertReputationOk, ReputationError } from '../api/_lib/a2a/reputation-gate.js';
+import { _resetMemoryStore, release, reserve, spent } from '../api/_lib/a2a/spend-ledger.js';
+
+// ── Intent Mandate ──────────────────────────────────────────────────────────
+
+describe('Intent Mandate', () => {
+ const base = {
+ ownerUserId: 'user-1',
+ subjectAgentId: 'agent-1',
+ maxAtomics: '10000000', // $10
+ perCallAtomics: '1000000', // $1
+ networks: ['eip155:8453'],
+ ttlSec: 3600,
+ };
+
+ it('issues and verifies a mandate round-trip', async () => {
+ const { jws, mandate } = await issueIntentMandate(base);
+ expect(typeof jws).toBe('string');
+ const verified = await verifyIntentMandate(jws);
+ expect(verified.ownerUserId).toBe('user-1');
+ expect(verified.subjectAgentId).toBe('agent-1');
+ expect(verified.maxAtomics).toBe('10000000');
+ expect(verified.perCallAtomics).toBe('1000000');
+ expect(verified.mandateId).toBe(mandate.mandateId);
+ expect(verified.networks).toEqual(['eip155:8453']);
+ });
+
+ it('rejects a tampered/invalid mandate', async () => {
+ await expect(verifyIntentMandate('not.a.jwt')).rejects.toMatchObject({ code: 'invalid_mandate' });
+ const { jws } = await issueIntentMandate(base);
+ await expect(verifyIntentMandate(jws + 'x')).rejects.toBeInstanceOf(MandateError);
+ });
+
+ it('rejects perCall greater than max at issuance', async () => {
+ await expect(
+ issueIntentMandate({ ...base, perCallAtomics: '99000000' }),
+ ).rejects.toMatchObject({ code: 'invalid_amount' });
+ });
+
+ it('rejects an unsupported network at issuance', async () => {
+ await expect(
+ issueIntentMandate({ ...base, networks: ['eip155:999999'] }),
+ ).rejects.toMatchObject({ code: 'unsupported_network' });
+ });
+
+ it('rejects a non-http resource prefix at issuance', async () => {
+ await expect(
+ issueIntentMandate({ ...base, resources: ['ftp://evil'] }),
+ ).rejects.toMatchObject({ code: 'invalid_resources' });
+ });
+
+ describe('assertMandateAllows', () => {
+ let mandate;
+ beforeEach(async () => {
+ mandate = (
+ await issueIntentMandate({ ...base, resources: ['https://peer.example/'] })
+ ).mandate;
+ });
+
+ it('allows a payment within policy', () => {
+ expect(() =>
+ assertMandateAllows({
+ mandate,
+ amountAtomics: '1000000',
+ network: 'eip155:8453',
+ resource: 'https://peer.example/skill',
+ currency: 'USDC',
+ }),
+ ).not.toThrow();
+ });
+
+ it('blocks a payment over the per-call cap', () => {
+ expect(() =>
+ assertMandateAllows({ mandate, amountAtomics: '2000000', network: 'eip155:8453' }),
+ ).toThrow(/per-call/);
+ });
+
+ it('blocks a disallowed network', () => {
+ expect(() =>
+ assertMandateAllows({ mandate, amountAtomics: '1000000', network: 'eip155:137' }),
+ ).toThrow(/network/);
+ });
+
+ it('blocks a resource outside the allowlist', () => {
+ expect(() =>
+ assertMandateAllows({
+ mandate,
+ amountAtomics: '1000000',
+ network: 'eip155:8453',
+ resource: 'https://other.example/skill',
+ }),
+ ).toThrow(/does not authorize paying/);
+ });
+
+ it('blocks a currency mismatch', () => {
+ expect(() =>
+ assertMandateAllows({
+ mandate,
+ amountAtomics: '1000000',
+ network: 'eip155:8453',
+ currency: 'DAI',
+ }),
+ ).toThrow(/authorizes USDC/);
+ });
+
+ it('blocks an expired mandate', () => {
+ expect(() =>
+ assertMandateAllows({
+ mandate,
+ amountAtomics: '1000000',
+ network: 'eip155:8453',
+ nowSec: mandate.expiresAt + 1,
+ }),
+ ).toThrow(/expired/);
+ });
+ });
+});
+
+// ── Spend ledger ────────────────────────────────────────────────────────────
+
+describe('Spend ledger', () => {
+ beforeEach(() => _resetMemoryStore());
+
+ it('reserves within the cap and accumulates spend', async () => {
+ const r1 = await reserve('m-1', 1_000_000, 3_000_000, 3600);
+ expect(r1).toMatchObject({ ok: true, spent: 1_000_000, cap: 3_000_000 });
+ const r2 = await reserve('m-1', 1_000_000, 3_000_000, 3600);
+ expect(r2.ok).toBe(true);
+ expect(r2.spent).toBe(2_000_000);
+ expect(await spent('m-1')).toBe(2_000_000);
+ });
+
+ it('refuses a reservation that would exceed the cap and reserves nothing', async () => {
+ await reserve('m-2', 2_000_000, 3_000_000, 3600);
+ const r = await reserve('m-2', 2_000_000, 3_000_000, 3600);
+ expect(r.ok).toBe(false);
+ expect(r.spent).toBe(2_000_000); // unchanged
+ expect(await spent('m-2')).toBe(2_000_000);
+ });
+
+ it('releases a reservation and floors at zero', async () => {
+ await reserve('m-3', 1_000_000, 3_000_000, 3600);
+ expect(await release('m-3', 1_000_000)).toBe(0);
+ expect(await release('m-3', 1_000_000)).toBe(0); // double release stays at 0
+ });
+
+ it('rejects unsafe amounts', async () => {
+ await expect(reserve('m-4', -1, 10, 60)).rejects.toThrow();
+ await expect(reserve('m-4', Number.MAX_SAFE_INTEGER + 2, 10, 60)).rejects.toThrow();
+ });
+});
+
+// ── Reputation gate ─────────────────────────────────────────────────────────
+
+describe('Reputation gate', () => {
+ it('is a no-op when no threshold is set', async () => {
+ const read = vi.fn();
+ const out = await assertReputationOk({ agentId: '1', chainId: 8453, read });
+ expect(out).toBeNull();
+ expect(read).not.toHaveBeenCalled();
+ });
+
+ it('passes when the peer clears the bar', async () => {
+ const read = vi.fn(async () => ({ average: 4.5, count: 12 }));
+ const out = await assertReputationOk({ agentId: '1', chainId: 8453, minAverage: 4, minCount: 5, read });
+ expect(out).toEqual({ average: 4.5, count: 12 });
+ });
+
+ it('fails when average is too low', async () => {
+ const read = vi.fn(async () => ({ average: 2.0, count: 50 }));
+ await expect(
+ assertReputationOk({ agentId: '1', chainId: 8453, minAverage: 4, read }),
+ ).rejects.toMatchObject({ code: 'reputation_too_low' });
+ });
+
+ it('fails when there are too few reviews', async () => {
+ const read = vi.fn(async () => ({ average: 5, count: 1 }));
+ await expect(
+ assertReputationOk({ agentId: '1', chainId: 8453, minCount: 5, read }),
+ ).rejects.toMatchObject({ code: 'reputation_too_few_reviews' });
+ });
+
+ it('requires an agentId when a threshold is set', async () => {
+ await expect(assertReputationOk({ chainId: 8453, minAverage: 4 })).rejects.toMatchObject({
+ code: 'reputation_required',
+ });
+ });
+
+ it('fails closed when the reader throws', async () => {
+ const read = vi.fn(async () => {
+ throw new Error('rpc down');
+ });
+ await expect(
+ assertReputationOk({ agentId: '1', chainId: 8453, minAverage: 4, read }),
+ ).rejects.toBeInstanceOf(ReputationError);
+ });
+});
+
+// ── /api/agents/a2a-call endpoint ───────────────────────────────────────────
+
+const authState = { session: null, bearer: null };
+const rlState = { success: true };
+const clientState = {
+ quote: null,
+ submit: null,
+};
+
+vi.mock('../api/_lib/auth.js', () => ({
+ getSessionUser: vi.fn(async () => authState.session),
+ authenticateBearer: vi.fn(async () => authState.bearer),
+ extractBearer: vi.fn(() => null),
+}));
+
+vi.mock('../api/_lib/rate-limit.js', () => ({
+ limits: {
+ mcpAgentPay: vi.fn(async () => ({ success: rlState.success })),
+ mcpAgent: vi.fn(async () => ({ success: rlState.success })),
+ },
+ clientIp: vi.fn(() => '127.0.0.1'),
+}));
+
+vi.mock('../api/_lib/ssrf-guard.js', () => ({
+ SsrfBlockedError: class SsrfBlockedError extends Error {},
+ assertSafePublicUrl: vi.fn(async (u) => new URL(u)),
+}));
+
+vi.mock('../api/_lib/x402/a2a-client.js', () => ({
+ A2AClientError: class A2AClientError extends Error {
+ constructor(code, message, details) {
+ super(message);
+ this.code = code;
+ this.details = details;
+ }
+ },
+ requestQuote: vi.fn(async () => clientState.quote),
+ submitPayment: vi.fn(async () => clientState.submit),
+ buildEvmExactPayload: vi.fn(async () => ({ scheme: 'exact', payload: {} })),
+ createPrivateKeySigner: vi.fn(async () => ({ address: '0xPayer', signAuthorization: vi.fn() })),
+}));
+
+const { invoke } = await import('./_helpers/monetization.js');
+const { default: a2aCallHandler } = await import('../api/agents/a2a-call.js');
+
+function quoteWith(amount) {
+ return {
+ taskId: 'task-1',
+ required: {
+ resource: { url: 'https://peer.example/skill', mimeType: 'application/json' },
+ accepts: [
+ {
+ scheme: 'exact',
+ network: 'eip155:8453',
+ amount,
+ payTo: '0xPeer',
+ asset: '0xUSDC',
+ extra: { name: 'USD Coin', version: '2', decimals: 6 },
+ },
+ ],
+ },
+ };
+}
+
+const completed = {
+ state: 'completed',
+ receipts: [{ success: true, transaction: '0xtx', network: 'eip155:8453' }],
+ task: { artifacts: [{ artifactId: 'a1', name: 'report.json', parts: [] }] },
+};
+
+async function freshMandate(overrides = {}) {
+ const { jws } = await issueIntentMandate({
+ ownerUserId: 'user-1',
+ subjectAgentId: 'agent-1',
+ maxAtomics: '10000000',
+ perCallAtomics: '1000000',
+ networks: ['eip155:8453'],
+ ttlSec: 3600,
+ ...overrides,
+ });
+ return jws;
+}
+
+describe('POST /api/agents/a2a-call', () => {
+ beforeEach(() => {
+ authState.session = null;
+ authState.bearer = null;
+ rlState.success = true;
+ clientState.quote = quoteWith('1000000');
+ clientState.submit = completed;
+ process.env.A2A_PAYER_PRIVATE_KEY = '0x59c6995e998f97a5a0044966f0945389dc9e86dae88c7a8412f4603b6b78690d';
+ _resetMemoryStore();
+ });
+
+ it('returns 401 when unauthenticated', async () => {
+ const { status, body } = await invoke(a2aCallHandler, {
+ method: 'POST',
+ url: '/api/agents/a2a-call',
+ body: { endpoint: 'https://peer.example/skill', mandate: await freshMandate() },
+ });
+ expect(status).toBe(401);
+ expect(body.error).toBe('unauthorized');
+ });
+
+ it('rejects a mandate issued to a different user', async () => {
+ authState.session = { id: 'user-1' };
+ const otherMandate = await freshMandate({ ownerUserId: 'user-2' });
+ const { status, body } = await invoke(a2aCallHandler, {
+ method: 'POST',
+ url: '/api/agents/a2a-call',
+ body: { endpoint: 'https://peer.example/skill', mandate: otherMandate },
+ });
+ expect(status).toBe(403);
+ expect(body.error).toBe('mandate_not_yours');
+ });
+
+ it('pays a peer end-to-end under a valid mandate', async () => {
+ authState.session = { id: 'user-1' };
+ const { status, body } = await invoke(a2aCallHandler, {
+ method: 'POST',
+ url: '/api/agents/a2a-call',
+ body: { endpoint: 'https://peer.example/skill', mandate: await freshMandate(), text: 'inspect' },
+ });
+ expect(status).toBe(200);
+ expect(body.ok).toBe(true);
+ expect(body.amount).toBe('1000000');
+ expect(body.network).toBe('eip155:8453');
+ expect(body.receipts[0].transaction).toBe('0xtx');
+ expect(body.artifacts).toHaveLength(1);
+ expect(body.spent).toBe(1_000_000);
+ });
+
+ it('blocks a payment over the per-call cap', async () => {
+ authState.session = { id: 'user-1' };
+ clientState.quote = quoteWith('5000000'); // $5 > $1 per-call cap
+ const { status, body } = await invoke(a2aCallHandler, {
+ method: 'POST',
+ url: '/api/agents/a2a-call',
+ body: { endpoint: 'https://peer.example/skill', mandate: await freshMandate() },
+ });
+ expect(status).toBe(402);
+ expect(body.error).toBe('amount_over_per_call');
+ });
+
+ it('enforces the total budget across calls', async () => {
+ authState.session = { id: 'user-1' };
+ // Budget == per-call == $1, so the first call exhausts it.
+ const mandate = await freshMandate({ maxAtomics: '1000000', perCallAtomics: '1000000' });
+ const first = await invoke(a2aCallHandler, {
+ method: 'POST',
+ url: '/api/agents/a2a-call',
+ body: { endpoint: 'https://peer.example/skill', mandate },
+ });
+ expect(first.status).toBe(200);
+ const second = await invoke(a2aCallHandler, {
+ method: 'POST',
+ url: '/api/agents/a2a-call',
+ body: { endpoint: 'https://peer.example/skill', mandate },
+ });
+ expect(second.status).toBe(402);
+ expect(second.body.error).toBe('budget_exceeded');
+ });
+
+ it('returns 501 when the payer wallet is not configured', async () => {
+ authState.session = { id: 'user-1' };
+ delete process.env.A2A_PAYER_PRIVATE_KEY;
+ const { status, body } = await invoke(a2aCallHandler, {
+ method: 'POST',
+ url: '/api/agents/a2a-call',
+ body: { endpoint: 'https://peer.example/skill', mandate: await freshMandate() },
+ });
+ expect(status).toBe(501);
+ expect(body.error).toBe('payer_not_configured');
+ });
+
+ it('releases the budget reservation when settlement fails', async () => {
+ authState.session = { id: 'user-1' };
+ clientState.submit = { state: 'failed', receipts: [{ success: false, errorReason: 'insufficient funds' }] };
+ const mandate = await freshMandate();
+ const failed = await invoke(a2aCallHandler, {
+ method: 'POST',
+ url: '/api/agents/a2a-call',
+ body: { endpoint: 'https://peer.example/skill', mandate },
+ });
+ expect(failed.status).toBe(502);
+ expect(failed.body.error).toBe('payment_failed');
+
+ // The failed reservation must have been released, so a retry that settles
+ // succeeds rather than hitting a phantom budget ceiling.
+ clientState.submit = completed;
+ const retry = await invoke(a2aCallHandler, {
+ method: 'POST',
+ url: '/api/agents/a2a-call',
+ body: { endpoint: 'https://peer.example/skill', mandate },
+ });
+ expect(retry.status).toBe(200);
+ expect(retry.body.spent).toBe(1_000_000);
+ });
+
+ it('returns 429 when rate limited', async () => {
+ authState.session = { id: 'user-1' };
+ rlState.success = false;
+ const { status, body } = await invoke(a2aCallHandler, {
+ method: 'POST',
+ url: '/api/agents/a2a-call',
+ body: { endpoint: 'https://peer.example/skill', mandate: await freshMandate() },
+ });
+ expect(status).toBe(429);
+ expect(body.error).toBe('rate_limited');
+ });
+});