Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
test(render): cover the animate endpoint and settle the GLB loader
nirholasba3316d07d4d
diff --git a/api/_lib/render-glb.js b/api/_lib/render-glb.jsindex 183107577..2fe7cbb52 100644--- a/api/_lib/render-glb.js+++ b/api/_lib/render-glb.js@@ -297,7 +297,10 @@ export async function renderGlbToPng(opts = {}) {if (!opts.glbUrl || typeof opts.glbUrl !== 'string') {throw Object.assign(new Error('glbUrl required'), { status: 400, code: 'invalid_args' });}- if (env.RENDER_CPU_LANE !== 'off') {+ // Read from process.env rather than ./env.js: that module exposes an+ // explicit allowlist of known keys, and an operational kill switch has to+ // work the moment it is set on the service, with no code change.+ if (process.env.RENDER_CPU_LANE !== 'off') {try {const { renderGlbToPngCpu } = await import('./render-cpu.js');const png = await renderGlbToPngCpu(opts);diff --git a/packages/motion/README.md b/packages/motion/README.mdindex c34762db9..1eb10064b 100644--- a/packages/motion/README.md+++ b/packages/motion/README.md@@ -1,12 +1,65 @@-# @three-ws/motion+<p align="center">+ <a href="https://three.ws"><img src="https://three.ws/three-ws-mcp-icon.svg" width="72" height="72" alt="three.ws" /></a>+</p>-**Text and structure into full-body 3D animation.** A Motion Score in, a-three.js `AnimationClip` out: forward and inverse kinematics, balance, ground-contact, and secondary motion, in plain JavaScript with no model, no GPU, and no-dependencies.+<h1 align="center">@three-ws/motion</h1>-The same score always compiles to the same clip, byte for byte, which is what-makes a motion cacheable, diffable, and safe to regenerate.+<p align="center"><strong>Text and structure to full-body 3D animation. No motion capture, no model weights, no renderer.</strong></p>++<p align="center">+ <a href="https://www.npmjs.com/package/@three-ws/motion"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/motion?logo=npm&color=cb3837"></a>+ <a href="https://www.npmjs.com/package/@three-ws/motion"><img alt="downloads" src="https://img.shields.io/npm/dm/@three-ws/motion?color=cb3837"></a>+ <img alt="license" src="https://img.shields.io/npm/l/@three-ws/motion?color=3b82f6">+ <img alt="node" src="https://img.shields.io/node/v/@three-ws/motion?color=339933&logo=node.js">+ <img alt="dependencies" src="https://img.shields.io/badge/dependencies-0-3b82f6">+</p>++<p align="center">+ <a href="#install">Install</a> ·+ <a href="#quick-start">Quick start</a> ·+ <a href="#the-motion-score">Motion Score</a> ·+ <a href="#api">API</a> ·+ <a href="#cli">CLI</a> ·+ <a href="#how-it-works">How it works</a> ·+ <a href="https://three.ws/motion">three.ws/motion</a>+</p>++---++Every other way to get a new animation needs data you do not have: a motion+capture stage, a licensed clip library, or a diffusion model trained on one.+This package needs a sentence.++```js+import { motionFromText } from '@three-ws/motion';++const { clip } = motionFromText('wave hello twice, excitedly');+// clip is a three.js AnimationClip.toJSON() document, ready to play+```++It works because a human body is a solved kinematics problem. Give a solver the+places a body should be at a few moments in time, plus how it should get there,+and it can produce the joint rotations for every frame between, with the feet on+the floor, the weight over them, and the shoulders doing what shoulders do. The+hard part was never the math, it was the authoring format, and that is what a+**Motion Score** is: an animation written in anatomy and timing rather than in+quaternions, which means a language model can write one and a person can read+the diff.++## Why++- **Nothing to download.** No `.fbx` library, no weights, no GPU. Zero+ dependencies, and it runs in a browser tab, a Node script, or a serverless+ handler from the same code path.+- **Deterministic.** The same score compiles to the same clip, byte for byte,+ forever. Cacheable, diffable, and regression-testable.+- **It plays on anything humanoid.** The output is standard clip JSON with+ canonical bone names, so it retargets onto Mixamo, Avaturn, VRM, Ready Player+ Me, Unreal and Daz rigs through any retargeter that speaks them.+- **It knows about bodies.** Feet stay on the floor, the centre of mass stays+ over the support base, the clavicle helps a long reach, and the whole thing+ breathes. Those are the four things that separate a synthesized motion from a+ mannequin changing shape.## Install@@ -14,99 +67,219 @@ makes a motion cacheable, diffable, and safe to regenerate.npm install @three-ws/motion```-## Two entry points cover almost every use+## Quick start++### From a prompt```jsimport { motionFromText } from '@three-ws/motion';+import { AnimationClip, AnimationMixer } from 'three';++const { clip, score, matched } = motionFromText('sit down heavily');++const mixer = new AnimationMixer(avatar);+mixer.clipAction(AnimationClip.parse(clip)).play();+```++`motionFromText` uses the built-in lane, which recognizes about twenty actions+with their modifiers (side, direction, manner, repetition) and needs no network+and no API key. It throws `code: 'unrecognized_motion'` for anything outside+that vocabulary, which is the signal to hand the prompt to a model instead.++### From a model++Give any tool-calling model `scoreSchema()` and let it author the score. Every+enum in the schema is generated from the same vocabulary the solver reads, so a+model cannot invent a word the compiler will reject.++```js+import { compileScore, scoreSchema } from '@three-ws/motion';++const score = await yourModel.json({+ system: 'Write a Motion Score for the described movement.',+ user: 'She looks up from her desk, considers it, then shakes her head slowly.',+ schema: scoreSchema(),+});-const { clip, score, matched } = motionFromText('wave hello twice, excitedly');-// clip -> an AnimationClip document, ready for THREE.AnimationClip.parse()-// score -> the Motion Score that produced it, so you can edit and recompile+const { clip, warnings } = compileScore(score);```+### By hand+```jsimport { compileScore } from '@three-ws/motion';-const { clip, warnings } = compileScore(myScore, {- idle: true, // layer breathing and micro-sway on top (default)- rootMotion: true, // emit the hip translation track (default)- fingers: true, // emit the finger bones (default)+const { clip } = compileScore({+ name: 'thinking it over',+ beats: [+ { label: 'still', posture: 'easy', hold: 0.4 },+ {+ label: 'hand to chin',+ posture: 'easy',+ arms: { right: { at: 'chin', palm: 'in', hand: 'loose', elbow: 'down' } },+ gaze: 'aside',+ face: 'focused',+ in: 0.5,+ hold: 1.2,+ },+ { label: 'decides', posture: 'proud', gaze: 'forward', face: 'smile', in: 0.45, hold: 0.5 },+ ],});```-`motionFromText` runs the **model-free lane**: it matches the prompt against a-known action vocabulary. When it does not recognise an action it throws, and the-message lists what it *does* know, so a caller can escalate to a model or tell-the user something useful instead of silently producing a T-pose.+## The Motion Score++A score is a list of **beats**. A beat is where the body is at one instant, how+long it takes to get there (`in`), and how long it stays (`hold`). Nothing in it+is a bone name.++```json+{+ "name": "greeting",+ "loop": false,+ "effort": "playful",+ "beats": [+ { "posture": "easy", "hold": 0.2 },+ {+ "label": "hand up",+ "posture": "easy",+ "arms": { "right": { "at": "overhead", "up": -0.08, "palm": "forward", "hand": "open", "elbow": "out" } },+ "gaze": "forward",+ "face": "smile",+ "in": 0.36,+ "hold": 0.1+ },+ { "label": "lower", "arms": { "right": { "at": "side", "hand": "relaxed" } }, "in": 0.5, "hold": 0.2 }+ ]+}+```++| Field | What it says |+| --------- | ----------------------------------------------------------------------------------------------- |+| `posture` | a whole-body shape (`stand`, `crouch`, `sit`, `lunge`, `bow`, `tiptoe`, …) that seeds the rest |+| `root` | hip `height` as a fraction of standing, plus `forward` / `side` travel, `rise`, and `turn` |+| `torso` | `lean`, `twist`, `sideBend`, in degrees, distributed along the spine |+| `arms` | per side: an anchor (`chin`, `sternum`, `overhead`, `thigh`, `front`, …), offsets, palm, hand |+| `legs` | a `stance`, or per-foot placement with `plant` (`flat`, `toe`, `heel`, `lift`) |+| `gaze` | a named look, or explicit `yaw` / `pitch` |+| `face` | a named expression, mapped to ARKit blendshape weights |+| `effort` | how it is performed: `weight`, `time`, `flow`, or a preset like `sharp` / `weary` / `sustained` |++**Effort is not decoration.** It picks the easing curve, scales the travel time,+and sets how far a limb overshoots before it settles, which is what makes the+same three shapes read as a wave, a swat, or a salute.++The full field reference is+[specs/MOTION_SCORE.md](https://github.com/nirholas/three.ws/blob/main/specs/MOTION_SCORE.md).++## API++| Export | What it does |+| ------------------------------- | ------------------------------------------------------------------------ |+| `motionFromText(prompt, opts)` | prompt to `{ clip, score, matched, warnings }`, no model needed |+| `compileScore(score, opts)` | score to `{ clip, score, warnings }` |+| `validateScore(input)` | `{ ok, score, error }` with the exact path that failed |+| `normalizeScore(input)` | the same, but throws |+| `scoreSchema()` | JSON Schema for a tool call, generated from the live vocabulary |+| `motionCapabilities()` | schema, limits, and known actions in one object |+| `composeScore(prompt, opts)` | the model-free lane on its own, returning a raw score |+| `describeScore(score)` | one readable line: duration, beats, and what happens |+| `solveBeat(beat)` | one beat to a solved `Pose` |+| `buildClip(keys, opts)` | solved poses to a clip document |++`compileScore` options: `idle` (breathing and micro-sway, default on),+`rootMotion` (the hip translation track, default on, turn off for a clip that+must play in place), `fingers` (default on).++The kinematics layer is exported too, for callers building an editor or a+different authoring format:```js-import { motionCapabilities } from '@three-ws/motion';-motionCapabilities(); // what this lane can do, for a capability check or a UI+import { restPose, solveArm, solveLeg, solveSpine, anchorPoint, centreOfMass } from '@three-ws/motion';++const pose = restPose();+solveArm(pose, 'Right', { wrist: anchorPoint(pose, 'chin', { side: 'Right' }), palm: [0, 0, 1] });+```++Or import it on its own, with none of the score machinery:++```js+import { Pose, solveTwoBone, BODY_FORWARD } from '@three-ws/motion/rig';```## CLI```bash-three-ws-motion "wave hello twice, excitedly" -o wave.json-three-ws-motion --score beats.json --loop --no-root -o clip.json-three-ws-motion --schema # the Motion Score JSON Schema-three-ws-motion --actions # every action this lane knows+npx @three-ws/motion "wave hello twice, excitedly" -o wave.json+npx @three-ws/motion --score sit.json --no-idle --no-root -o sit.json+npx @three-ws/motion --schema # the score schema, for a tool call+npx @three-ws/motion --actions # what the model-free lane knows```-| Option | Meaning |-| --- | --- |-| `-o, --out <file>` | Write the clip here (default: stdout) |-| `--score <file>` | Compile a Motion Score instead of a prompt |-| `--name <name>` | Clip name (default: the prompt, or the score's name) |-| `--loop` | Close the last beat back into the first |-| `--effort <name>` | Override the performance quality for every beat |-| `--no-idle` | Leave out the breathing and micro-sway layer |-| `--no-root` | Leave out the hip translation track, for a clip that plays in place |-| `--no-fingers` | Leave out the finger bones |-| `--score-out <file>` | Also write the Motion Score that produced the clip |+## How it works-## The Motion Score+Each beat is solved in an order that matters:-A score is a list of beats: what the body is doing, where it is looking, what the-hands are shaped like, and how the performance is played. It is plain JSON with a-published schema (`scoreSchema`), so it can be authored by a person, an editor, or-a model, and validated before anything is compiled.+```+root where the hips are, which everything below hangs from+turn the body's heading, so limbs solve in the turned frame+torso lean, twist, side-bend, shared along the spine+legs ankles placed in WORLD space, so dropping the hips bends the knees+balance the hips nudged until the centre of mass sits over the feet+arms wrists placed against anchors that ride the posed chest+hands shape, after the wrist is where it belongs+gaze last, so a look is relative to the chest it ended up on+```-```js-import { validateScore, normalizeScore, describeScore } from '@three-ws/motion';+Reverse any two and the result is subtly wrong in a way that is impossible to+fix downstream. Solve the arms before the torso and every gesture sits where the+chest used to be. Solve the legs before the root and a crouch drives the feet+through the floor.-const { valid, errors } = validateScore(score);-const normalized = normalizeScore(score); // defaults filled, ranges clamped-describeScore(normalized); // a human-readable summary-```+Four details do most of the work:-The vocabulary is exported as data, not hidden behind the compiler:-`POSTURES`, `STANCES`, `HAND_SHAPES`, `ELBOW_POLES`, `ACTION_NAMES`, and their-`*_NAMES` lists. Build a picker straight from them.+- **Feet are placed against the floor, not against the hips.** The hips are free+ to drop, lean and turn; the legs absorb it through IK, which is what a real+ body does and why a crouch looks like a crouch.+- **Balance is measured, not assumed.** The centre of mass is a mass-weighted+ sum over the segments that carry a body's weight, and the hips are moved until+ it sits over whichever feet are carrying weight. A lifted foot carries none,+ so a single-leg beat shifts the body over the standing leg on its own.+- **The clavicle helps.** An arm is not two bones on a fixed socket. The+ shoulder girdle swings toward a distant target, which is worth ten to fifteen+ centimetres of reach and most of what makes a reach read as a whole body+ reaching.+- **Easing is baked as geometry.** A mixer slerps between quaternion keys+ linearly, so an ease named in the score has to exist as extra samples in the+ track or it is not there at all.-## The solver, if you need it directly+The reference skeleton is measured from a real rig's bind pose rather than+assumed: bone lengths, segment directions, the body's own forward axis, and the+hand frame are all read from the data, so re-measuring a different rig changes+the numbers and not the code.-An editor, a different score format, or a custom front end is a reasonable thing-to build on this, and should not have to fork it. The rig layer is exported:+## Playing the clip on a different rig-| Export | What it does |-| --- | --- |-| `solveArm`, `solveLeg`, `solveSpine`, `solveGaze`, `solveTurn` | The IK chains |-| `shapeHand` | Finger posing from a named hand shape |-| `balanceError`, `balanceOffset`, `centreOfMass`, `supportCentre` | Keeping weight over the feet |-| `Pose`, `restPose`, `blendPose` | The pose representation and blending |-| `ANCHORS`, `anchorPoint`, `restAnchor`, `bodyDirection` | Named points on the body and the directions between them |-| `solveBeat`, `solveScorePoses`, `expressionWeights` | Score to poses |-| `buildClip`, `restClip`, `stableUuid` | Poses to an AnimationClip document |+The output uses canonical bone names (`Hips`, `Spine2`, `LeftForeArm`,+`RightUpLeg`, …). To play it on a rig with different names, run it through a+retargeter: three.ws ships one that maps Mixamo, Avaturn, Unreal, VRM/VRoid,+Daz, MakeHuman and Blender conventions onto the same canonical set.-`MOTION_BONES` is the canonical bone set the clips target; `LIMITS` and-`MOTION_SCORE_VERSION` pin the score contract.+```html+<script type="module" src="https://three.ws/agent-3d.js"></script>+<agent-3d src="agent://base/42" clip="https://example.com/wave.json"></agent-3d>+```## Related-- [`@three-ws/render`](../render): rasterize the resulting clip to PNG or GIF- with no GPU, to see what a score actually looks like.-- [`STRUCTURE.md`](../../STRUCTURE.md): where every three.ws surface lives.+- [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar) renders+ the avatar this drives.+- [`@three-ws/mocap`](https://www.npmjs.com/package/@three-ws/mocap) is the+ captured half: a webcam performance saved as a clip.+- [`@three-ws/pose`](https://www.npmjs.com/package/@three-ws/pose) is named+ static poses, where this package is motion between them.+- [three.ws/motion](https://three.ws/motion) is the studio: type a sentence,+ watch any avatar perform it, and export the GLB.## Licensediff --git a/public/changelog.json b/public/changelog.jsonindex 822f3bc89..512ff8798 100644--- a/public/changelog.json+++ b/public/changelog.json@@ -1,5 +1,5 @@{- "generated_at": "2026-08-28T05:50:30.686Z",+ "generated_at": "2026-08-28T05:52:45.301Z","generated_by": "scripts/build-page-index.mjs from data/pages.json + data/changelog.json","site": {"name": "three.ws",@@ -320,6 +320,17 @@"improvement"]},+ {+ "date": "2026-08-28",+ "type": "update",+ "title": "Glance: your agent on your Windows home screen, in your README, and in your terminal",+ "summary": "Your agent now has a card: its name, what it did in the last 24 hours, when it last acted, and a tap straight back into it. Pin it to the Windows 11 widgets board and it installs with the site itself, no app store, and refreshes on its own every fifteen minutes; signed out it shows a sign-in card instead of an error, and offline it keeps showing the last card it saw. The same card is one image URL you can paste into a GitHub README, a Slack message, or any page, and it follows the reader's light or dark mode. There is a live element for websites, a command you can run in a terminal to watch an agent work, and an npm package for building your own. Android is next, then macOS and iOS.",+ "link": "/glance",+ "tags": [+ "feature",+ "sdk"+ ]+ },{"date": "2026-08-28","type": "update",diff --git a/public/features.json b/public/features.jsonindex e9d00e1ad..692b9cb7f 100644--- a/public/features.json+++ b/public/features.json@@ -1,5 +1,5 @@{- "generated_at": "2026-08-28T05:50:30.472Z",+ "generated_at": "2026-08-28T05:52:45.034Z","generated_by": "scripts/build-page-index.mjs from data/pages.json","site": {"name": "three.ws",diff --git a/tests/api/render-animate.test.js b/tests/api/render-animate.test.jsnew file mode 100644index 000000000..114b90b25--- /dev/null+++ b/tests/api/render-animate.test.js@@ -0,0 +1,159 @@+// GET /api/render/animate — the animated-avatar image endpoint.+//+// The render itself is covered by packages/render/tests; what matters here is+// the public contract around it: a discoverable catalog, an honest error for an+// unknown clip, and a clip name that can never escape the motion library into+// the filesystem.++import { describe, it, expect, vi, beforeEach } from 'vitest';++const getAvatar = vi.fn();+const renderGlbToApngCpu = vi.fn();++vi.mock('../../api/_lib/avatars.js', () => ({+ getAvatar: (...args) => getAvatar(...args),+}));++vi.mock('../../api/_lib/render-cpu.js', () => ({+ renderGlbToApngCpu: (...args) => renderGlbToApngCpu(...args),+ renderGlbToPngCpu: vi.fn(),+ isUnsupportedModelError: () => false,+ clearModelCache: () => {},+}));++vi.mock('../../api/_lib/rate-limit.js', () => ({+ clientIp: () => '203.0.113.7',+ limits: { renderIp: async () => ({ success: true, limit: 60, remaining: 59, reset: Date.now() + 1000 }) },+}));++function makeRes() {+ const res = {+ statusCode: 0,+ headers: {},+ body: null,+ setHeader(k, v) {+ this.headers[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this.headers[k.toLowerCase()];+ },+ removeHeader(k) {+ delete this.headers[k.toLowerCase()];+ },+ writeHead(status, headers) {+ this.statusCode = status;+ Object.assign(this.headers, headers || {});+ return this;+ },+ end(body) {+ if (body !== undefined) this.body = body;+ this.ended = true;+ return this;+ },+ on() {},+ };+ return res;+}++async function call(url) {+ const { default: handler } = await import('../../api/render/animate.js');+ const req = { method: 'GET', url, headers: { host: 'three.ws' }, on() {} };+ const res = makeRes();+ await handler(req, res);+ return res;+}++const json = (res) => JSON.parse(typeof res.body === 'string' ? res.body : res.body.toString('utf8'));++beforeEach(() => {+ getAvatar.mockReset();+ renderGlbToApngCpu.mockReset();+ renderGlbToApngCpu.mockResolvedValue(Buffer.from([0x89, 0x50, 0x4e, 0x47, 1, 2, 3]));+});++describe('catalog', () => {+ it('lists the built-in motion library when asked for nothing', async () => {+ const res = await call('/api/render/animate');+ expect(res.statusCode).toBe(200);+ const body = json(res);+ expect(body.clips.length).toBeGreaterThan(20);+ expect(body.clips.map((c) => c.name)).toContain('idle');+ expect(body.usage).toContain('/api/render/animate');+ expect(res.getHeader('cache-control')).toContain('max-age');+ });+});++describe('clip resolution', () => {+ it('refuses a clip the library does not have', async () => {+ const res = await call('/api/render/animate?clip=definitely-not-a-clip');+ expect(res.statusCode).toBe(400);+ const body = json(res);+ expect(body.error).toBe('unknown_clip');+ expect(body.clips).toContain('idle');+ expect(renderGlbToApngCpu).not.toHaveBeenCalled();+ });++ it('cannot be walked out of the motion library', async () => {+ for (const attempt of ['../../../etc/passwd', '..%2f..%2fpackage', '/etc/hosts', 'idle/../../secret']) {+ const res = await call(`/api/render/animate?clip=${encodeURIComponent(attempt)}`);+ expect(res.statusCode, attempt).toBe(400);+ expect(json(res).error, attempt).toBe('unknown_clip');+ }+ expect(renderGlbToApngCpu).not.toHaveBeenCalled();+ });+});++describe('rendering', () => {+ it('renders the default model with no target named', async () => {+ const res = await call('/api/render/animate?clip=idle');+ expect(res.statusCode).toBe(200);+ expect(res.getHeader('content-type')).toBe('image/png');+ expect(res.getHeader('x-render-lane')).toBe('cpu');+ const args = renderGlbToApngCpu.mock.calls[0][0];+ expect(args.glbUrl).toBe('https://three.ws/avatars/default.glb');+ expect(args.clipJson.tracks.length).toBeGreaterThan(0);+ });++ it('clamps frame count, fps and size to the documented ranges', async () => {+ await call('/api/render/animate?clip=idle&frames=9999&fps=1000&size=99999');+ const args = renderGlbToApngCpu.mock.calls[0][0];+ expect(args.frames).toBe(48);+ expect(args.fps).toBe(30);+ expect(args.width).toBe(640);+ expect(args.height).toBe(640);+ });++ it('renders a public avatar by id', async () => {+ getAvatar.mockResolvedValue({ id: 'abc', name: 'Vern', model_url: 'https://cdn.three.ws/a.glb' });+ const res = await call('/api/render/animate?avatar=abc&clip=idle');+ expect(res.statusCode).toBe(200);+ expect(renderGlbToApngCpu.mock.calls[0][0].glbUrl).toBe('https://cdn.three.ws/a.glb');+ });++ it('will not render a private avatar', async () => {+ getAvatar.mockResolvedValue({ id: 'abc', name: 'Private', model_url: null });+ const res = await call('/api/render/animate?avatar=abc&clip=idle');+ expect(res.statusCode).toBe(404);+ expect(renderGlbToApngCpu).not.toHaveBeenCalled();+ });++ it('404s an avatar that does not exist', async () => {+ getAvatar.mockResolvedValue(null);+ const res = await call('/api/render/animate?avatar=missing&clip=idle');+ expect(res.statusCode).toBe(404);+ });++ it('refuses a src pointed at a private address', async () => {+ const res = await call('/api/render/animate?clip=idle&src=http://169.254.169.254/latest/meta-data/');+ expect(res.statusCode).toBe(400);+ expect(json(res).error).toBe('invalid_src');+ expect(renderGlbToApngCpu).not.toHaveBeenCalled();+ });++ it('reports a render failure as a 502 rather than a broken image', async () => {+ renderGlbToApngCpu.mockRejectedValue(new Error('not a GLB'));+ const res = await call('/api/render/animate?clip=idle');+ expect(res.statusCode).toBe(502);+ expect(json(res).error).toBe('render_failed');+ });+});