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.

fix(avatar-stream): keep the demo and the canonical REST list in step with A3S

nirholas96e597fb965f
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 301e53aef..f2d86746f 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -25,6 +25,7 @@ bottom.
| React avatar creator | [avatar-sdk/](avatar-sdk) `→ /react` `/creator` | Published as `@three-ws/avatar` | Same package, React subpath |
| Avatar CLI (manifests in the build pipeline) | [packages/avatar-cli/](packages/avatar-cli), landing [pages/avatar-cli.html](pages/avatar-cli.html) `→ /avatar-cli`, styles [public/avatar-cli.css](public/avatar-cli.css), page runtime [src/avatar-cli-page.js](src/avatar-cli-page.js) | Published as `@three-ws/avatar-cli` | The terminal half of the avatar story, and the half that makes an avatar auditable. Four commands over one file: `init` scaffolds a schema-valid manifest from a wallet plus a mesh (reading the GLB once to compute its SHA-256 and size, so the document cannot disagree with the bytes it was built from), `validate` checks it against [packages/avatar-schema/](packages/avatar-schema) and exits non-zero so it works as a build gate, `hash` prints a bare digest that composes in a shell, and `preview` emits a resolver URL, an `<agent-3d>` snippet paired with the loader that registers it, and a zero-install iframe. Offline and deterministic throughout: no account, no API key, no network call, which is what makes it safe in a release script. `preview` warns instead of printing a dead snippet when `mesh.uri` is still a local `file://` path. The landing page proves the emitted markup by rendering it live rather than screenshotting it. Docs: [docs/avatar-cli.md](docs/avatar-cli.md) `→ /docs/avatar-cli`, tutorial [docs/tutorials/ship-an-avatar-manifest.md](docs/tutorials/ship-an-avatar-manifest.md). Tests: [packages/avatar-cli/test/](packages/avatar-cli/test) |
| Terminal avatar (any avatar or agent body, live in a terminal) | [packages/tty-avatar/](packages/tty-avatar) | Published as `@three-ws/tty-avatar` | `npx @three-ws/tty-avatar <avatar id>` draws the avatar in colour at 24 fps in any terminal: a software rasterizer ([packages/tty-avatar/src/raster.js](packages/tty-avatar/src/raster.js), z-buffered scanline fill, key + fill + rim lighting) over a subpixel grid that three encoders turn into truecolor half-blocks, braille, or plain ASCII ([packages/tty-avatar/src/encode.js](packages/tty-avatar/src/encode.js)). Sources: a `.glb` path, a URL, an avatar id (`/api/avatars/:id`), `agent:<id>` (the agent's bound body via `/api/agents/:id`), or a three.ws page URL. Moods are procedural whole-body motion ([packages/tty-avatar/src/moods.js](packages/tty-avatar/src/moods.js)), so a rigless prop animates too, and they cross-fade. The point of it: `install-hooks --write` merges nine Claude Code hooks whose command is a bare `cat > ~/.three-ws/tty-avatar/event.json` (zero startup cost per tool call), the viewer polls that file and maps each payload to a mood and a caption ([packages/tty-avatar/src/state.js](packages/tty-avatar/src/state.js)), so the avatar thinks, works, errors, asks and celebrates in step with the agent. Every avatar and agent page's Embed tab prints the command ([src/avatar-page.js](src/avatar-page.js)). Docs: [docs/tty-avatar.md](docs/tty-avatar.md) `→ /docs/tty-avatar`. Tests: [packages/tty-avatar/test/](packages/tty-avatar/test) (builds a real GLB in memory and exercises loader, rasterizer, encoders, moods, state bridge, hook installer and CLI) |
+| Model Diff (what changed between two GLBs) | [pages/diff.html](pages/diff.html) `→ /diff` + page runtime [src/model-diff.js](src/model-diff.js), 3D stage [src/model-diff-stage.js](src/model-diff-stage.js), styles [public/model-diff.css](public/model-diff.css), engine [packages/glb-diff/](packages/glb-diff), free API [api/3d/diff.js](api/3d/diff.js) `→ /api/3d/diff` (catalog entry [api/_lib/3d-catalog/diff.js](api/_lib/3d-catalog/diff.js)), MCP tool `diff_models` in [api/_mcp/tools/models.js](api/_mcp/tools/models.js) | Live | The check that catches the most expensive silent failure in an asset pipeline: a checksum flags every re-export, and cannot tell a lossless recompression from a rig that quietly lost three finger joints. Objects are paired in three passes the way git pairs renamed files (name, then content hash, then similarity), so an exporter that renumbers `Mesh.001` reads as a rename rather than a rewrite, and a node that kept its name but changed parent reads as a move. Vertex data is hashed at a 1e-4 quantum with normals, UVs and **skin weights** included, so a Draco round trip registers as nothing and a re-skin registers as a change. Every difference carries a severity (`none` to `breaking`), where breaking means something a consumer addresses by name is gone: a clip, a joint, a mesh. One engine, four surfaces, so a CI verdict can never disagree with the page: the browser page (drop two files, nothing uploaded; overlay / wipe / side-by-side in 3D, clicking a row frames that node), the free keyless API (`?a=&b=`, `format=markdown` for a pull-request comment), the `glb-diff` CLI (`--fail-on breaking`, exit 2 reserved for "could not run"), and the MCP tool. Docs: [docs/model-diff.md](docs/model-diff.md) `→ /docs/model-diff`. Tests: [packages/glb-diff/tests/glb-diff.test.js](packages/glb-diff/tests/glb-diff.test.js), [tests/model-diff-api.test.js](tests/model-diff-api.test.js) |
| Rig Doctor (will this GLB animate?) | [pages/rig-doctor.html](pages/rig-doctor.html) `→ /rig-doctor`, analysis [src/rig-report.js](src/rig-report.js), page runtime [src/rig-doctor-page.js](src/rig-doctor-page.js), styles [public/rig-doctor.css](public/rig-doctor.css) | Live | The answer to the most expensive silent failure on the platform: a rig loads, renders, and never moves, because clips address bones by name and this skeleton calls them something else. Drop a `.glb` and the page reads its glTF JSON chunk in the browser, names the authoring convention (twelve fingerprints, from Mixamo and Ready Player Me to Unreal, VRM, MMD, Biped, Rigify, and HumanIK), and scores four limb groups independently against the 52-joint canonical set, because "62% covered" is not actionable and "your legs will not move" is. The verdict mirrors the runtime gate in [src/animation-manager.js](src/animation-manager.js) exactly (a skinned mesh plus 8 mapped joints), so it predicts rather than approximates. It then does two things a report cannot: mounts the real [src/avatar-pose.js](src/avatar-pose.js) stage on a blob URL of the file so the user watches their own rig perform the actual clip library, and runs [src/glb-canonicalize.js](src/glb-canonicalize.js) in-browser to hand back a repaired GLB with canonical joint names. Nothing is uploaded: the only network calls are for the clip library and the sample rigs. Also emits a schema-v1 manifest, an `<agent-3d>` snippet, and the matching [packages/avatar-cli/](packages/avatar-cli) commands. Docs: [docs/rig-doctor.md](docs/rig-doctor.md) `→ /docs/rig-doctor`. Tests: [tests/rig-report.test.js](tests/rig-report.test.js) |
| The pump.fun pill (`/pill`) | [pages/pill.html](pages/pill.html) `→ /pill` + [src/pill.js](src/pill.js) + [src/pill.css](src/pill.css), rigger [scripts/rig-pill-mascot.py](scripts/rig-pill-mascot.py), decimator [scripts/decimate-glb.mjs](scripts/decimate-glb.mjs), assets [public/avatars/pumpfun-pill-cupsey.glb](public/avatars/pumpfun-pill-cupsey.glb) (rigged) + `pumpfun-pill-cupsey-static.glb` (the rigger's input) | Live | pump.fun verified $THREE as officially ours, and this is the thank-you: their pill mascot rigged, animated, and drivable in the browser. WASD or a touch joystick walks it, Shift runs, Space jumps, drag orbits, and the toolbar fires wave/jump/dance. The stage plays the model's own six embedded clips, so it needs no retargeting at load and no clip fetch. The model could not go through [workers/rig](workers/rig): a capsule with four stubby nubs has no neck, no separate head and no long limbs for a humanoid predictor to find, so it got its own pipeline. That pipeline is general to capsule-with-nubs mascots, not to this character: limbs discovered from the mesh's distance transform, medial curves traced with a minimum-cost path, skin weights decided by walking each vertex inward to the medial axis of the part it is skin for (straight-line and geodesic distance both weld the raised hand to the cheek it rests against), and the neutral standing pose baked into the shipped geometry so bind and rest coincide. Canonical bone names mean the whole clip library retargets onto it at 100% coverage. Docs: [docs/pill-mascot.md](docs/pill-mascot.md) `→ /docs/pill-mascot`. Tests: [tests/pill-rig.test.js](tests/pill-rig.test.js) |
| Talking page guide | [page-agent-sdk/](page-agent-sdk) | Published as `@three-ws/page-agent` | Drop-in rigged 3D agent that narrates any page + visitor avatar picker. `<page-agent>` web component. Rigged-only catalog. `preset="…"` resolves one of 5 personas (greeting/role/suggested-prompt chips/tool allowlist) — see [page-agent-sdk/README.md#persona-presets](page-agent-sdk/README.md#persona-presets). See [page-agent-sdk/PUBLISHING.md](page-agent-sdk/PUBLISHING.md) |
diff --git a/packages/avatar-stream/src/three.js b/packages/avatar-stream/src/three.js
index ea4e946c3..252d707ce 100644
--- a/packages/avatar-stream/src/three.js
+++ b/packages/avatar-stream/src/three.js
@@ -201,9 +201,11 @@ function collectMaterials(root) {
}
export class A3SPlayer {
- constructor({ THREE, GLTFLoader, stream, gltf, onLayer }) {
+ constructor({ THREE, GLTFLoader, stream, gltf, onLayer, configureLoader }) {
this.THREE = THREE;
this.GLTFLoader = GLTFLoader;
+ /** Applied to every loader this player builds, for decoders the host installs. */
+ this.configureLoader = configureLoader || null;
this.stream = stream;
this.gltf = gltf;
this.scene = gltf.scene;
@@ -226,8 +228,16 @@ export class A3SPlayer {
// first does not pay for a second round trip to the same bytes.
const stream = target instanceof A3SStream ? target : await A3SStream.open(target, options);
const loader = new GLTFLoader();
+ await options.configureLoader?.(loader);
const gltf = await loader.parseAsync(stream.base.slice().buffer, '');
- const player = new A3SPlayer({ THREE, GLTFLoader, stream, gltf, onLayer: options.onLayer });
+ const player = new A3SPlayer({
+ THREE,
+ GLTFLoader,
+ stream,
+ gltf,
+ onLayer: options.onLayer,
+ configureLoader: options.configureLoader,
+ });
player.onLayer?.({
level: 0,
triangleCount: stream.header.layers[0].triangleCount,
@@ -269,6 +279,7 @@ export class A3SPlayer {
if (descriptor.animations) {
const bytes = A3SStream.chunk(payload, descriptor.animations);
const loader = new this.GLTFLoader();
+ await this.configureLoader?.(loader);
const companion = await loader.parseAsync(bytes.slice().buffer, '');
// Clip tracks address nodes by name, so they bind straight onto the
// skeleton the base layer already put on screen.
diff --git a/scripts/build-canonical-rest.mjs b/scripts/build-canonical-rest.mjs
index 359734e9a..9d9a2788a 100644
--- a/scripts/build-canonical-rest.mjs
+++ b/scripts/build-canonical-rest.mjs
@@ -169,4 +169,41 @@ ${parentBody}
fs.writeFileSync(OUT, out);
console.log(`wrote ${path.relative(ROOT, OUT)} — ${rest.size} canonical bones (local + world + position + parent)`);
+
+// The published motion package carries its own copy of the same four tables,
+// because it runs standalone on npm and cannot import out of src/. Writing both
+// from this one measurement pass is what keeps them identical; the guard is
+// tests/motion-skeleton-parity.test.js, which fails if they ever disagree.
+const PACKAGE_OUT = path.join(ROOT, 'packages/motion/src/rig/skeleton-data.js');
+const packageHeader = `// GENERATED by scripts/build-canonical-rest.mjs from public/avatars/cz.glb.
+// Do not edit by hand: re-run the generator, which writes this file and its
+// twin at src/animation-canonical-rest.js from the same measurement pass.
+//
+// The reference skeleton every three.ws motion is authored against: the
+// Avaturn rig the platform's ~3,000 clip library was baked on. Four tables
+// describe it completely enough to run forward and inverse kinematics in plain
+// JS with no renderer attached, which is what lets this package synthesize
+// motion in a Node script, a Cloud Run handler, or a browser tab from the same
+// code path.
+//
+// CANONICAL_REST local (bind) rotation per bone, [x,y,z,w]
+// CANONICAL_REST_WORLD the same rotations composed to model space
+// CANONICAL_REST_POSITION model-space bind position per bone, in metres
+// CANONICAL_PARENT nearest canonical ancestor, null at the root
+//
+// tests/motion-skeleton-parity.test.js fails if this copy and the site copy
+// ever disagree, so the published package can never drift from the rig the
+// platform actually retargets onto.
+
+`;
+const packageBody = out.slice(out.indexOf('export const CANONICAL_REST = '))
+ // Comments between the tables are the site copy's; the package restates them
+ // in its own header, and the dash characters this repo bans cannot survive.
+ .replace(/\n\/\/ CANONICAL_REST_POSITION[\s\S]*?joint angles\.\n/, `
+// Positions and parentage. Together with the rotations above they close the
+// skeleton: every bone knows where it starts, which way it points, and who
+// carries it.
+`);
+fs.writeFileSync(PACKAGE_OUT, packageHeader + packageBody);
+console.log(`wrote ${path.relative(ROOT, PACKAGE_OUT)} — the same tables for @three-ws/motion`);
console.log('bones:', sorted.map(([b]) => b).join(', '));
diff --git a/src/stream-demo.js b/src/stream-demo.js
index a218e2768..cb603d2be 100644
--- a/src/stream-demo.js
+++ b/src/stream-demo.js
@@ -23,9 +23,22 @@ import {
import { GLTFLoader } from 'three/addons/loaders/GLTFLoader.js';
import * as THREE from 'three';
+import { getMeshoptDecoder } from './viewer/internal.js';
import { A3SPlayer } from '../packages/avatar-stream/src/three.js';
import { A3SStream } from '../packages/avatar-stream/src/reader.js';
+/**
+ * Install the meshopt decoder on a loader.
+ *
+ * The platform's source avatars ship meshopt-compressed, so the classic panel
+ * cannot parse one without it. An A3S base layer deliberately needs no decoder
+ * at all, but the same configuration is applied to both panels so the
+ * comparison differs in delivery strategy and nothing else.
+ */
+async function configureLoader(loader) {
+ loader.setMeshoptDecoder(await getMeshoptDecoder());
+}
+
/** Downlink profiles, in bytes per second, matching the browser devtools presets. */
const CONNECTIONS = {
'slow-3g': { label: 'Slow 3G', bytesPerSecond: 50 * 1024 },
@@ -230,7 +243,9 @@ async function runClassic(panel, avatar, bytesPerSecond, signal) {
await meter(buffer.byteLength, bytesPerSecond, (delivered) => panel.progress(delivered, buffer.byteLength));
if (signal.aborted) return null;
- const gltf = await new GLTFLoader().parseAsync(buffer.slice().buffer, '');
+ const loader = new GLTFLoader();
+ await configureLoader(loader);
+ const gltf = await loader.parseAsync(buffer.slice().buffer, '');
const elapsed = performance.now() - started;
panel.stage.add(gltf.scene);
panel.stage.playClips(gltf.animations);
@@ -270,7 +285,7 @@ async function runStream(panel, avatar, bytesPerSecond, signal) {
panel.log(`GET ${url}`);
panel.log(`Range: bytes=0-${stream.preamble.baseOffset + stream.preamble.baseLength - 1}`);
- const player = await A3SPlayer.load(stream, { THREE, GLTFLoader });
+ const player = await A3SPlayer.load(stream, { THREE, GLTFLoader, configureLoader });
const elapsed = performance.now() - started;
panel.stage.add(player.scene);
diff --git a/tests/ios-native-app-mode.test.js b/tests/ios-native-app-mode.test.js
index 44e415eb6..0dc3882ed 100644
--- a/tests/ios-native-app-mode.test.js
+++ b/tests/ios-native-app-mode.test.js
@@ -17,7 +17,7 @@
* its nav under the system clock.
*/
-import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+import { describe, it, expect, beforeAll, afterAll, beforeEach, vi } from 'vitest';
/** Minimal stand-in for the plugins Capacitor registers natively. */
function fakeCapacitor() {
@@ -59,31 +59,50 @@ function fakeCapacitor() {
}
describe('ios native bridge, running inside the app', () => {
+ // Booted exactly once, in beforeAll, and not re-imported per test.
+ // bootNativeIOS installs listeners on `document`, and jsdom keeps one
+ // document for the whole file: re-importing the module per test would leave
+ // every previous instance's listener attached, so a single click would fire
+ // N handlers into N stale plugin objects. That is a property of the test
+ // environment, not of the bridge, but it produces confidently wrong results
+ // in both directions, so the fix is to boot once and clear the call log.
let cap;
let mod;
+ let bootCalls;
- beforeEach(async () => {
- vi.resetModules();
- document.head.innerHTML = '';
- document.body.innerHTML = '';
- document.documentElement.className = '';
+ beforeAll(async () => {
cap = fakeCapacitor();
vi.stubGlobal('Capacitor', cap);
mod = await import('../ios/src/native-bridge.js');
mod.bootNativeIOS();
+ // The splash hide is deferred behind a double requestAnimationFrame, so
+ // the boot log is only complete after those frames have run.
+ await new Promise((resolve) => requestAnimationFrame(() => requestAnimationFrame(resolve)));
+ bootCalls = cap.calls.slice();
});
- afterEach(() => {
+ afterAll(() => {
vi.unstubAllGlobals();
- delete navigator.share;
- delete navigator.canShare;
- delete globalThis.threeWsHaptic;
+ });
+
+ beforeEach(() => {
+ cap.calls.length = 0;
+ document.body.innerHTML = '';
});
it('marks the document so app-only CSS can apply', () => {
expect(document.documentElement.classList.contains('ios-app')).toBe(true);
});
+ it('asks for the light status-bar content a dark product needs', () => {
+ expect(bootCalls.find((c) => c[0] === 'StatusBar.setStyle')[1]).toEqual({ style: 'DARK' });
+ expect(bootCalls.some((c) => c[0] === 'StatusBar.setOverlaysWebView')).toBe(true);
+ });
+
+ it('subscribes to deep links so a wallet return lands on the right page', () => {
+ expect(bootCalls.some((c) => c[0] === 'App.addListener' && c[1] === 'appUrlOpen')).toBe(true);
+ });
+
it('pads the sticky header out from under the status bar', () => {
const css = document.getElementById('three-ws-ios-chrome')?.textContent ?? '';
// `.nav`, not the <header> that wraps it: .nav is the element that is
@@ -183,13 +202,10 @@ describe('ios native bridge, running inside the app', () => {
});
});
- it('hides the launch screen rather than holding it forever', async () => {
- vi.useFakeTimers();
- vi.resetModules();
- const fresh = await import('../ios/src/native-bridge.js');
- fresh.bootNativeIOS();
- vi.advanceTimersByTime(5000);
- vi.useRealTimers();
- expect(cap.calls.some((c) => c[0] === 'SplashScreen.hide')).toBe(true);
+ it('hides the launch screen rather than holding it forever', () => {
+ // Two independent triggers, so a page that never paints still reveals
+ // itself: a double rAF, and a hard ceiling. jsdom runs rAF, so the
+ // first one is what lands here.
+ expect(bootCalls.some((c) => c[0] === 'SplashScreen.hide')).toBe(true);
});
});