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
feat(api): motion signatures as a public API
nirholasba6bc5f35e77
diff --git a/api/animations/signatures.js b/api/animations/signatures.jsnew file mode 100644index 000000000..d2c3126f8--- /dev/null+++ b/api/animations/signatures.js@@ -0,0 +1,166 @@+// GET /api/animations/signatures+//+// The measured motion signature of every baked animation clip, as an API. The+// data is scripts/build-motion-signatures.mjs output (public/animations/+// signatures.json): energy, tempo, regional shares, loop seam, travel and the+// derived flags, measured from keyframes rather than authored by hand. This+// endpoint adds the three questions callers keep computing client-side:+//+// ?clip=<name> one clip's signature + plain-language line+// ?clip=<name>&slot=<slot> does this clip FIT that runtime slot?+// ?similar=<name>&limit=<1..20> nearest clips by measured motion+//+// and a filterable listing for everything else:+//+// ?overlay=true&loop=clean&lead=arms&band=lively+// &sort=energy|tempo|duration|upperShare|travel&order=asc|desc+// &limit=<1..200>&offset=<n>+//+// Static measurement only: no database, no session, no per-caller state. It+// changes exactly when a deploy ships re-measured clips, so it caches like+// /api/play/solver does.++import { readFileSync } from 'node:fs';+import { cors, json, method, wrap, error, rateLimited } from '../_lib/http.js';+import { limits, clientIp } from '../_lib/rate-limit.js';+import {+ describe,+ energyBand,+ leadRegion,+ similarTo,+ slotFit,+ REGIONS,+} from '../../src/runtime/motion-signature.js';+import { SLOTS, DEFAULT_ANIMATION_MAP } from '../../src/runtime/animation-slots.js';++// One read per process. The file ships inside the image, so a missing or+// unparsable index is a build defect, not a runtime condition to soften.+const INDEX = JSON.parse(+ readFileSync(new URL('../../public/animations/signatures.json', import.meta.url), 'utf8'),+);++const SORT_KEYS = ['energy', 'tempo', 'duration', 'upperShare', 'travel', 'beat', 'balance'];+const BANDS = ['still', 'calm', 'gentle', 'lively', 'explosive'];+const CACHE = { 'cache-control': 'public, max-age=300, s-maxage=3600, stale-while-revalidate=86400' };++/** The signature plus the derived words every consumer ends up recomputing. */+function present(sig) {+ return { ...sig, band: energyBand(sig), lead: sig.lead || leadRegion(sig.regions), description: describe(sig) };+}++/** Parse "true"/"false"/null. Anything else reads as null (no filter). */+function boolParam(v) {+ if (v === 'true') return true;+ if (v === 'false') return false;+ return null;+}++export default wrap(async (req, res) => {+ if (cors(req, res, { methods: 'GET,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['GET'])) return;++ const rl = await limits.publicIp(clientIp(req));+ if (!rl.success) return rateLimited(res, rl);++ const url = new URL(req.url, 'http://localhost');+ const q = url.searchParams;++ // ── Similar-clips mode ────────────────────────────────────────────────+ const similar = q.get('similar');+ if (similar) {+ if (!INDEX.clips[similar]) {+ return error(res, 404, 'unknown_clip', `No signature for "${similar}". GET this endpoint with no parameters to list every measured clip.`);+ }+ const limitRaw = Number.parseInt(q.get('limit') ?? '5', 10);+ const limit = Number.isFinite(limitRaw) ? Math.max(1, Math.min(20, limitRaw)) : 5;+ return json(res, 200, {+ version: INDEX.version,+ clip: similar,+ similar: similarTo(similar, INDEX.clips, limit).map((m) => ({+ clip: m.clip,+ distance: Math.round(m.distance * 1000) / 1000,+ band: energyBand(m.signature),+ description: describe(m.signature),+ })),+ }, CACHE);+ }++ // ── Single-clip mode, with optional slot-fit verdict ─────────────────+ const clip = q.get('clip');+ if (clip) {+ const sig = INDEX.clips[clip];+ if (!sig) {+ return error(res, 404, 'unknown_clip', `No signature for "${clip}". GET this endpoint with no parameters to list every measured clip.`);+ }+ const slot = q.get('slot');+ let fit;+ if (slot !== null) {+ if (!SLOTS.includes(slot)) {+ return error(res, 400, 'unknown_slot', `"${slot}" is not a runtime slot. Slots: ${SLOTS.join(', ')}.`);+ }+ fit = { slot, defaultClip: DEFAULT_ANIMATION_MAP[slot] ?? slot, ...slotFit(slot, sig) };+ }+ return json(res, 200, { version: INDEX.version, signature: present(sig), ...(fit ? { fit } : {}) }, CACHE);+ }++ // A slot without a clip is answerable too: report the fit of the slot's+ // own default, which is the question "is this slot healthy right now?".+ const slotOnly = q.get('slot');+ if (slotOnly !== null) {+ if (!SLOTS.includes(slotOnly)) {+ return error(res, 400, 'unknown_slot', `"${slotOnly}" is not a runtime slot. Slots: ${SLOTS.join(', ')}.`);+ }+ const defaultClip = DEFAULT_ANIMATION_MAP[slotOnly] ?? slotOnly;+ const sig = INDEX.clips[defaultClip];+ return json(res, 200, {+ version: INDEX.version,+ fit: { slot: slotOnly, defaultClip, ...(sig ? slotFit(slotOnly, sig) : { level: 'warn', message: `The default clip "${defaultClip}" has no signature.` }) },+ ...(sig ? { signature: present(sig) } : {}),+ }, CACHE);+ }++ // ── Listing mode with filters ─────────────────────────────────────────+ const overlay = boolParam(q.get('overlay'));+ const anchored = boolParam(q.get('anchored'));+ const loopClean = q.get('loop') === 'clean' ? true : null;+ const lead = q.get('lead');+ if (lead !== null && !REGIONS.includes(lead)) {+ return error(res, 400, 'unknown_region', `"${lead}" is not a body region. Regions: ${REGIONS.join(', ')}.`);+ }+ const band = q.get('band');+ if (band !== null && !BANDS.includes(band)) {+ return error(res, 400, 'unknown_band', `"${band}" is not an energy band. Bands: ${BANDS.join(', ')}.`);+ }++ let rows = Object.values(INDEX.clips);+ if (overlay !== null) rows = rows.filter((s) => s.overlay === overlay);+ if (anchored !== null) rows = rows.filter((s) => s.anchored === anchored);+ if (loopClean !== null) rows = rows.filter((s) => s.loopClean === true);+ if (lead !== null) rows = rows.filter((s) => s.lead === lead);+ if (band !== null) rows = rows.filter((s) => energyBand(s) === band);++ const sortKey = q.get('sort');+ if (sortKey !== null && !SORT_KEYS.includes(sortKey)) {+ return error(res, 400, 'unknown_sort', `"${sortKey}" is not sortable. Sort keys: ${SORT_KEYS.join(', ')}.`);+ }+ if (sortKey) {+ const dir = q.get('order') === 'asc' ? 1 : -1;+ rows = rows.slice().sort((a, b) => dir * ((a[sortKey] ?? 0) - (b[sortKey] ?? 0)));+ } else {+ rows = rows.slice().sort((a, b) => a.clip.localeCompare(b.clip));+ }++ const total = rows.length;+ const limitRaw = Number.parseInt(q.get('limit') ?? '200', 10);+ const limit = Number.isFinite(limitRaw) ? Math.max(1, Math.min(200, limitRaw)) : 200;+ const offsetRaw = Number.parseInt(q.get('offset') ?? '0', 10);+ const offset = Number.isFinite(offsetRaw) ? Math.max(0, offsetRaw) : 0;++ return json(res, 200, {+ version: INDEX.version,+ count: INDEX.count,+ total,+ offset,+ clips: rows.slice(offset, offset + limit).map(present),+ }, CACHE);+});diff --git a/docs/api-reference.md b/docs/api-reference.mdindex eb73853a0..2c50774e5 100644--- a/docs/api-reference.md+++ b/docs/api-reference.md@@ -4019,6 +4019,52 @@ Returns `{ "clips": [], "total": 0 }` until the library has been published, so c---+## Motion Signatures API++```+GET /api/animations/signatures+```++The measured motion signature of every baked clip in the starter library: energy, tempo, per-region motion shares, loop-seam cleanliness, root travel, and the derived flags (`overlay`, `anchored`, `loopClean`, `static`). Nothing is authored by hand; `scripts/build-motion-signatures.mjs` measures the keyframes and this endpoint serves the result with the plain-language derivations (`band`, `description`) added. No auth. CORS open. Edge-cached for 5 minutes.++Use it to pick clips by what they do rather than by name: "a calm, arms-led loop that survives as an upper-body overlay" is a query here, not an afternoon of previewing.++**Modes** (mutually exclusive; listing is the default)++| Query | Answer |+| ----- | ------ |+| `?clip=<name>` | One clip's full signature. |+| `?clip=<name>&slot=<slot>` | The signature plus a fit verdict: can this clip play in that runtime slot? `fit.level` is `ok` or `warn`, and `fit.message` says why in plain language (open loop seam, motion below the waist, held pose, root drift). |+| `?slot=<slot>` | The health of the slot's own default clip: the question "is this slot fine right now?". |+| `?similar=<name>&limit=<1..20>` | The nearest clips by measured motion distance, closest first. |++**Listing filters** (combine freely)++| Param | Values |+| ----- | ------ |+| `overlay` | `true` / `false`: survives the upper-body strip on /walk. |+| `loop` | `clean`: last frame meets the first, no visible snap. |+| `anchored` | `true` / `false`: ends where it started. |+| `lead` | `head`, `arms`, `torso`, `root`, `legs`: which region carries the motion. |+| `band` | `still`, `calm`, `gentle`, `lively`, `explosive`. |+| `sort` | `energy`, `tempo`, `duration`, `upperShare`, `travel`, `beat`, `balance` (+ `order=asc|desc`, default desc). |+| `limit`, `offset` | Paging, `limit` 1 to 200 (default 200). |++```bash+# Calm, clean-looping clips an agent can idle on+curl 'https://three.ws/api/animations/signatures?loop=clean&band=calm'++# Would av-waiting hold the fidget loop? (No: its last frame misses its first.)+curl 'https://three.ws/api/animations/signatures?clip=av-waiting&slot=fidget'++# Five clips that move like "wave"+curl 'https://three.ws/api/animations/signatures?similar=wave&limit=5'+```++**Errors:** `404 unknown_clip`, `400 unknown_slot` / `unknown_region` / `unknown_band` / `unknown_sort`, each naming the valid values. The same data powers the `animation_signature` and `find_similar_animations` MCP tools and the /gestures page, so all three always agree.++---+## Config API```diff --git a/tests/api/animations-signatures.test.js b/tests/api/animations-signatures.test.jsnew file mode 100644index 000000000..9a4455d8f--- /dev/null+++ b/tests/api/animations-signatures.test.js@@ -0,0 +1,172 @@+// Unit tests for GET /api/animations/signatures, the measured motion index as+// an API. The measurements themselves are proven in tests/motion-signature.test.js;+// these cover the HTTP contract: single-clip and slot-fit modes, the similar+// ranking, list filters, and the guarantee that the served signature is the+// shipped index's own row plus derived words, never a reshaped copy.++import { describe, it, expect, vi, beforeEach } from 'vitest';+import { readFileSync } from 'node:fs';+import { resolve } from 'node:path';++const rlState = { success: true, limit: 60, remaining: 59, reset: 0 };+vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { publicIp: vi.fn(async () => rlState) },+ clientIp: vi.fn(() => '127.0.0.1'),+}));++const handler = (await import('../../api/animations/signatures.js')).default;+const { slotFit, similarTo, describe: describeSig } = await import('../../src/runtime/motion-signature.js');+const { SLOTS, DEFAULT_ANIMATION_MAP } = await import('../../src/runtime/animation-slots.js');++const ROOT = resolve(import.meta.dirname, '..', '..');+const INDEX = JSON.parse(readFileSync(resolve(ROOT, 'public/animations/signatures.json'), 'utf8'));++function mockRes() {+ const chunks = [];+ return {+ statusCode: 0,+ headers: {},+ setHeader(k, v) { this.headers[String(k).toLowerCase()] = v; },+ getHeader(k) { return this.headers[String(k).toLowerCase()]; },+ writeHead(status, headers) {+ this.statusCode = status;+ for (const [k, v] of Object.entries(headers || {})) this.setHeader(k, v);+ return this;+ },+ end(body) { if (body) chunks.push(body); return this; },+ get body() { return chunks.join(''); },+ get parsed() { return JSON.parse(chunks.join('')); },+ };+}++const mockReq = (url, method = 'GET') => ({+ method,+ url,+ headers: { host: 'three.ws' },+ socket: { remoteAddress: '127.0.0.1' },+});++async function get(url) {+ const res = mockRes();+ await handler(mockReq(url), res);+ return res;+}++beforeEach(() => {+ rlState.success = true;+});++describe('GET /api/animations/signatures: single clip', () => {+ it('serves the shipped row for a clip, with the derived words added', async () => {+ const res = await get('/api/animations/signatures?clip=idle');+ expect(res.statusCode).toBe(200);+ const sig = res.parsed.signature;+ // Every measured field survives to the wire unchanged.+ for (const [k, v] of Object.entries(INDEX.clips.idle)) expect(sig[k]).toEqual(v);+ expect(sig.description).toBe(describeSig(INDEX.clips.idle));+ expect(typeof sig.band).toBe('string');+ });++ it('404s an unknown clip with a pointer to the listing', async () => {+ const res = await get('/api/animations/signatures?clip=not-a-clip');+ expect(res.statusCode).toBe(404);+ expect(res.parsed.error).toBe('unknown_clip');+ expect(res.headers['cache-control']).toBe('no-store');+ });+});++describe('GET /api/animations/signatures: slot fit', () => {+ it('answers clip+slot with exactly what slotFit computes', async () => {+ const res = await get('/api/animations/signatures?clip=wave&slot=wave');+ expect(res.statusCode).toBe(200);+ const expected = slotFit('wave', INDEX.clips.wave);+ expect(res.parsed.fit.level).toBe(expected.level);+ expect(res.parsed.fit.message).toBe(expected.message);+ expect(res.parsed.fit.slot).toBe('wave');+ });++ it('answers a bare slot with the health of its own default clip', async () => {+ const res = await get('/api/animations/signatures?slot=fidget');+ expect(res.statusCode).toBe(200);+ expect(res.parsed.fit.defaultClip).toBe(DEFAULT_ANIMATION_MAP.fidget);+ // The defaults are held to 'ok' by tests/motion-signature.test.js, so a+ // warn here means this endpoint and the runtime disagree about the map.+ expect(res.parsed.fit.level).toBe('ok');+ });++ it('rejects an unknown slot and names the real ones', async () => {+ const res = await get('/api/animations/signatures?clip=wave&slot=frolic');+ expect(res.statusCode).toBe(400);+ expect(res.parsed.error).toBe('unknown_slot');+ for (const slot of SLOTS.slice(0, 3)) expect(res.parsed.error_description).toContain(slot);+ });+});++describe('GET /api/animations/signatures: similar', () => {+ it('ranks neighbors exactly the way the runtime helper does', async () => {+ const res = await get('/api/animations/signatures?similar=wave&limit=3');+ expect(res.statusCode).toBe(200);+ const expected = similarTo('wave', INDEX.clips, 3).map((m) => m.clip);+ expect(res.parsed.similar.map((m) => m.clip)).toEqual(expected);+ expect(res.parsed.similar).toHaveLength(3);+ });++ it('clamps the limit into 1..20', async () => {+ const res = await get('/api/animations/signatures?similar=wave&limit=999');+ expect(res.parsed.similar.length).toBeLessThanOrEqual(20);+ });+});++describe('GET /api/animations/signatures: listing', () => {+ it('lists every measured clip by default', async () => {+ const res = await get('/api/animations/signatures');+ expect(res.statusCode).toBe(200);+ expect(res.parsed.total).toBe(Object.keys(INDEX.clips).length);+ expect(res.parsed.clips.length).toBe(res.parsed.total);+ expect(res.headers['cache-control']).toContain('public');+ });++ it('filters are conjunctive and honest against the index', async () => {+ const res = await get('/api/animations/signatures?overlay=true&loop=clean&lead=arms');+ for (const c of res.parsed.clips) {+ expect(c.overlay).toBe(true);+ expect(c.loopClean).toBe(true);+ expect(c.lead).toBe('arms');+ }+ const manual = Object.values(INDEX.clips).filter((s) => s.overlay && s.loopClean && s.lead === 'arms');+ expect(res.parsed.total).toBe(manual.length);+ });++ it('sorts by any documented key in either direction', async () => {+ const res = await get('/api/animations/signatures?sort=energy&order=asc&limit=5');+ const energies = res.parsed.clips.map((c) => c.energy);+ expect(energies).toEqual(energies.slice().sort((a, b) => a - b));+ });++ it('rejects an unknown sort key instead of silently ignoring it', async () => {+ const res = await get('/api/animations/signatures?sort=vibes');+ expect(res.statusCode).toBe(400);+ expect(res.parsed.error).toBe('unknown_sort');+ });++ it('paginates without losing anyone', async () => {+ const a = await get('/api/animations/signatures?limit=50');+ const b = await get('/api/animations/signatures?limit=50&offset=50');+ const seen = new Set([...a.parsed.clips, ...b.parsed.clips].map((c) => c.clip));+ expect(seen.size).toBe(Math.min(100, a.parsed.total));+ });+});++describe('GET /api/animations/signatures: envelope', () => {+ it('rejects non-GET', async () => {+ const res = mockRes();+ await handler(mockReq('/api/animations/signatures', 'POST'), res);+ expect(res.statusCode).toBe(405);+ });++ it('429s when the public bucket is exhausted', async () => {+ rlState.success = false;+ const res = await get('/api/animations/signatures');+ expect(res.statusCode).toBe(429);+ });+});