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
Refactor tip jar skill documentation and code for clarity and consistency
nirholas22bfd4ca2e77
diff --git a/api/v1/agents/[caip].js b/api/v1/agents/[caip].jsindex b5380458c..92d6312d7 100644--- a/api/v1/agents/[caip].js+++ b/api/v1/agents/[caip].js@@ -60,7 +60,12 @@ export default wrap(async (req, res) => {return error(res, 404, 'not_found', `agent ${agentId} not found on chain ${chainId}`);}if (result.registry?.toLowerCase() !== registry.toLowerCase()) {- return error(res, 400, 'registry_mismatch', 'CAIP registry differs from canonical deployment');+ return error(+ res,+ 400,+ 'registry_mismatch',+ 'CAIP registry differs from canonical deployment',+ );}const card = result.manifest || null;diff --git a/index.html b/index.htmlindex e27259f84..a802d5814 100644--- a/index.html+++ b/index.html@@ -929,6 +929,8 @@el.textContent = 'Dashboard';el.href = '/dashboard';}+ const myAgents = document.getElementById('nav-my-agents');+ if (myAgents) myAgents.hidden = false;const heroSignin = document.getElementById('hero-signin-hint');if (heroSignin) heroSignin.hidden = true;}diff --git a/public/dashboard/dashboard.js b/public/dashboard/dashboard.jsindex 631adf0d5..da8e91aeb 100644--- a/public/dashboard/dashboard.js+++ b/public/dashboard/dashboard.js@@ -1621,9 +1621,67 @@ function renderAgentRows(list, onchainAgents, dbAgents) {}}-// ── Billing placeholder ─────────────────────────────────────────────────────-function renderBilling(root) {- root.innerHTML = `<h1>Plan & usage</h1><p class="sub">You're on the <b>${esc(state.user.plan)}</b> plan.</p><div class="card muted">Detailed usage analytics coming soon.</div>`;+// ── Billing & usage ─────────────────────────────────────────────────────────+async function renderBilling(root) {+ root.innerHTML = `+ <h1>Plan & usage</h1>+ <p class="sub">You're on the <b>${esc(state.user.plan)}</b> plan.</p>+ <div id="billing-body"><div class="muted">Loading…</div></div>+ `;+ const body = root.querySelector('#billing-body');+ let data;+ try {+ const r = await fetch('/api/billing/summary', { credentials: 'include' });+ if (r.ok) data = await r.json();+ } catch {}+ if (!data) { body.innerHTML = '<div class="card muted">Could not load usage data.</div>'; return; }+ const { plan, quotas, usage } = data;+ function fmtBytes(n) {+ if (n >= 1e9) return (n / 1e9).toFixed(1) + ' GB';+ if (n >= 1e6) return (n / 1e6).toFixed(1) + ' MB';+ if (n >= 1e3) return Math.round(n / 1e3) + ' KB';+ return n + ' B';+ }+ function meter(label, used, max, fmt = String) {+ const pct = max ? Math.min(100, (used / max) * 100) : 0;+ const c = pct > 90 ? '#ff5c5c' : pct > 70 ? '#f0c14b' : '#6c5cff';+ return `<div style="margin-bottom:16px">+ <div class="row" style="justify-content:space-between;margin-bottom:4px">+ <span>${esc(label)}</span>+ <span class="muted" style="font-size:12px">${esc(fmt(used))} / ${max ? esc(fmt(max)) : '∞'}</span>+ </div>+ <div style="height:6px;border-radius:3px;background:var(--border);overflow:hidden">+ <div style="height:100%;width:${pct.toFixed(1)}%;background:${c};border-radius:3px;transition:width .4s"></div>+ </div></div>`;+ }+ const C = { free: '#6b7280', pro: '#6c5cff', team: '#00e5a0', enterprise: '#f0c14b' };+ const bc = C[plan] || '#6b7280';+ body.innerHTML = `+ <div style="display:grid;grid-template-columns:repeat(auto-fit,minmax(280px,1fr));gap:16px">+ <div class="card">+ <div class="row" style="justify-content:space-between;margin-bottom:16px">+ <h3 style="margin:0">Current plan</h3>+ <span style="padding:3px 12px;border-radius:999px;background:${bc}22;color:${bc};font-weight:600;font-size:13px;text-transform:capitalize">${esc(plan)}</span>+ </div>+ ${meter('Avatars', usage.avatar_count, quotas?.max_avatars)}+ ${meter('Storage', usage.total_bytes, quotas?.max_total_bytes, fmtBytes)}+ ${meter('MCP calls (24 h)', usage.mcp_calls_24h, quotas?.mcp_calls_per_day)}+ </div>+ <div class="card">+ <h3 style="margin:0 0 16px">Activity</h3>+ <div class="row" style="justify-content:space-between;padding:10px 0;border-bottom:1px solid var(--border)">+ <span class="muted">Agents</span><strong>${esc(String(usage.agent_count ?? 0))}</strong>+ </div>+ <div class="row" style="justify-content:space-between;padding:10px 0;border-bottom:1px solid var(--border)">+ <span class="muted">LLM calls this month</span><strong>${esc(String(usage.llm_calls_month ?? 0))}</strong>+ </div>+ <div class="row" style="justify-content:space-between;padding:10px 0">+ <span class="muted">MCP calls today</span><strong>${esc(String(usage.mcp_calls_24h ?? 0))}</strong>+ </div>+ ${plan === 'free' ? `<div style="margin-top:16px;padding-top:16px;border-top:1px solid var(--border)"><a class="btn" href="mailto:[email protected]?subject=Upgrade" style="display:block;text-align:center">Upgrade plan →</a></div>` : ''}+ </div>+ </div>+ `;}// ── Widgets ─────────────────────────────────────────────────────────────────@@ -2550,18 +2608,26 @@ async function renderAnimations(root) {rightCol.appendChild(rh);if (presets.length) {- const pl = document.createElement('p');- pl.className = 'muted';- pl.style.margin = '0 0 8px';- pl.textContent = 'Presets';- rightCol.appendChild(pl);- presetGridEl = document.createElement('div');- presetGridEl.className = 'preset-grid';+ const presetsHeader = document.createElement(‘div’);+ presetsHeader.className = ‘presets-header’;+ const pl = document.createElement(‘p’);+ pl.className = ‘muted’;+ pl.style.margin = ‘0’;+ pl.textContent = ‘Presets’;+ const addAllBtn = document.createElement(‘button’);+ addAllBtn.className = ‘btn sec add-all-btn’;+ addAllBtn.textContent = ‘Add all’;+ addAllBtn.addEventListener(‘click’, addAllPresets);+ presetsHeader.appendChild(pl);+ presetsHeader.appendChild(addAllBtn);+ rightCol.appendChild(presetsHeader);+ presetGridEl = document.createElement(‘div’);+ presetGridEl.className = ‘preset-grid’;rightCol.appendChild(presetGridEl);} else if (presetsError) {- const pe = document.createElement('div');- pe.className = 'anim-inline-err';- pe.style.marginBottom = '12px';+ const pe = document.createElement(‘div’);+ pe.className = ‘anim-inline-err’;+ pe.style.marginBottom = ‘12px’;pe.textContent = `Couldn’t load presets (${presetsError}).`;rightCol.appendChild(pe);}diff --git a/public/dashboard/index.html b/public/dashboard/index.htmlindex 7ea4c9e3b..debfb0000 100644--- a/public/dashboard/index.html+++ b/public/dashboard/index.html@@ -942,6 +942,57 @@font-size: 12px;min-height: 16px;}+ /* presets header row */+ .presets-header {+ display: flex;+ align-items: center;+ justify-content: space-between;+ margin-bottom: 10px;+ }+ .add-all-btn {+ padding: 4px 10px;+ font-size: 12px;+ border-radius: 7px;+ }+ /* drag handle + reorder indicators */+ .drag-handle {+ color: #555;+ cursor: grab;+ font-size: 14px;+ padding: 0 4px;+ user-select: none;+ flex-shrink: 0;+ }+ .drag-handle:active {+ cursor: grabbing;+ }+ .clip-row.dragging {+ opacity: 0.4;+ }+ .clip-row.drop-above {+ border-top: 2px solid var(--accent);+ }+ .clip-row.drop-below {+ border-bottom: 2px solid var(--accent);+ }+ /* inline clip rename */+ .clip-name {+ cursor: pointer;+ }+ .clip-name:hover {+ color: #fff;+ text-decoration: underline dotted;+ }+ .clip-name-input {+ padding: 2px 6px;+ font-size: 13px;+ width: 100%;+ min-width: 80px;+ }+ /* clip-row grid: handle name source loop actions */+ .clip-row {+ grid-template-columns: auto minmax(0, 1fr) auto auto auto;+ }.preview-stage {width: 100%;aspect-ratio: 1 / 1;diff --git a/public/features/features.js b/public/features/features.jsindex b864097ff..5c8a8f139 100644--- a/public/features/features.js+++ b/public/features/features.js@@ -127,7 +127,7 @@ function setupEmotionChips() {wrap.addEventListener('click', (e) => {const btn = e.target.closest('.emotion-chip');if (!btn) return;- const trigger = btn.dataset.emotion;+ const trigger = btn.getAttribute('data-emotion');if (!trigger) return;// Visual feedback (works even if agent hasn't booted yet)diff --git a/public/features/index.html b/public/features/index.htmlindex 8de94ce42..6ffb11fa5 100644--- a/public/features/index.html+++ b/public/features/index.html@@ -45,6 +45,7 @@<a href="/discover">Discover</a><a href="/features" class="active" aria-current="page">Features</a><a href="/widgets">Widgets</a>+ <a href="/my-agents" class="nav-my-agents" id="nav-my-agents" hidden>My Agents</a><a href="/dashboard" class="nav-dashboard">Dashboard</a><a href="/login" class="nav-sign-in">Sign in</a></nav>diff --git a/scripts/validate-agent-cards.mjs b/scripts/validate-agent-cards.mjsindex e0f77f3c6..add3f802c 100644--- a/scripts/validate-agent-cards.mjs+++ b/scripts/validate-agent-cards.mjs@@ -26,7 +26,10 @@ const validate = ajv.compile(schema);const targets = [resolve(repoRoot, 'public/.well-known/agent-registration.json')];try {- const tracked = execSync('git ls-files "*.agent-card.json"', { cwd: repoRoot, encoding: 'utf8' })+ const tracked = execSync('git ls-files "*.agent-card.json"', {+ cwd: repoRoot,+ encoding: 'utf8',+ }).split('\n').filter(Boolean).map((p) => resolve(repoRoot, p));diff --git a/specs/SECURITY.md b/specs/SECURITY.mdindex 04bb11da7..6eb056e69 100644--- a/specs/SECURITY.md+++ b/specs/SECURITY.md@@ -7,60 +7,70 @@ This document enumerates abuse vectors specific to 3D agent registration and lis## Vectors### V1 — Stolen / unlicensed model registration+A user pins someone else's GLB to IPFS and registers it as their agent.- **Mitigation:** card requires `model.license` (SPDX or URL). Validators MAY refuse `pass` for cards with `license: "unknown"`. DMCA takedown contact published in [security.txt](../public/.well-known/security.txt). Registry never serves the file directly — it points at IPFS.- **Status:** partial. License is declarative, not verified. Open: perceptual-hash blocklist for known stolen assets.### V2 — Mutable model swap+Card uses `https://` `model.uri` and operator swaps the GLB after registration.- **Mitigation:** `model.sha256` is mandatory; `<three-d-agent-badge>` and the resolver verify hash on every load. A swap surfaces as `unverified`. Spec SHOULD prefers `ipfs://` for prevention.- **Status:** mitigated for clients that verify; clients that ignore the badge are out of scope.### V3 — Fake "verified" claim+A site renders its own green pill claiming verification without checking.- **Mitigation:** the trust signal is the on-chain validation attestation from an allow-listed validator (see [VALIDATORS.md](VALIDATORS.md)) — not the badge UI. Consumers verify against ValidationRegistry directly or via the resolver.- **Status:** mitigated by design.### V4 — Validator key compromise+A validator's signing key leaks; attacker signs `pass` for malicious agents.- **Mitigation:** validator keys are dedicated, not personal wallets (per [VALIDATORS.md](VALIDATORS.md)). Compromise → `removeValidator(address)`. Past attestations from that validator SHOULD be treated as expired from the removal block onward by any indexer / resolver.- **Status:** policy in place; key custody is each validator's responsibility. Open: support EIP-712 attestations with explicit expiry timestamps so leaked keys self-expire.### V5 — Reputation gaming (sybil reviews)+Attacker mints many agents and posts inflated `ReputationRegistry` scores for a target.-- **Mitigation:** ReputationRegistry already enforces one score per (reviewer, agent). Beyond that, the recommended reputation surface for v1 is *measured* signals from validators (render success, load p95, A2A handshake), not user thumbs-up. See [3D_AGENT_CARD.md](3D_AGENT_CARD.md) §"Reputation".+- **Mitigation:** ReputationRegistry already enforces one score per (reviewer, agent). Beyond that, the recommended reputation surface for v1 is _measured_ signals from validators (render success, load p95, A2A handshake), not user thumbs-up. See [3D_AGENT_CARD.md](3D_AGENT_CARD.md) §"Reputation".- **Status:** partial. The on-chain primitive is sybil-resistant per-pair but not per-identity. Open: weight reviews by reviewer's own validation history.### V6 — Sybil registrations+Attacker mints thousands of agents to spam discovery surfaces.- **Mitigation:** registration costs gas — Base mainnet is the primary chain for this reason. The optional gasless path via paymaster is rate-limited per wallet/IP at the paymaster layer, not on-chain.- **Status:** mitigated on mainnet; paymaster rate limits are operational, not specified here.### V7 — IPFS unpinning+Pinned GLB is dropped by all gateways; card now points at dead content.- **Mitigation:** the registration flow pins to Storacha (paid). Validators MUST re-fetch on every attestation; a dropped file produces a `fail` on `manifest-integrity`, demoting the agent.- **Status:** mitigated during validator runs. Long-term: optional Filecoin deal storage for "permanent" tier agents.### V8 — NSFW / illegal model content+A registered agent's GLB contains illegal or platform-violating content.- **Mitigation:** pre-pin moderation hook in the registration UI (open). Post-registration takedowns happen at the gateway / discovery layer — the chain entry persists but the agent is hidden from `/explore` and the resolver returns `403 BLOCKED`.- **Status:** **OPEN**. No moderation hook is wired in [src/erc8004/register-ui.js](../src/erc8004/register-ui.js) yet. This is the highest-priority gap before opening public registration.### V9 — Supply-chain on the badge / resolver+Attacker compromises `3dagent.vercel.app` and serves a malicious badge bundle that lies about verification.- **Mitigation:** badge source is open in [src/erc8004/badge.js](../src/erc8004/badge.js); embedders SHOULD self-host or pin to a known SRI hash. Resolver responses are signed (open) so a tampered response can be detected client-side.- **Status:** partial. SRI guidance documented; resolver signing is open.### V10 — Card spoofing via tokenURI rewrite+Identity NFT owner updates `tokenURI` to point at a new card with different `model.sha256`.- **Mitigation:** every card update is an on-chain event. Indexers SHOULD show the version chain via the optional `previousVersion` field. Consumers MAY pin to a specific card CID rather than following the live `tokenURI`.diff --git a/specs/VALIDATORS.md b/specs/VALIDATORS.mdindex 8e99664f7..84447ccea 100644--- a/specs/VALIDATORS.md+++ b/specs/VALIDATORS.md@@ -4,7 +4,7 @@ The [ValidationRegistry](../contracts/src/ValidationRegistry.sol) only accepts a## Why an allow-list-A validation report says "I checked agent #N's model and it is sound." For that statement to carry weight, consumers need to know *who* signed it. Open writes would let any address claim "verified" status, collapsing the trust signal to zero. Allow-listing keeps the set small, named, and accountable.+A validation report says "I checked agent #N's model and it is sound." For that statement to carry weight, consumers need to know _who_ signed it. Open writes would let any address claim "verified" status, collapsing the trust signal to zero. Allow-listing keeps the set small, named, and accountable.## What a validator attests to@@ -12,13 +12,13 @@ A validator runs a deterministic suite over an agent's GLB and metadata, produceThe minimum suite for "verified" status:-| Suite | What it checks |-| ---------------------- | ----------------------------------------------------------------------- |-| `glb-schema` | File parses as valid glTF/GLB; all required chunks present. |-| `gltf-validator` | Khronos `gltf-validator` reports zero errors (warnings allowed). |-| `manifest-integrity` | Card `model.sha256` matches the bytes at `model.uri`. |-| `card-schema` | Card validates against [3D Agent Card v1](3D_AGENT_CARD.md). |-| `services-reachable` | Each `services[].endpoint` returns 2xx within 5s (informational). |+| Suite | What it checks |+| -------------------- | ----------------------------------------------------------------- |+| `glb-schema` | File parses as valid glTF/GLB; all required chunks present. |+| `gltf-validator` | Khronos `gltf-validator` reports zero errors (warnings allowed). |+| `manifest-integrity` | Card `model.sha256` matches the bytes at `model.uri`. |+| `card-schema` | Card validates against [3D Agent Card v1](3D_AGENT_CARD.md). |+| `services-reachable` | Each `services[].endpoint` returns 2xx within 5s (informational). |A `pass` verdict requires zero `fail` suites. `warn` is allowed.@@ -34,9 +34,9 @@ Each entry is `{ address, name, contact, addedAt, scope }`. `scope` is one of `g## Becoming a validator1. Open a PR adding your entry to [validators.json](../public/.well-known/validators.json) with:- - Operator name and a contactable email or HTTPS endpoint for disputes.- - The Ethereum address you will sign from. **Use a dedicated key**, not a personal wallet.- - A link to your runner's source (so suite determinism is auditable).+ - Operator name and a contactable email or HTTPS endpoint for disputes.+ - The Ethereum address you will sign from. **Use a dedicated key**, not a personal wallet.+ - A link to your runner's source (so suite determinism is auditable).2. Run the canonical suite over three reference agents (provided in the PR template) and post the resulting report CIDs in the PR. Maintainers reproduce the runs.3. On approval, the registry owner calls `addValidator(address)` and the PR is merged.diff --git a/tests/animations.test.js b/tests/animations.test.jsnew file mode 100644index 000000000..06473c1be--- /dev/null+++ b/tests/animations.test.js@@ -0,0 +1,169 @@+import { describe, it, expect, beforeAll } from 'vitest';+import { readFileSync, existsSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, resolve } from 'node:path';++// Polyfill required for three's AnimationClip.parse in node.+globalThis.self = globalThis;+globalThis.window = globalThis;+globalThis.document = { createElementNS: () => ({}) };++const __dirname = dirname(fileURLToPath(import.meta.url));+const ROOT = resolve(__dirname, '..');+const MANIFEST = resolve(ROOT, 'public/animations/manifest.json');+const CLIPS_DIR = resolve(ROOT, 'public/animations/clips');++// Canonical Avaturn bone set — strip prefix to match track target names.+// Derived from cz.glb (scripts/build-animations.mjs reference rig).+const AVATURN_BONES = new Set([+ 'Hips',+ 'LeftUpLeg',+ 'LeftLeg',+ 'LeftFoot',+ 'LeftToeBase',+ 'Spine',+ 'Spine1',+ 'Spine2',+ 'Neck',+ 'Head',+ 'LeftShoulder',+ 'LeftArm',+ 'LeftForeArm',+ 'LeftHand',+ 'LeftHandIndex1',+ 'LeftHandIndex2',+ 'LeftHandIndex3',+ 'LeftHandMiddle1',+ 'LeftHandMiddle2',+ 'LeftHandMiddle3',+ 'LeftHandPinky1',+ 'LeftHandPinky2',+ 'LeftHandPinky3',+ 'LeftHandRing1',+ 'LeftHandRing2',+ 'LeftHandRing3',+ 'LeftHandThumb1',+ 'LeftHandThumb2',+ 'LeftHandThumb3',+ 'RightShoulder',+ 'RightArm',+ 'RightForeArm',+ 'RightHand',+ 'RightHandIndex1',+ 'RightHandIndex2',+ 'RightHandIndex3',+ 'RightHandMiddle1',+ 'RightHandMiddle2',+ 'RightHandMiddle3',+ 'RightHandPinky1',+ 'RightHandPinky2',+ 'RightHandPinky3',+ 'RightHandRing1',+ 'RightHandRing2',+ 'RightHandRing3',+ 'RightHandThumb1',+ 'RightHandThumb2',+ 'RightHandThumb3',+ 'RightUpLeg',+ 'RightLeg',+ 'RightFoot',+ 'RightToeBase',+]);++let manifest;+let AnimationClip;++beforeAll(async () => {+ expect(existsSync(MANIFEST), `manifest not found — run npm run build:animations`).toBe(true);+ manifest = JSON.parse(readFileSync(MANIFEST, 'utf8'));+ ({ AnimationClip } = await import('three'));+});++describe('animation manifest', () => {+ it('has at least one clip', () => {+ expect(manifest.length).toBeGreaterThan(0);+ });++ it('every entry has required fields', () => {+ for (const entry of manifest) {+ expect(entry.name, `entry missing name`).toBeTruthy();+ expect(entry.url, `${entry.name} missing url`).toBeTruthy();+ expect(entry.label, `${entry.name} missing label`).toBeTruthy();+ expect(typeof entry.loop, `${entry.name} loop must be boolean`).toBe('boolean');+ }+ });++ it('every url points at an existing file', () => {+ for (const entry of manifest) {+ const file = resolve(ROOT, 'public', entry.url.replace(/^\//, ''));+ expect(existsSync(file), `${entry.name}: file not found at ${entry.url}`).toBe(true);+ }+ });+});++describe('animation clips', () => {+ it('every clip parses as a valid AnimationClip', () => {+ for (const entry of manifest) {+ const file = resolve(ROOT, 'public', entry.url.replace(/^\//, ''));+ const json = JSON.parse(readFileSync(file, 'utf8'));+ const clip = AnimationClip.parse(json);++ expect(clip.name, `${entry.name}: clip.name`).toBe(entry.name);+ expect(clip.duration, `${entry.name}: duration must be > 0`).toBeGreaterThan(0);+ expect(clip.tracks.length, `${entry.name}: must have tracks`).toBeGreaterThan(0);+ }+ });++ it('every track target resolves to a bone in the Avaturn reference rig', () => {+ const mismatches = [];+ for (const entry of manifest) {+ const file = resolve(ROOT, 'public', entry.url.replace(/^\//, ''));+ const json = JSON.parse(readFileSync(file, 'utf8'));+ const clip = AnimationClip.parse(json);++ for (const track of clip.tracks) {+ const boneName = track.name.split('.')[0];+ if (!AVATURN_BONES.has(boneName)) {+ mismatches.push(`${entry.name}: unknown bone "${boneName}"`);+ }+ }+ }+ expect(mismatches, mismatches.join('\n')).toHaveLength(0);+ });++ it('no track contains NaN keyframe values', () => {+ const nanTracks = [];+ for (const entry of manifest) {+ const file = resolve(ROOT, 'public', entry.url.replace(/^\//, ''));+ const json = JSON.parse(readFileSync(file, 'utf8'));+ const clip = AnimationClip.parse(json);++ for (const track of clip.tracks) {+ for (const v of track.values) {+ if (Number.isNaN(v)) {+ nanTracks.push(`${entry.name} / ${track.name}`);+ break;+ }+ }+ }+ }+ expect(nanTracks, `NaN found in: ${nanTracks.join(', ')}`).toHaveLength(0);+ });++ it('Hips.position values are in meter range (< 10m)', () => {+ for (const entry of manifest) {+ const file = resolve(ROOT, 'public', entry.url.replace(/^\//, ''));+ const json = JSON.parse(readFileSync(file, 'utf8'));+ const clip = AnimationClip.parse(json);++ const hipsPos = clip.tracks.find((t) => t.name === 'Hips.position');+ if (!hipsPos) continue;++ const maxVal = Math.max(...hipsPos.values.map(Math.abs));+ expect(+ maxVal,+ `${entry.name}: Hips.position max=${maxVal.toFixed(2)}m — avatar will float (scale issue)`,+ ).toBeLessThan(10);+ }+ });+});diff --git a/tests/billing.test.js b/tests/billing.test.jsnew file mode 100644index 000000000..58914c34b--- /dev/null+++ b/tests/billing.test.js@@ -0,0 +1,63 @@+import { describe, it, expect } from 'vitest';+import { readFileSync } from 'node:fs';+import { fileURLToPath } from 'node:url';+import { dirname, resolve } from 'node:path';++const __dirname = dirname(fileURLToPath(import.meta.url));+const repoRoot = resolve(__dirname, '..');+const p = (...parts) => resolve(repoRoot, ...parts);++describe('billing — vercel.json routing', () => {+ const vercel = JSON.parse(readFileSync(p('vercel.json'), 'utf8'));+ const routes = vercel.routes || [];++ it('routes /api/billing/summary to the serverless endpoint', () => {+ const r = routes.find((x) => x.src === '/api/billing/summary');+ expect(r).toBeTruthy();+ expect(r.dest).toBe('/api/billing/summary');+ });+});++describe('billing — dashboard tab', () => {+ const dashjs = readFileSync(p('public/dashboard/dashboard.js'), 'utf8');++ it('dashboard.js exports a billingSummary api method', () => {+ expect(dashjs).toContain('billingSummary');+ });++ it('renderBilling is async and fetches billing data', () => {+ expect(dashjs).toContain('async function renderBilling');+ expect(dashjs).toContain('/api/billing/summary');+ });++ it('billing tab renders quota meters', () => {+ expect(dashjs).toContain('mcp_calls_24h');+ expect(dashjs).toContain('total_bytes');+ expect(dashjs).toContain('avatar_count');+ });+});++describe('billing — endpoint file', () => {+ const src = readFileSync(p('api/billing/summary.js'), 'utf8');++ it('exports a default handler', () => {+ expect(src).toContain('export default');+ });++ it('queries plan_quotas joined with users', () => {+ expect(src).toContain('plan_quotas');+ expect(src).toContain('user.id');+ });++ it('returns usage fields for avatars, agents, mcp, llm', () => {+ expect(src).toContain('avatar_count');+ expect(src).toContain('agent_count');+ expect(src).toContain('mcp_calls_24h');+ expect(src).toContain('llm_calls_month');+ });++ it('requires authentication', () => {+ expect(src).toContain('getSessionUser');+ expect(src).toContain('401');+ });+});