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(portal): add the CLI and give agent-glance its README

nirholasda5359a2f76d
diff --git a/STRUCTURE.md b/STRUCTURE.md
index 46863a4f6..301e53aef 100644
--- a/STRUCTURE.md
+++ b/STRUCTURE.md
@@ -56,6 +56,7 @@ bottom.
| Herald: messages delivered in person | SDK [herald-sdk/](herald-sdk) `→ /herald.js` (published as `@three-ws/herald`), rail [api/herald/announce.js](api/herald/announce.js) + [api/herald/stream.js](api/herald/stream.js) + [api/_lib/herald.js](api/_lib/herald.js), playground [pages/herald.html](pages/herald.html) `→ /herald` + [src/herald-page.js](src/herald-page.js), CLI [herald-sdk/bin/herald.mjs](herald-sdk/bin/herald.mjs), MCP [packages/herald-mcp/](packages/herald-mcp) | Live | A 3D character walks onto the page and says what happened, instead of a badge nobody notices. The library is the interrupt budget: importance scoring with pluggable scorers, a floor, quiet hours, a rate limit, dedupe with a TTL, freshness, batch collapse, focus awareness, and a stable reason for every message it refuses (`duplicate`, `rate-limited`, `quiet-hours`, `below-importance-floor`). Delivery is the walk companion ([walk-sdk](walk-sdk) `control.announce`) with an accessible `aria-live` card fallback for anything that cannot render 3D, and opt-in gesture-gated voice. **The rail is the part nobody expects:** `POST /api/herald/announce` with an API key carrying the `herald:announce` scope reaches the browser tab the caller has open over SSE, so `herald watch -- npm test` makes your avatar tell you the build finished, and an AI agent can do the same through the MCP server. An announcement is always delivered to the caller's own sessions (no recipient field, so no key can interrupt anyone else); the queue is Redis-backed, drained not broadcast, and expires in five minutes. Docs: [docs/herald.md](docs/herald.md), [docs/api-reference.md](docs/api-reference.md). Tests: [tests/herald-rules.test.js](tests/herald-rules.test.js), [tests/herald-runtime.test.js](tests/herald-runtime.test.js), [tests/herald-rail.test.js](tests/herald-rail.test.js), [tests/herald-announce-endpoint.test.js](tests/herald-announce-endpoint.test.js) |
| Notification bell & preferences | Event vocabulary [api/_lib/feed.js](api/_lib/feed.js) (`USER_EVENT_TYPES` → `publishUserEvent()` → `user_notifications`), endpoints [api/notifications/](api/notifications), preference matrix [api/_lib/notify-prefs.js](api/_lib/notify-prefs.js), bell client [src/notifications.js](src/notifications.js), avatar announcements [src/notification-herald.js](src/notification-herald.js), settings panel [src/dashboard-next/pages/settings.js](src/dashboard-next/pages/settings.js) | Live | In-app inbox covering remixes ([api/x402/remix-asset.js](api/x402/remix-asset.js)), DMs ([api/friends/messages.js](api/friends/messages.js)), coin bonding-curve graduations (pump cron in [api/cron/[name].js](api/cron/%5Bname%5D.js)), follows, sales, purchases, IRL, market, and account events. Preferences are a category × channel matrix (`in_app` always on; push/email/telegram/avatar are per-category opt-outs) edited from `/dashboard/settings`. **The `avatar` channel delivers in person:** for a fresh, unread notification in an opted-in category the corner companion walks on screen, gestures, and says the line with a link straight to it, summoning itself for that one message and retreating if it was off ([walk-sdk](walk-sdk) `control.announce`). Rules (15-minute freshness, once per browser, two per batch, visible tab only, device-level mute) live in [src/notification-herald.js](src/notification-herald.js). Docs: [docs/notifications.md](docs/notifications.md), [docs/social-layer.md](docs/social-layer.md). Tests: [tests/notification-herald.test.js](tests/notification-herald.test.js), [tests/notify-prefs.test.js](tests/notify-prefs.test.js) |
| Personal companion (`/companion`) | Page [pages/companion.html](pages/companion.html) `→ /companion` + [src/companion/](src/companion) (page, source cards, voice), API [api/companion/](api/companion) (settings, sources, contacts, events, `ingest`, `stream`, `poll`), engine [api/_lib/companion/](api/_lib/companion) (store, encrypted BYOK configs, triage, lanes for Telegram / iCal / IMAP), cron [api/cron/companion-poll.js](api/cron/companion-poll.js), migration [api/_lib/migrations/20260828140000_companion_harness.sql](api/_lib/migrations/20260828140000_companion_harness.sql) | Live | Turns a person's own inbox, chats, calendar and phone into deliveries a 3D character makes **in person**. BYOK per source (a Telegram bot the user made, a private iCal URL, IMAP with an app password) plus a universal bridge token anything can POST to. Every message is scored 0-100 by the shared deterministic rules ([@three-ws/companion/triage](packages/companion-sdk/src/triage-rules.js), the same module the CLI runs locally) and optionally refined by the user's own Anthropic key; above their threshold and outside quiet hours it is delivered through `companion_delivery` notifications, so the bell, Web Push, and the avatar channel all carry it. A contact's message is spoken by **that contact's avatar and voice** (`control.announce({ avatar })` in [walk-sdk](walk-sdk)). Live SSE at `/api/companion/stream` feeds the desktop app and any third-party body. Docs: [docs/companion.md](docs/companion.md). Tests: [tests/companion-triage.test.js](tests/companion-triage.test.js), [tests/companion-calendar.test.js](tests/companion-calendar.test.js), [packages/companion-sdk/tests/](packages/companion-sdk/tests) |
+| Knock: a priced door to a person (`/knock`) | Hub [pages/knock.html](pages/knock.html) `→ /knock` + [src/knock/page.js](src/knock/page.js), public door [pages/knock-door.html](pages/knock-door.html) `→ /knock/<handle>` + [src/knock/door.js](src/knock/door.js), API [api/knock/](api/knock) (door, directory, send, reply, settings, inbox), paid lane [api/x402/knock.js](api/x402/knock.js), engine [api/_lib/knock/](api/_lib/knock) (pure policy, store, delivery, receipt tokens), migration [api/_lib/migrations/20260828210000_knock_doors.sql](api/_lib/migrations/20260828210000_knock_doors.sql), SDK + CLI [packages/knock-sdk/](packages/knock-sdk) (`@three-ws/knock`), MCP [packages/knock-mcp/](packages/knock-mcp) (`@three-ws/knock-mcp`) | Live | Every account can publish a door at `/knock/<username>` and set what one message from a stranger costs. Paying it buys exactly one message through, and the delivery is **in person**: the knock becomes a `companion_events` row whose importance is derived from the amount paid, so the recipient's corner avatar walks on wherever they are and says who is at the door and what they paid. **The USDC settles straight to the recipient** (`payTo` on the 402 challenge is their own address, and a priced door cannot be opened without one), so there is no platform wallet in the path and no cut. Solana leads; Base is advertised only when the owner sets an address for it. **Every refusal happens before the 402** (shut door, daily cap, block list, length limits) and again before settlement, so a knock that was never going to land is never a knock somebody paid for. Only the subject line is spoken; an untrusted body never uses the recipient's avatar as a speaker. The sender gets a derived HMAC receipt URL and reads the reply through it with no account, which is why answering someone never hands out an address. Free doors take a plain POST on a tight per-IP bucket. Spec: [specs/KNOCK_PROTOCOL.md](specs/KNOCK_PROTOCOL.md). Docs: [docs/knock.md](docs/knock.md). Tests: [tests/knock-policy.test.js](tests/knock-policy.test.js), [packages/knock-sdk/test/](packages/knock-sdk/test), [packages/knock-mcp/test/](packages/knock-mcp/test) |
| Visitor feedback loop | Recorder [@three-ws/witness](packages/witness), capture + panel [src/feedback-companion.js](src/feedback-companion.js) (mounted by [src/walk-companion.js](src/walk-companion.js)), intake [api/feedback/report.js](api/feedback/report.js), queue API [api/feedback/index.js](api/feedback/index.js), scoring [api/_lib/feedback/triage.js](api/_lib/feedback/triage.js), store [api/_lib/feedback/store.js](api/_lib/feedback/store.js), cron [api/cron/feedback-triage.js](api/cron/feedback-triage.js), review page [pages/feedback.html](pages/feedback.html) `→ /feedback` + [src/feedback-page.js](src/feedback-page.js) | Live | The return channel on the corner companion: the visitor tells the avatar what broke and the report carries the route, build SHA, viewport, and the last console errors and failed requests the browser captured, so a vague sentence lands as an actionable row. The companion offers proactively at the one moment worth asking (right after the page actually threw), once per route per session, never in a background tab. **Feedback is data, never an instruction:** the model that reads untrusted visitor text writes six scalars to that report's own row and has no path to the repo, a deploy, or any other write; the admin-only `/feedback` queue groups reports into one row per problem and a person decides. **A report arrives as a runnable failing test:** the recorded session compiles into a Playwright spec asserting the failure is GONE (red until fixed, green after), reachable from the queue's Copy test button, `GET /api/feedback/repro`, `npm run feedback:repro`, and the `get_feedback_repro` MCP tool. Docs: [docs/feedback.md](docs/feedback.md), [docs/witness.md](docs/witness.md). Tests: [tests/feedback-triage.test.js](tests/feedback-triage.test.js) |
| Session-to-test recorder | [packages/witness/](packages/witness) `→ @three-ws/witness`: recorder [recorder.js](packages/witness/src/recorder.js), selector synthesis [selector.js](packages/witness/src/selector.js), capture-time privacy [redact.js](packages/witness/src/redact.js), spec compiler [compile.js](packages/witness/src/compile.js); compiled repros land in [tests/repros/](tests/repros) with [their own Playwright config](tests/repros/playwright.config.mjs) | Published as `@three-ws/witness` (Apache-2.0, zero deps) | Turns a real user session into a runnable failing test. Records INTENT (about 2 KB) rather than DOM mutations (megabytes), so it can be always-on, which is the point: the trace already exists when somebody decides to complain. Every element gets the strongest handle that is unique in the live document (test id > id > aria-label > role+name > text > name > placeholder > class > structural path), framework-generated ids and utility classes refused, and each trace carries a replay confidence equal to its WEAKEST link. The compiled spec asserts the failure is gone, never that it happened, so it locks in the fix rather than the bug; a session with no machine-visible failure emits `test.fail()` and says which assertion a human must add rather than faking green. Privacy is enforced at capture: typed values are never held (only a length and a shape), password/hidden/email/tel/date inputs and `data-witness="off"` subtrees record nothing, URLs lose their credentials before storage. Docs: [docs/witness.md](docs/witness.md). Tests: [packages/witness/test/](packages/witness/test) (36, `npm run test:witness`) |
| Prepaid credits (`/credits`) | [pages/credits.html](pages/credits.html) `→ /credits` + [src/credits.js](src/credits.js), balance/ledger [api/credits/index.js](api/credits/index.js) `→ GET /api/credits`, deposit verifier [api/credits/deposit.js](api/credits/deposit.js) `→ POST /api/credits/deposit` over [api/_lib/credit-deposit.js](api/_lib/credit-deposit.js), ledger engine [api/_lib/credits.js](api/_lib/credits.js), schema [api/_lib/migrations/20260621200000_credits.sql](api/_lib/migrations/20260621200000_credits.sql) | Live | The prepaid balance every metered action on the platform debits. Top up by sending SOL or $THREE to the platform deposit wallet (connect + SIWS-link + sign in the page, or paste a signature you already sent); crediting is server-authoritative and idempotent on the signature, so a signature that is not signed by a wallet linked to the account credits nobody. The page renders the caller's $THREE holder tier from the same `holder` block [api/pricing.js](api/pricing.js) returns ([api/_lib/three-tier.js](api/_lib/three-tier.js)), which is the discount [api/_lib/credits.js](api/_lib/credits.js) already applies to every debit, and lists what credits buy straight from the pricing catalog ([api/_lib/pricing/catalog.js](api/_lib/pricing/catalog.js)). Ledger is keyset-paginated. Docs: [docs/payment-sessions.md](docs/payment-sessions.md). Tests: [tests/credits.test.js](tests/credits.test.js) |
diff --git a/packages/agent-glance/README.md b/packages/agent-glance/README.md
new file mode 100644
index 000000000..abaf97c09
--- /dev/null
+++ b/packages/agent-glance/README.md
@@ -0,0 +1,131 @@
+# @three-ws/agent-glance
+
+**A three.ws agent, on any surface that has a slot.** One agent, one live number, one link back in: the same card renders on the Windows 11 widgets board, in a GitHub README, in a Slack message, on a web page, and in your terminal.
+
+```bash
+npx @three-ws/agent-glance 0f3a1c22-9b7e-4d51-8a10-2c6f5d90ab34
+```
+
+```
+╭──────────────────────────────────────────────────────────────────╮
+│ Atlas Scout ● active │
+│ Watches the launch feed and reports what matters. │
+│ │
+│ 17 moves today │
+│ This week 96 All time 412 Skills 4 │
+│ │
+│ https://three.ws/agents/0f3a1c22-9b7e-4d51-8a10-2c6f5d90ab34 │
+╰──────────────────────────────────────────────────────────────────╯
+```
+
+Zero dependencies. Works in Node 18+, a browser, a service worker, and an edge runtime. Every call is bounded by a deadline, because a card is decoration on someone else's page and must never be the reason it hangs.
+
+## Install
+
+```bash
+npm install @three-ws/agent-glance
+```
+
+## The card
+
+A glance card is public, cacheable, and side-effect free. It reads real platform state: the agent, its avatar (only when that avatar is public or unlisted), and its action log.
+
+```js
+import { fetchGlanceCard } from '@three-ws/agent-glance';
+
+const card = await fetchGlanceCard('0f3a1c22-9b7e-4d51-8a10-2c6f5d90ab34');
+
+card.name; // 'Atlas Scout'
+card.status; // 'active' | 'idle' | 'new'
+card.metric; // { label: 'Moves today', value: 17 }
+card.stats; // [{ label: 'This week', value: 96 }, ...]
+card.lastAction; // { type: 'skill.invoke', at: '...', relative: '1h ago' } | null
+card.url; // 'https://three.ws/agents/0f3a1c22-...'
+```
+
+The full field list is in [specs/GLANCE_CARD.md](https://github.com/nirholas/three.ws/blob/main/specs/GLANCE_CARD.md).
+
+## An image for a README or Slack
+
+```js
+import { glanceImageUrl, glanceMarkdown } from '@three-ws/agent-glance';
+
+glanceImageUrl(id, { size: 'medium', theme: 'auto' });
+// https://three.ws/api/glance/card?agent=...&format=svg&size=medium&theme=auto
+
+glanceMarkdown(id);
+// [![three.ws agent](https://three.ws/api/glance/card?...)](https://three.ws/agents/...)
+```
+
+Sizes are `small` (240x240), `medium` (480x200) and `large` (480x300). Theme `auto` ships both palettes inside the SVG and lets `prefers-color-scheme` choose, which GitHub and Slack both honour.
+
+## A live card on a page
+
+The element is hosted by three.ws, so a page needs no bundler and no npm install:
+
+```html
+<script type="module" src="https://three.ws/glance/element.js"></script>
+<agent-glance agent="0f3a1c22-9b7e-4d51-8a10-2c6f5d90ab34" size="medium" theme="auto"></agent-glance>
+```
+
+It is real DOM, not an image: hoverable, focusable, and readable by a screen reader. It refreshes every 5 minutes (`refresh="0"` disables it) and stops entirely while the tab is hidden or the element is off screen. `glanceEmbedHtml(id)` prints that snippet for you.
+
+## An Adaptive Card
+
+For a host that renders Adaptive Cards directly (the Windows widgets board, Teams, any Adaptive Card renderer):
+
+```js
+import { fetchGlanceAdaptiveCard } from '@three-ws/agent-glance';
+const adaptive = await fetchGlanceAdaptiveCard(id); // version 1.6, already bound
+```
+
+## CLI
+
+```bash
+agent-glance <agent-id> # the card, in your terminal
+agent-glance <agent-id> --watch 60 # redraw every 60 seconds
+agent-glance <agent-id> --json # the raw model
+agent-glance <agent-id> --markdown # a README snippet
+agent-glance <agent-id> --html # an embed snippet
+agent-glance <agent-id> --svg card.svg # write the image to a file
+```
+
+Options: `--size`, `--theme`, `--origin`, `--no-color`.
+
+## API
+
+| Export | What it does |
+| --- | --- |
+| `fetchGlanceCard(id, opts?)` | The card model. Throws `GlanceError` on a bad id, a 404, or an unreachable host. |
+| `fetchGlanceAdaptiveCard(id, opts?)` | The same card as a bound Adaptive Card. |
+| `glanceCardUrl(id, opts?)` | The JSON endpoint URL. |
+| `glanceImageUrl(id, opts?)` | The SVG endpoint URL. |
+| `glanceMarkdown(id, opts?)` | A README snippet. |
+| `glanceEmbedHtml(id, opts?)` | A page embed snippet. |
+| `renderGlanceAnsi(card, opts?)` | The card as ANSI for a terminal. |
+| `GlanceError` | Carries `status` and `agentId`. |
+
+Options common to all of them: `origin` (default `https://three.ws`), `size`, `theme`, plus `timeoutMs`, `signal` and `fetchImpl` on the fetchers.
+
+## Errors
+
+Every failure is one class, and it says what to do:
+
+```js
+try {
+ await fetchGlanceCard(id);
+} catch (err) {
+ err.status; // 404 when the agent is not on three.ws, 0 when the host was unreachable
+ err.agentId;
+}
+```
+
+An id that is not a uuid throws before any network call, so a typo in a README fails at build time rather than rendering a broken image forever.
+
+## Related
+
+- The live playground and install guide: [three.ws/glance](https://three.ws/glance)
+- Docs: [three.ws/docs/glance](https://three.ws/docs/glance)
+- Embeddable 3D avatars (a different product: the agent's body, on your page): [three.ws/widgets](https://three.ws/widgets)
+
+Apache-2.0
diff --git a/packages/glb-diff/README.md b/packages/glb-diff/README.md
index 0c8ce3928..85a4683d1 100644
--- a/packages/glb-diff/README.md
+++ b/packages/glb-diff/README.md
@@ -1,54 +1,12 @@
-<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>
+# @three-ws/glb-diff
-<h1 align="center">@three-ws/glb-diff</h1>
+**Structural diff for glTF/GLB.** Tells you what actually changed between two 3D
+models: geometry, materials, textures, skeletons, and animations, with git-style
+rename and move detection.
-<p align="center"><strong>git diff for 3D. Tell what actually changed between two glTF/GLB models, and whether it breaks anything.</strong></p>
-
-<p align="center">
- <a href="https://www.npmjs.com/package/@three-ws/glb-diff"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/glb-diff?logo=npm&color=cb3837"></a>
- <img alt="license" src="https://img.shields.io/npm/l/@three-ws/glb-diff?color=3b82f6">
- <img alt="node" src="https://img.shields.io/node/v/@three-ws/glb-diff?color=339933&logo=node.js">
-</p>
-
-<p align="center">
- <a href="#install">Install</a> &middot;
- <a href="#quick-start">Quick start</a> &middot;
- <a href="#the-cli">CLI</a> &middot;
- <a href="#api">API</a> &middot;
- <a href="#how-it-decides">How it decides</a> &middot;
- <a href="https://three.ws/diff">Try it in the browser</a>
-</p>
-
----
-
-## Why
-
-A checksum tells you two `.glb` files differ. It cannot tell a lossless
-recompression from a rig that quietly lost three finger joints, and only one of
-those takes your avatar off the screen.
-
-That failure is specific and expensive: animation clips address joints **by
-name**. Drop a joint, rename a bone, re-export through a tool that renumbers
-`Mesh.001`, and the model still loads, still renders, and never moves. Nothing
-throws. There is no error to grep for. You find out when someone tells you the
-character is standing in a T-pose.
-
-`glb-diff` is the check that catches it before the deploy. It reads both models,
-matches their objects the way `git` matches renamed files, and reports every
-difference with a severity you can gate a build on.
-
-```
-glb-diff avatar.v3.glb -> avatar.v4.glb
- BREAKING 12 change(s): +0 -3 ~6 renamed 3 moved 0
- Something a consumer references by name is gone. Clips, attachments, or materials bound to it will fail.
-
- !! Skeleton "Character" lost 2 joint(s): mixamorig:LeftEye, mixamorig:RightEye. Clips that target them will not play.
- ! 1 mesh(es) have different vertex data: "Body".
- ! Triangle count is down 21,006 (-42.8%).
- 3 object(s) kept their content and changed name.
-```
+A binary diff of two GLB files tells you the bytes differ, which you already
+knew. This tells you the thing you need to know before you ship: whether a
+consumer of that model is about to break.
## Install
@@ -56,17 +14,7 @@ glb-diff avatar.v3.glb -> avatar.v4.glb
npm install @three-ws/glb-diff
```
-Node 18+. Works in the browser too (the [/diff](https://three.ws/diff) page runs
-this exact package client side, and nothing is uploaded).
-
-`meshoptimizer` is an optional peer dependency. Install it if your models ship
-with `EXT_meshopt_compression`, which most web-optimized assets do:
-
-```bash
-npm install meshoptimizer
-```
-
-## Quick start
+## Library
```js
import { readFile } from 'node:fs/promises';
@@ -76,33 +24,30 @@ const before = await readFile('avatar.v1.glb');
const after = await readFile('avatar.v2.glb');
const changes = await diffModels(before, after, { nameA: 'v1', nameB: 'v2' });
-
console.log(formatText(changes));
+
if (changes.severity === 'breaking') process.exit(1);
```
-## The CLI
-
-```bash
-npx @three-ws/glb-diff before.glb after.glb
-```
+Isomorphic: it takes bytes, so the same call works in Node, in a worker, in a
+serverless handler, or in a browser.
-Either side may be a file path or an `http(s)` URL, so comparing a local build
-against the copy already live on your CDN takes one command:
+## CLI
```bash
-npx @three-ws/glb-diff dist/avatar.glb https://cdn.example.com/avatar.glb
+glb-diff before.glb after.glb
+glb-diff before.glb https://example.com/after.glb --markdown
+glb-diff base.glb candidate.glb --fail-on major
```
-| Flag | What it does |
+| Option | Meaning |
| --- | --- |
-| `--json` | Print the full change set as JSON |
-| `--markdown` | Print a Markdown report, sized for a pull-request comment |
-| `--fail-on <level>` | Exit 1 when severity reaches `cosmetic`/`minor`/`major`/`breaking` |
-| `--verbose` | Include unchanged rows in the totals table |
-| `--no-color` | Disable ANSI colour |
+| `--json` | The full change set as JSON |
+| `--markdown` | A Markdown report, sized for a pull-request comment |
+| `--fail-on <level>` | Exit 1 once severity reaches this level |
+| `--verbose` | Include unchanged totals in the table |
-Exit codes are the contract a pipeline depends on, so they are deliberate:
+Exit codes are the contract a CI job depends on, so they are deliberate:
| Code | Meaning |
| --- | --- |
@@ -113,154 +58,42 @@ Exit codes are the contract a pipeline depends on, so they are deliberate:
A tool that returns `1` for both "your model regressed" and "I could not open the
file" is useless in a pipeline, which is why `2` exists.
-### In a build
-
-```bash
-# Fail the build if an optimization pass broke the rig.
-npx @three-ws/glb-diff src/avatar.glb dist/avatar.glb --fail-on breaking
-
-# Post the report on the pull request.
-npx @three-ws/glb-diff base.glb head.glb --markdown > diff.md
-```
-
-## API
-
-### `diffModels(bytesA, bytesB, opts?)`
-
-Read two models and diff them. Returns a `ChangeSet`.
-
-```js
-const changes = await diffModels(beforeBytes, afterBytes, { nameA: 'before.glb', nameB: 'after.glb' });
-```
-
-### `describeModel(bytes, meta?)` and `diffDescriptions(a, b)`
-
-The two halves of `diffModels`, exposed separately because the interesting uses
-are not always end to end. A **description** is a small, JSON-safe summary of a
-model: hashes, counts, names, and structure, with no geometry buffers in it.
-
-```js
-const baseline = await describeModel(await readFile('base.glb'), { name: 'base.glb' });
-await writeFile('base.description.json', JSON.stringify(baseline));
-
-// Later, in another job, with the model itself long gone:
-const candidate = await describeModel(await readFile('build.glb'), { name: 'build.glb' });
-const changes = diffDescriptions(baseline, candidate);
-```
-
-That is how you keep a per-release baseline in CI without storing every
-historical `.glb`, and how a browser can describe one file once and compare it
-against many candidates without re-parsing.
+## Severity
-### `formatText(changeset, opts?)` and `formatMarkdown(changeset)`
-
-Render a change set. `formatText` takes `{ color, verbose }`; pass
-`color: false` for a log file.
-
-### `atLeast(severity, threshold)`
-
-The severity comparison the CLI gates on, exported so your own gate matches:
-
-```js
-import { atLeast } from '@three-ws/glb-diff';
-if (atLeast(changes.severity, 'major')) throw new Error('model regressed');
-```
-
-### The change set
-
-```jsonc
-{
- "version": 1,
- "identical": false,
- "severity": "breaking",
- "a": { "name": "before.glb", "sizeBytes": 780912, "generator": "glTF-Transform v4.4.0" },
- "b": { "name": "after.glb", "sizeBytes": 829780, "generator": "glTF-Transform v4.4.0" },
- "summary": { "changed": 98, "added": 6, "removed": 13, "modified": 70, "renamed": 4, "moved": 1 },
- "totals": {
- "triangles": { "a": 49112, "b": 28106, "delta": -21006, "pct": -42.8 }
- // ... vertices, joints, nodes, meshes, materials, textures, animations, skins, textureBytes, sizeBytes
- },
- "sections": {
- "skins": { "added": [], "removed": [], "renamed": [], "modified": [], "unchanged": 0, "changed": 3, "severity": "breaking" },
- "animations": { "...": "same shape" },
- "meshes": { "...": "same shape" },
- "nodes": { "...": "same shape, plus a `moved` list for reparented nodes" },
- "materials": { "...": "same shape" },
- "textures": { "...": "same shape" }
- },
- "extensions": { "used": { "added": [], "removed": [] }, "required": { "added": [], "removed": [] } },
- "asset": [],
- "highlights": [
- { "severity": "breaking", "text": "Skeleton \"Character\" lost 2 joint(s): mixamorig:LeftEye, mixamorig:RightEye. Clips that target them will not play." }
- ]
-}
-```
-
-`highlights` is the layer you print when you only have room for three lines. The
-sections are the layer you open when one of them is worth investigating.
-
-## How it decides
-
-### Matching: renames, not churn
-
-Objects are paired in three passes, the same strategy `git` uses for file
-renames:
-
-1. **by key** the names agree, so the objects correspond
-2. **by fingerprint** the names disagree but the content hashes identically, so
- it is a rename
-3. **by similarity** neither agrees, but one candidate scores close enough that
- "the same object, edited and renamed" is more honest than an add plus a remove
-
-Anything still unpaired really is an addition or a removal. Nodes get a fourth
-distinction: a node that kept its name and changed parent is reported as
-**moved**, because that changes where anything attached to it ends up.
-
-Objects with no name in the file are labelled `(unnamed mesh 3)` and keyed to
-their slot, so they only ever pair with the same slot on the other side rather
-than accidentally matching an unrelated object that happened to come third.
-
-### Tolerance: strict on edits, quiet on noise
-
-Vertex data is hashed at a quantum of `1e-4` units. A re-export through Blender,
-a `gltfpack` round trip, or a Draco decode perturbs positions in the `1e-6`
-range and does **not** register. A genuine edit moves vertices by orders of
-magnitude more and does.
-
-Positions are not the only thing hashed. Normals, tangents, UVs, colors, and
-**skin joints and weights** all participate, because a re-skin that leaves every
-vertex exactly where it was still changes how the model deforms, and a
-positions-only hash would call that unchanged.
-
-### Severity
+Every change set carries one severity, the worst of everything it found:
| Level | Meaning |
| --- | --- |
-| `none` | Structurally identical |
-| `cosmetic` | Only metadata changed. Nothing a renderer or a clip can observe |
-| `minor` | Appearance changed. Still loads, animates, keeps its shape |
-| `major` | Geometry or hierarchy changed. Re-check anything positioned against it |
-| `breaking` | Something a consumer references by name is gone. Clips, attachments, or materials bound to it will fail |
+| `none` | The two models are structurally identical. |
+| `cosmetic` | Only metadata changed. Nothing a renderer or a clip can observe. |
+| `minor` | Appearance changed. The model still loads, animates, and keeps its shape. |
+| `major` | Geometry or hierarchy changed. Anything positioned against this model should be re-checked. |
+| `breaking` | Something a consumer references by name is gone. Clips, attachments, or materials bound to it will fail. |
-The ladder is defined by what a downstream consumer notices, not by how large
-the byte delta is. A 40 MB texture swap is `minor`. Deleting one joint is
-`breaking`.
+That ladder is what makes `--fail-on` useful. A texture swap should not fail a
+build; a deleted bone that every animation clip targets should.
-## Determinism
+## API
+
+| Export | What it does |
+| --- | --- |
+| `diffModels(bytesA, bytesB, opts?)` | Bytes in, change set out. The one call most callers need. |
+| `describeModel(bytes)` / `describeDocument(doc)` | The structural description a diff is computed from. |
+| `diffDescriptions(a, b)` | Diff two descriptions you already have, skipping the parse. |
+| `formatText(changes)` / `formatMarkdown(changes)` | Render a change set for a terminal or a PR comment. |
+| `readDocument(bytes)` / `isGLB(bytes)` | Parse helpers over `@gltf-transform/core`. |
+| `SEVERITIES`, `SEVERITY_MEANING`, `atLeast()`, `maxSeverity()`, `severityRank()` | The severity ladder as data. |
+| `matchEntries()`, `jaccard()`, `ratio()` | The similarity matcher behind rename and move detection. |
-The same two files always produce the same change set, byte for byte, on any
-machine. That is what makes the output worth committing, posting on a pull
-request, and diffing against yesterday's.
+`DESCRIPTION_VERSION` and `CHANGESET_VERSION` are exported so a cache or a stored
+report can tell whether it was produced by a compatible version.
-## Also available as
+## Related
-- **A page.** [three.ws/diff](https://three.ws/diff) runs this package in your
- browser, overlays both models in 3D, and lets you wipe between them.
-- **A free API.** `GET https://three.ws/api/3d/diff?a=<url>&b=<url>` returns the
- same change set. Keyless, no account. Add `&format=markdown` for a report.
-- **An MCP tool.** `diff_models` on the three.ws MCP server, so an agent can ask
- whether the model it just optimized is still safe to ship.
+- [`@three-ws/render`](../render): rasterize a GLB to PNG with no GPU, for a
+ visual check alongside the structural one.
+- [`STRUCTURE.md`](../../STRUCTURE.md): where every three.ws surface lives.
## License
-Apache-2.0. Built by [three.ws](https://three.ws).
+Apache-2.0
diff --git a/packages/portal/src/cli.js b/packages/portal/src/cli.js
new file mode 100755
index 000000000..29f3087df
--- /dev/null
+++ b/packages/portal/src/cli.js
@@ -0,0 +1,94 @@
+#!/usr/bin/env node
+// portal — walk a website from the command line, or take the world with you.
+//
+// npx @three-ws/portal example.com summary of the world
+// npx @three-ws/portal example.com --glb site.glb save it as a 3D file
+// npx @three-ws/portal example.com --json w.json save the world document
+// npx @three-ws/portal example.com --open print the walkable link
+//
+// It reads the public API, so there is nothing to configure. Point it at your
+// own deployment with --endpoint https://your-host/api/portal.
+
+import { writeFile } from 'node:fs/promises';
+import { fetchWorld, fetchWorldGlb, describeWorld, PORTAL_API, PORTAL_PAGE, PortalError } from './index.js';
+
+const USAGE = `portal — turn a website into a walkable 3D world
+
+Usage
+ portal <url> [options]
+
+Options
+ --glb <file> write the world as a glTF binary
+ --json <file> write the world document as JSON
+ --open print the walkable three.ws link
+ --endpoint <url> Portal API to use (default ${PORTAL_API})
+ --help this text
+`;
+
+function parseArgs(argv) {
+ const args = { url: '', endpoint: PORTAL_API };
+ for (let i = 0; i < argv.length; i++) {
+ const a = argv[i];
+ if (a === '--help' || a === '-h') args.help = true;
+ else if (a === '--open') args.open = true;
+ else if (a === '--glb') args.glb = argv[++i];
+ else if (a === '--json') args.json = argv[++i];
+ else if (a === '--endpoint') args.endpoint = argv[++i];
+ else if (!a.startsWith('-') && !args.url) args.url = a;
+ }
+ return args;
+}
+
+const plural = (n, one, many = `${one}s`) => `${n} ${n === 1 ? one : many}`;
+
+function bar(value, max, width = 22) {
+ const filled = max > 0 ? Math.round((value / max) * width) : 0;
+ return `${'█'.repeat(filled)}${'·'.repeat(Math.max(0, width - filled))}`;
+}
+
+async function main() {
+ const args = parseArgs(process.argv.slice(2));
+ if (args.help || !args.url) {
+ process.stdout.write(USAGE);
+ process.exit(args.url ? 0 : 1);
+ }
+
+ const { world, cached } = await fetchWorld(args.url, { endpoint: args.endpoint, include: 'world' });
+ const summary = describeWorld(world);
+ const tallest = Math.max(...summary.districts.map((d) => d.height), 1);
+
+ const lines = [
+ '',
+ ` ${summary.title}`,
+ ` ${summary.host}${cached ? ' (cached)' : ''}`,
+ '',
+ ` ${plural(summary.sections, 'district')} · ${plural(summary.words, 'word')} · ${plural(summary.doors, 'door')} (${summary.internalDoors} internal) · ${plural(summary.billboards, 'billboard')} · ${plural(summary.monoliths, 'code monolith')}`,
+ '',
+ ];
+ for (const d of summary.districts.slice(0, 20)) {
+ lines.push(` ${bar(d.height, tallest)} ${String(d.words).padStart(5)}w ${d.name}`);
+ }
+ if (summary.districts.length > 20) lines.push(` … and ${summary.districts.length - 20} more districts`);
+ lines.push('');
+ if (args.open) lines.push(` walk it: ${PORTAL_PAGE}?url=${encodeURIComponent(args.url)}`, '');
+ process.stdout.write(`${lines.join('\n')}\n`);
+
+ if (args.json) {
+ await writeFile(args.json, `${JSON.stringify(world, null, '\t')}\n`);
+ process.stdout.write(` wrote ${args.json}\n`);
+ }
+ if (args.glb) {
+ const bytes = await fetchWorldGlb(args.url, { endpoint: args.endpoint });
+ await writeFile(args.glb, Buffer.from(bytes));
+ process.stdout.write(` wrote ${args.glb} (${(bytes.byteLength / 1024).toFixed(1)} kB)\n`);
+ }
+}
+
+main().catch((err) => {
+ if (err instanceof PortalError) {
+ process.stderr.write(`\n ${err.code}: ${err.message}\n\n`);
+ process.exit(2);
+ }
+ process.stderr.write(`\n ${err?.message || err}\n\n`);
+ process.exit(1);
+});
diff --git a/packages/render/tests/render.test.js b/packages/render/tests/render.test.js
index c0c23c8b7..6985f0749 100644
--- a/packages/render/tests/render.test.js
+++ b/packages/render/tests/render.test.js
@@ -7,6 +7,7 @@
import { describe, it, expect, beforeAll } from 'vitest';
import { readFileSync } from 'node:fs';
+import { createHash } from 'node:crypto';
import { AvatarModel } from '../src/model.js';
import { renderFrame, renderFrames, frameCamera, PRESETS } from '../src/render.js';
import { parseClipJson } from '../src/clips.js';
@@ -150,7 +151,7 @@ describe('animation', () => {
spin: 360,
});
expect(frames).toHaveLength(4);
- const hashes = new Set(frames.map((f) => Buffer.from(f.data).toString('base64').slice(0, 64)));
+ const hashes = new Set(frames.map((f) => createHash('sha256').update(Buffer.from(f.data)).digest('hex')));
expect(hashes.size).toBe(4);
}, 60_000);
});
diff --git a/tests/ios-native-app-mode.test.js b/tests/ios-native-app-mode.test.js
new file mode 100644
index 000000000..44e415eb6
--- /dev/null
+++ b/tests/ios-native-app-mode.test.js
@@ -0,0 +1,195 @@
+// @vitest-environment jsdom
+// @vitest-environment-options { "url": "https://three.ws/create" }
+/**
+ * The iOS bridge with the app actually present.
+ *
+ * ios-native-bridge.test.js pins the browser case, where the module must be
+ * inert. This one pins the half that only ever runs on a phone, which is
+ * exactly the half nobody can eyeball in a browser: it needs a real Capacitor
+ * global, so without a test it is verified for the first time on a device, in
+ * TestFlight, by a person who has to guess why a header is under the clock.
+ *
+ * The status-bar padding is the rule most worth pinning. In the app the WebView
+ * runs edge to edge and the page starts at y=0 under the notch, and the site's
+ * own compensation is behind `@media (display-mode: standalone)`, which a
+ * WKWebView loading a remote URL does not match. If the injected stylesheet
+ * stops targeting the sticky header, every page on the platform quietly renders
+ * its nav under the system clock.
+ */
+
+import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest';
+
+/** Minimal stand-in for the plugins Capacitor registers natively. */
+function fakeCapacitor() {
+ const calls = [];
+ const record =
+ (name) =>
+ (...args) => {
+ calls.push([name, ...args]);
+ return Promise.resolve({});
+ };
+ return {
+ calls,
+ isNativePlatform: () => true,
+ getPlatform: () => 'ios',
+ Plugins: {
+ SplashScreen: { hide: record('SplashScreen.hide') },
+ StatusBar: {
+ setStyle: record('StatusBar.setStyle'),
+ setOverlaysWebView: record('StatusBar.setOverlaysWebView'),
+ },
+ Browser: { open: record('Browser.open') },
+ Share: { share: record('Share.share') },
+ Filesystem: {
+ writeFile: (opts) => {
+ calls.push(['Filesystem.writeFile', opts]);
+ return Promise.resolve({ uri: `file:///cache/${opts.path}` });
+ },
+ },
+ Haptics: { impact: record('Haptics.impact') },
+ App: {
+ addListener: (event, handler) => {
+ calls.push(['App.addListener', event]);
+ fakeCapacitor.lastUrlHandler = handler;
+ return Promise.resolve({ remove() {} });
+ },
+ },
+ },
+ };
+}
+
+describe('ios native bridge, running inside the app', () => {
+ let cap;
+ let mod;
+
+ beforeEach(async () => {
+ vi.resetModules();
+ document.head.innerHTML = '';
+ document.body.innerHTML = '';
+ document.documentElement.className = '';
+ cap = fakeCapacitor();
+ vi.stubGlobal('Capacitor', cap);
+ mod = await import('../ios/src/native-bridge.js');
+ mod.bootNativeIOS();
+ });
+
+ afterEach(() => {
+ vi.unstubAllGlobals();
+ delete navigator.share;
+ delete navigator.canShare;
+ delete globalThis.threeWsHaptic;
+ });
+
+ it('marks the document so app-only CSS can apply', () => {
+ expect(document.documentElement.classList.contains('ios-app')).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
+ // position:sticky;top:0, so padding the wrapper is undone by the first
+ // scroll. public/nav.css line 40 is the rule this compensates for.
+ expect(css).toMatch(/html\.ios-app \.nav \{\s*padding-top: env\(safe-area-inset-top/);
+ });
+
+ it('offsets the nav drawer by the same inset it moved the header by', () => {
+ const css = document.getElementById('three-ws-ios-chrome').textContent;
+ expect(css).toContain('calc(57px + env(safe-area-inset-top, 0px))');
+ });
+
+ it('keeps form fields at 16px so focusing one cannot zoom the page', () => {
+ const css = document.getElementById('three-ws-ios-chrome').textContent;
+ expect(css).toMatch(/html\.ios-app input,[\s\S]*?font-size: max\(16px/);
+ });
+
+ it('injects the stylesheet once, however often it boots', () => {
+ mod.bootNativeIOS();
+ expect(document.querySelectorAll('#three-ws-ios-chrome')).toHaveLength(1);
+ });
+
+ it('gives the page a navigator.share WKWebView does not have', async () => {
+ expect(typeof navigator.share).toBe('function');
+ await navigator.share({ title: 'Agent', url: 'https://three.ws/agents/1' });
+ const call = cap.calls.find((c) => c[0] === 'Share.share');
+ expect(call[1]).toMatchObject({ title: 'Agent', url: 'https://three.ws/agents/1' });
+ });
+
+ it('writes a shared blob to cache first, because the plugin takes URIs not Blobs', async () => {
+ const file = new File(['x'], 'capture.png', { type: 'image/png' });
+ await navigator.share({ files: [file] });
+ const written = cap.calls.find((c) => c[0] === 'Filesystem.writeFile');
+ expect(written[1].directory).toBe('CACHE');
+ expect(cap.calls.find((c) => c[0] === 'Share.share')[1].files).toEqual([
+ 'file:///cache/capture.png',
+ ]);
+ });
+
+ it('sends an off-site link to the Safari sheet instead of the app WebView', () => {
+ document.body.innerHTML = '<a id="out" href="https://solscan.io/tx/abc">tx</a>';
+ const ev = new MouseEvent('click', { bubbles: true, cancelable: true, button: 0 });
+ document.getElementById('out').dispatchEvent(ev);
+ expect(ev.defaultPrevented).toBe(true);
+ expect(cap.calls.find((c) => c[0] === 'Browser.open')[1].url).toBe('https://solscan.io/tx/abc');
+ });
+
+ it('leaves an in-app link to normal navigation', () => {
+ document.body.innerHTML = '<a id="in" href="/create">create</a>';
+ const ev = new MouseEvent('click', { bubbles: true, cancelable: true, button: 0 });
+ document.getElementById('in').dispatchEvent(ev);
+ expect(ev.defaultPrevented).toBe(false);
+ expect(cap.calls.some((c) => c[0] === 'Browser.open')).toBe(false);
+ });
+
+ it('leaves a download link alone, since a browser sheet cannot save a file', () => {
+ document.body.innerHTML = '<a id="dl" href="https://cdn.example.com/a.glb" download>glb</a>';
+ const ev = new MouseEvent('click', { bubbles: true, cancelable: true, button: 0 });
+ document.getElementById('dl').dispatchEvent(ev);
+ expect(ev.defaultPrevented).toBe(false);
+ });
+
+ describe('haptics', () => {
+ function tap(html) {
+ // Count only what THIS tap produced: cap.calls accumulates for the
+ // whole test, and boot itself makes plugin calls.
+ const before = cap.calls.length;
+ document.body.innerHTML = html;
+ document.body.firstElementChild.dispatchEvent(
+ new MouseEvent('click', { bubbles: true, cancelable: true, button: 0 }),
+ );
+ return cap.calls.slice(before).filter((c) => c[0] === 'Haptics.impact');
+ }
+
+ it('fires on a primary action with no markup change needed anywhere', () => {
+ expect(tap('<button class="btn btn--primary">Create</button>')).toHaveLength(1);
+ });
+
+ it('hits harder on a destructive action', () => {
+ expect(tap('<button class="btn btn--danger">Delete</button>')[0][1]).toEqual({
+ style: 'MEDIUM',
+ });
+ });
+
+ it('stays quiet on a control that did nothing', () => {
+ expect(tap('<button class="btn btn--primary" disabled>Create</button>')).toHaveLength(0);
+ expect(tap('<button class="btn btn--primary" aria-busy="true">Working</button>')).toHaveLength(0);
+ });
+
+ it('stays quiet on a secondary control, so the tick keeps meaning something', () => {
+ expect(tap('<button class="btn btn--ghost">Cancel</button>')).toHaveLength(0);
+ });
+
+ it('honours an explicit opt-in anywhere else', () => {
+ expect(tap('<div data-haptic="heavy">tip</div>')[0][1]).toEqual({ style: 'HEAVY' });
+ });
+ });
+
+ 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);
+ });
+});