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.

style: strip the banned em and en dashes from docs, package READMEs, and comments

nirholas1b2f9d765a8a
diff --git a/api/_lib/solana/connection.js b/api/_lib/solana/connection.js
index a18dded81..cdd0c8012 100644
--- a/api/_lib/solana/connection.js
+++ b/api/_lib/solana/connection.js
@@ -5,7 +5,7 @@
// Connection whose underlying fetch rotates across a priority-ordered endpoint
// list. Every method on it (getBalance, getLatestBlockhash, sendRawTransaction,
// confirmTransaction, …) transparently fails over when an endpoint returns
-// 429/5xx/auth errors or the network blips — no call-site change beyond swapping
+// 429/5xx/auth errors or the network blips: no call-site change beyond swapping
// the constructor. Re-sending an already-signed transaction to a second RPC is
// safe: Solana dedupes by signature.
//
@@ -25,7 +25,7 @@
//
// To survive a single provider's quota running dry (e.g. a paid Helius plan
// exhausting its monthly requests), register free-tier keys at several providers
-// and list their URLs in SOLANA_RPC_FALLBACK_URLS — every connection rotates
+// and list their URLs in SOLANA_RPC_FALLBACK_URLS: every connection rotates
// across the whole set, so the platform keeps serving even mid-outage.
import { Connection } from '@solana/web3.js';
@@ -34,7 +34,7 @@ import { Connection } from '@solana/web3.js';
// module is shared with the BROWSER bundle (public/agent/index.html →
// src/agent-skills.js → src/agent-skills-pumpfun.js → src/solana/sns.js →
// here), and api/_lib/cache.js statically imports node:zlib and node:util. A
-// top-level import therefore broke `npm run build` outright — rollup resolves
+// top-level import therefore broke `npm run build` outright, rollup resolves
// the Node built-ins to __vite-browser-external and fails on
// `"promisify" is not exported`. Loading it lazily behind isServer() also fixes
// the architectural half: the browser holds no Upstash credentials and must
@@ -107,7 +107,7 @@ export function resolveWsEndpoint(primaryHttpUrl, network = 'mainnet') {
return deriveWsUrl(primaryHttpUrl);
}
-// True only for a value @solana/web3.js's `new Connection` will accept — a parseable
+// True only for a value @solana/web3.js's `new Connection` will accept, a parseable
// URL whose protocol is http: or https:. Connection's `assertEndpointUrl` rejects
// everything else (ws://, a scheme-less host, junk) by throwing
// "Endpoint URL must start with `http:` or `https:`.", which is exactly the
@@ -128,10 +128,10 @@ export function isHttpUrl(u) {
// cannot be salvaged. Repairs the malformed shapes seen in production env config
// before they reach `new Connection` (where they 500 with "Endpoint URL must start
// with http: or https:"):
-// • surrounding quotes — a dashboard paste artifact (`SOLANA_RPC_URL="https://…"`)
-// • a websocket URL (ws/wss) — a valid URL but not an HTTP JSON-RPC endpoint; the
+// • surrounding quotes: a dashboard paste artifact (`SOLANA_RPC_URL="https://…"`)
+// • a websocket URL (ws/wss): a valid URL but not an HTTP JSON-RPC endpoint; the
// RPC host serves both on the same origin, so we map it to its http(s) form
-// • a scheme-less host (`mainnet.helius-rpc.com/?api-key=…`) — assume https
+// • a scheme-less host (`mainnet.helius-rpc.com/?api-key=…`), assume https
// It also keeps the original Helius host repair: the JSON-RPC host is
// `mainnet.helius-rpc.com` / `devnet.helius-rpc.com`; a recurring misconfiguration
// set SOLANA_RPC_URL to `api-mainnet.helius-rpc.com` (conflating it with the
@@ -148,7 +148,7 @@ export function normalizeRpcUrl(raw) {
if (!v) return '';
// Build a parseable candidate, repairing ws/wss and scheme-less inputs. String-
- // level repairs (not URL.toString()) so a clean input round-trips byte-for-byte —
+ // level repairs (not URL.toString()) so a clean input round-trips byte-for-byte -
// no trailing-slash churn versus the hardcoded endpoint constants, which would
// otherwise defeat dedupe and list the same node twice.
let candidate = v;
@@ -156,7 +156,7 @@ export function normalizeRpcUrl(raw) {
else if (/^ws:\/\//i.test(candidate)) candidate = candidate.replace(/^ws:/i, 'http:');
else if (!/^[a-z][a-z0-9+.-]*:\/\//i.test(candidate)) {
// Scheme-less: assume https only for a host-shaped value (has a dot, or
- // localhost[:port]). A bare token like "helius" is a typo, not a host — drop
+ // localhost[:port]). A bare token like "helius" is a typo, not a host, drop
// it so it never becomes a bogus `https://helius` lane that wastes a failover
// round-trip before the real fallback answers.
const host = candidate.split(/[/?#]/)[0];
@@ -190,22 +190,22 @@ export function normalizeRpcUrl(raw) {
// Cooldown durations by failure class. Quota exhaustion (e.g. Helius -32429
// "max usage reached") means the provider is dead for the billing window, so we
// park it for hours instead of re-hammering it on every RPC call and every cron
-// tick — that re-hammering was the source of the 429 retry storm in the logs.
+// tick: that re-hammering was the source of the 429 retry storm in the logs.
// Plain rate-limits, auth rejections, and transient 5xx/network blips cool down
// for shorter, proportionate windows.
// Per-attempt fetch bound inside the rotating fetch: one hung provider must cost
// at most this before the rotation moves to the next lane.
const ATTEMPT_TIMEOUT_MS = 10_000;
-const QUOTA_COOLDOWN_MS = 6 * 3_600_000; // 6h — daily/monthly quota exhausted
-const RATE_LIMIT_COOLDOWN_MS = 10 * 60_000; // 10m — transient 429
-const AUTH_COOLDOWN_MS = 30 * 60_000; // 30m — bad/expired key on this provider only
-const SERVER_COOLDOWN_MS = 2 * 60_000; // 2m — provider 5xx
-const NETWORK_COOLDOWN_MS = 30_000; // 30s — fetch threw (DNS/connection blip)
+const QUOTA_COOLDOWN_MS = 6 * 3_600_000; // 6h: daily/monthly quota exhausted
+const RATE_LIMIT_COOLDOWN_MS = 10 * 60_000; // 10m, transient 429
+const AUTH_COOLDOWN_MS = 30 * 60_000; // 30m: bad/expired key on this provider only
+const SERVER_COOLDOWN_MS = 2 * 60_000; // 2m: provider 5xx
+const NETWORK_COOLDOWN_MS = 30_000; // 30s: fetch threw (DNS/connection blip)
// A lane refusing ONE call shape is demoted for that method alone, never for the
// lane. Short, because a policy block is a provider setting that can change and
-// re-probing costs exactly one request that transparently fails over — unlike a
+// re-probing costs exactly one request that transparently fails over, unlike a
// quota probe, which burns the very budget it is testing.
-const METHOD_DEMOTION_MS = 15 * 60_000; // 15m — this lane refuses this method
+const METHOD_DEMOTION_MS = 15 * 60_000; // 15m: this lane refuses this method
const PUBLIC_MAINNET = 'https://api.mainnet-beta.solana.com';
const PUBLIC_DEVNET = 'https://api.devnet.solana.com';
@@ -453,7 +453,7 @@ function cooldownMsFor(status, bodyText) {
// the exhausted paid lanes. The endpoint is fine, this one request is not: fail
// over for the call, keep the lane.
//
- // The rotating fetch no longer reaches this branch — it recognises the refusal
+ // The rotating fetch no longer reaches this branch: it recognises the refusal
// first and demotes the METHOD instead of the lane (see markMethodDemotion), so
// the lane keeps serving every other call shape with no cooldown at all. The
// branch stays because markEndpointCooldown is exported and must still classify
@@ -461,7 +461,7 @@ function cooldownMsFor(status, bodyText) {
if (status === 403 && isCallShapeRefusal(bodyText)) return NETWORK_COOLDOWN_MS;
if (status === 401 || status === 403) return AUTH_COOLDOWN_MS;
// 404/410: the endpoint URL is dead or misrouted (expired Quicknode/Alchemy
- // app, wrong path) — a persistent misconfiguration, so park it like an auth
+ // app, wrong path): a persistent misconfiguration, so park it like an auth
// failure rather than re-probing every few minutes.
if (status === 404 || status === 410) return AUTH_COOLDOWN_MS;
if (status >= 500) return SERVER_COOLDOWN_MS;
@@ -477,7 +477,7 @@ export function isEndpointCooling(url) {
// Per-method lane capability
// ---------------------------------------------------------------------------
// The lane cooldown above is the right tool for a provider that cannot serve
-// ANY call — quota spent, key rejected, node down. It is the wrong tool for the
+// ANY call: quota spent, key rejected, node down. It is the wrong tool for the
// far more common free-lane failure: a provider that serves most of the chain
// happily and refuses exactly one call shape. PublicNode answers getBalance,
// getLatestBlockhash and getSignatureStatuses perfectly while refusing
@@ -495,7 +495,7 @@ export function isEndpointCooling(url) {
// Deliberately process-local, unlike the quota breaker. Re-discovering a method
// block on a cold instance costs ONE request that transparently fails over.
// Re-discovering a quota block costs a request against a plan that is already
-// over its cap, which is what keeps a daily cap pinned — that asymmetry is the
+// over its cap, which is what keeps a daily cap pinned, that asymmetry is the
// whole reason the quota verdict is shared and this one is not.
const _methodDemotion = new Map(); // `${url}${METHOD_KEY_SEP}${method}` → expiry ms
@@ -510,7 +510,7 @@ const methodKey = (url, method) => `${url}${METHOD_KEY_SEP}${method}`;
/**
* The JSON-RPC method names carried by a request body, deduped. Handles the
* single-call and batch forms web3.js emits. Returns [] for an unreadable body,
- * which makes every capability check a no-op — an unparseable request must never
+ * which makes every capability check a no-op: an unparseable request must never
* silently skip a healthy lane.
*/
export function rpcMethodsFromBody(body) {
@@ -623,7 +623,7 @@ function dedupe(list) {
}
// devnet is inferred from the caller's url so we never append a mainnet fallback
-// to a devnet primary (or vice-versa) — crossing clusters would return wrong data.
+// to a devnet primary (or vice-versa): crossing clusters would return wrong data.
function inferNetwork(url) {
return /devnet/i.test(String(url || '')) ? 'devnet' : 'mainnet';
}
@@ -632,7 +632,7 @@ function inferNetwork(url) {
// This is the zero-deploy lever for "spread load across as many free tiers as
// possible": sign up for free-tier keys at several providers (Alchemy, dRPC,
// Quicknode, Chainstack, Triton…), drop their URLs here, and EVERY Solana
-// connection rotates across them — so no single free quota becomes the bottleneck
+// connection rotates across them: so no single free quota becomes the bottleneck
// and a provider running dry transparently fails over to the next.
function extraFallbackUrls() {
// SOLANA_RPC_FALLBACKS was the balances-layer-only fallback var before the
@@ -651,7 +651,7 @@ function extraFallbackUrls() {
// The inverse economics of SOLANA_RPC_FALLBACK_URLS: paid metered endpoints
// (e.g. the Quicknode credit-funded endpoint) whose quota should be PRESERVED,
// not load-balanced. They sit after every free/keyless public node, so they are
-// only hit when the entire free chain is down or throttled — the endpoint acts
+// only hit when the entire free chain is down or throttled, the endpoint acts
// as an insurance rung and its monthly credits stretch as long as possible.
function lastResortUrls() {
return (process.env.SOLANA_RPC_LAST_RESORT_URLS || '')
@@ -660,7 +660,7 @@ function lastResortUrls() {
.filter(Boolean);
}
-// The caller's explicit `url` is pinned at priority 1 — but ~35 call sites spell
+// The caller's explicit `url` is pinned at priority 1, but ~35 call sites spell
// their default as `process.env.SOLANA_RPC_URL || 'https://api.mainnet-beta.solana.com'`,
// so whenever SOLANA_RPC_URL is unset they would pin the single most-throttled
// endpoint in the chain AHEAD of Helius and every paid lane, silently inverting
@@ -687,7 +687,7 @@ export function solanaRpcEndpoints(network = 'mainnet', url = null) {
const key = process.env.HELIUS_API_KEY;
const alch = process.env.ALCHEMY_API_KEY;
const ankr = process.env.ANKR_API_KEY;
- // dRPC — free tier requires a key (keyless now returns "chain is not available
+ // dRPC: free tier requires a key (keyless now returns "chain is not available
// on freetier"). Added in its authenticated form only when DRPC_API_KEY is set.
const drpc = process.env.DRPC_API_KEY;
if (network === 'devnet') {
@@ -696,7 +696,7 @@ export function solanaRpcEndpoints(network = 'mainnet', url = null) {
return dedupe([
pinnedUrl(url),
normalizeRpcUrl(process.env.SOLANA_RPC_URL_DEVNET),
- // QuickNode — a full dedicated endpoint URL (key embedded in the path), so
+ // QuickNode: a full dedicated endpoint URL (key embedded in the path), so
// it takes a URL var rather than an api-key. Premium/reliable, placed high.
normalizeRpcUrl(process.env.QUICKNODE_RPC_URL_DEVNET),
key && `https://devnet.helius-rpc.com/?api-key=${key}`,
@@ -708,7 +708,7 @@ export function solanaRpcEndpoints(network = 'mainnet', url = null) {
return dedupe([
pinnedUrl(url),
normalizeRpcUrl(process.env.SOLANA_RPC_URL),
- // QuickNode — a full dedicated endpoint URL (key embedded in the path), so it
+ // QuickNode: a full dedicated endpoint URL (key embedded in the path), so it
// takes a URL var rather than an api-key. A premium paid lane: placed right
// after the operator's explicit SOLANA_RPC_URL and ahead of the shared-key
// providers so it absorbs load first. Its WSS is derived by deriveWsUrl
@@ -717,19 +717,19 @@ export function solanaRpcEndpoints(network = 'mainnet', url = null) {
key && `https://mainnet.helius-rpc.com/?api-key=${key}`,
alch && `https://solana-mainnet.g.alchemy.com/v2/${alch}`,
drpc && `https://lb.drpc.org/ogrpc?network=solana&dkey=${drpc}`,
- // Ankr sunset keyless access — every keyless rpc.ankr.com/<chain> now 403s
+ // Ankr sunset keyless access: every keyless rpc.ankr.com/<chain> now 403s
// ("authenticate with an API key"), so include it only in its authenticated
// form when ANKR_API_KEY is set. Mirrors idxRpcUrls() in api/cron/[name].js;
// a keyless entry here was a guaranteed 403 + cooldown log every cron tick.
ankr && `https://rpc.ankr.com/solana/${ankr}`,
- // Operator's own free-tier fallbacks (mainnet only — devnet URLs would cross
+ // Operator's own free-tier fallbacks (mainnet only: devnet URLs would cross
// clusters and return wrong data). Tried before the public nodes so the
// configured providers absorb load first.
...extraFallbackUrls(),
// The curated keyless free chain (see FREE_KEYLESS_MAINNET above), ending
// with the most-throttled public cluster.
...FREE_KEYLESS_MAINNET,
- // Paid metered reserve (mainnet only — devnet URLs would cross clusters).
+ // Paid metered reserve (mainnet only: devnet URLs would cross clusters).
// Dead last BY DESIGN: these bill against a monthly quota, so they serve
// only when every free lane above is down or throttled at once.
...lastResortUrls(),
@@ -739,7 +739,7 @@ export function solanaRpcEndpoints(network = 'mainnet', url = null) {
}
/**
- * The keyed / metered mainnet lanes — every endpoint we PAY for, in the same
+ * The keyed / metered mainnet lanes: every endpoint we PAY for, in the same
* forms solanaRpcEndpoints() builds them. Free keyless nodes are excluded.
* Used by the lane-health sensor to answer "are we still on paid capacity, or
* has the whole premium tier gone dark and left us on free public nodes?"
@@ -771,7 +771,7 @@ function paidMainnetEndpoints() {
* cooldown and, critically, whether ANY paid lane is still serving.
*
* The blind spot this closes: before 2026-07-29 the only RPC sensor watched
- * Helius, and it read per-instance memory — so a fresh instance reported
+ * Helius, and it read per-instance memory: so a fresh instance reported
* "premium RPC healthy" while the plan was hard-exhausted, and QuickNode's daily
* cap and Alchemy's monthly cap had no sensor at all. All three were exhausted
* simultaneously and nothing surfaced it. Because the cooldown map is now
@@ -835,21 +835,21 @@ export function formatCooldown(ms) {
return ms < 60_000 ? `${Math.round(ms / 1000)}s` : `${Math.round(ms / 60_000)}m`;
}
-// JSON-RPC error codes that mean "this provider can't serve you right now" — a
+// JSON-RPC error codes that mean "this provider can't serve you right now", a
// capacity/quota/auth/staleness problem the NEXT provider may not share, so we
// fail over instead of surfacing it. Crucially this is how an exhausted paid plan
// answers: HTTP 200 with `{"error":{"code":-32429,"message":"max usage reached"}}`
-// — no rotate-worthy HTTP status, so without this it leaks straight to the caller.
+//: no rotate-worthy HTTP status, so without this it leaks straight to the caller.
// Method/data errors (-32600 invalid request, -32601 method not found, -32602
// invalid params, -32002 tx simulation failed) are deterministic across providers
-// and are intentionally excluded — rotating on those would just retry a guaranteed
+// and are intentionally excluded: rotating on those would just retry a guaranteed
// failure on every lane.
const PROVIDER_CAPACITY_CODES = new Set([
-32429, // Helius / common: max usage / quota reached
-32029, // OnFinality / common: too many requests
-32052, // Ankr: key not allowed / forbidden
- -32005, // node is behind by N slots — a fresher node may answer
- -32004, // block/slot not available yet — another node may have it
+ -32005, // node is behind by N slots: a fresher node may answer
+ -32004, // block/slot not available yet: another node may have it
-32003, // QuickNode: daily/request limit reached (capped), the next lane serves
429, // Alchemy: monthly capacity exceeded, reported as a JSON-RPC code
]);
@@ -870,8 +870,8 @@ const PROVIDER_CAPACITY_CODES = new Set([
// demotion, never a lane bench: the lane is healthy for every other shape.
const JSONRPC_INTERNAL_ERROR = -32603;
-// A provider that refuses one call shape — by paid-tier gate, by policy, or by
-// switching the method off — answers with a method-shaped JSON-RPC error, and the
+// A provider that refuses one call shape: by paid-tier gate, by policy, or by
+// switching the method off: answers with a method-shaped JSON-RPC error, and the
// dangerous variant answers HTTP 200 so no status-driven rotation fires. Measured
// on the live free lanes 2026-07-30:
// • PublicNode getProgramAccounts → 200 + {code:-32010, "… excluded from account
@@ -885,7 +885,7 @@ const JSONRPC_INTERNAL_ERROR = -32603;
// plans only", a code otherwise indistinguishable from a genuinely absent
// method (which IS deterministic and must never rotate)
// Every one is lane-and-method specific, so the disposition is: fail this request
-// over to the next lane, and demote THIS method on THIS lane — never the lane.
+// over to the next lane, and demote THIS method on THIS lane, never the lane.
// Unclassified, the 200-status ones surfaced straight to the caller and hard-failed
// the $THREE holder-gating and token-balance readers (api/_lib/balances.js,
// api/_lib/coin/holders.js, api/_lib/embed-gate.js, api/scene/gate-check.js)
@@ -912,7 +912,7 @@ function isProviderCapacityError(rpcError) {
// transparent failover: that error is web3.js choking on a 200 body that is NOT a
// well-formed JSON-RPC response (empty, HTML interstitial, truncated JSON, or a
// `{jsonrpc,id}` envelope with neither `result` nor `error`). We detect every one
-// of those shapes here — plus provider-capacity JSON-RPC errors — and route past
+// of those shapes here: plus provider-capacity JSON-RPC errors, and route past
// the bad node instead of handing the caller something it cannot parse.
export function classifyRpcBody(body) {
const trimmed = (body || '').trim();
@@ -931,7 +931,7 @@ export function classifyRpcBody(body) {
bodyText: '',
};
}
- // Single response or a JSON-RPC batch array — every element must be a valid envelope.
+ // Single response or a JSON-RPC batch array: every element must be a valid envelope.
const items = Array.isArray(parsed) ? parsed : [parsed];
if (items.length === 0) {
return {
@@ -953,7 +953,7 @@ export function classifyRpcBody(body) {
const hasResult = 'result' in item;
const hasError = 'error' in item;
if (!hasResult && !hasError) {
- // Neither field present — the exact shape that produces the empty-`received:`
+ // Neither field present: the exact shape that produces the empty-`received:`
// StructError. `result: null` is fine (the key is present); this catches a
// genuinely truncated/garbage envelope.
return {
@@ -998,9 +998,9 @@ export function classifyRpcBody(body) {
// Rotate this endpoint out of service on a 401/403 (bad/expired key on this
// provider only), 404/408/410 (the endpoint URL itself is dead, misrouted, or
-// timing out — a live JSON-RPC node answers a POST with method-not-found as a
+// timing out: a live JSON-RPC node answers a POST with method-not-found as a
// 200 + JSON-RPC error body, never an HTTP 404, so a 404 means the configured
-// URL is wrong, not the request), 429 (rate-limited), or 5xx (provider down) —
+// URL is wrong, not the request), 429 (rate-limited), or 5xx (provider down) -
// all of which the next provider may not share. Other 4xx are real request
// errors, identical on every provider, so they're returned to the caller as-is.
export function shouldRotate(status) {
@@ -1090,7 +1090,7 @@ export function throwDisposition({ callerAborted, attemptTimedOut, hasMethods })
// is fine, and it serves the very same call happily one at a time. A plain 400
// also does not rotate (see shouldRotate: other 4xx are caller errors identical
// on every lane), so left unclassified it surfaced raw and hard-failed the
-// caller — which is exactly how the pump.fun MCP `get_token_trades` tool died
+// caller: which is exactly how the pump.fun MCP `get_token_trades` tool died
// with "400 Bad Request: Maximum number of 'getTransaction' calls in a batch
// request is 1" on every attempt, while every other tool on the same lane worked.
//
@@ -1175,19 +1175,19 @@ export function rpcBatchCaps(now = Date.now()) {
}
// Rotating fetch backing a Connection. It NEVER surfaces a rotate-worthy status
-// (401/403/429/5xx) to @solana/web3.js — it either returns a healthy response or
-// throws — so web3.js's internal 429 backoff loop ("Server responded with 429 …
+// (401/403/429/5xx) to @solana/web3.js: it either returns a healthy response or
+// throws: so web3.js's internal 429 backoff loop ("Server responded with 429 …
// Retrying after Nms") never fires. Cooldowns live in the process-wide map, so a
// quota-dead provider is skipped on the very next call (and next cron tick), not
// re-probed every time.
//
// Log severity tracks actionability, not event count. A single provider getting
// parked while the call transparently lands on the next one is the failover doing
-// its job — the request still succeeds (HTTP 200), so it logs at INFO. Emitting it
+// its job: the request still succeeds (HTTP 200), so it logs at INFO. Emitting it
// at WARN flooded Vercel's `level:warning` view with non-actionable failover
-// chatter (the source of the recurring "[solana-rpc] … 429 — cooling" warnings).
-// The genuinely actionable condition — every provider in the chain failing within
-// one request, so the caller gets nothing back — is the only WARN.
+// chatter (the source of the recurring "[solana-rpc] … 429, cooling" warnings).
+// The genuinely actionable condition: every provider in the chain failing within
+// one request, so the caller gets nothing back: is the only WARN.
export function makeRotatingFetch(endpoints) {
return async function rotatingFetch(_info, init) {
// The call shapes in this request. Empty for an unreadable body, which makes
@@ -1230,7 +1230,7 @@ export function makeRotatingFetch(endpoints) {
// the endpoint so the caller rotates on. It NEVER returns an
// unvalidated body: a 200 carrying an empty/HTML/truncated payload, a
// `{jsonrpc,id}` envelope missing `result`, or a 200 + JSON-RPC capacity
- // error is treated as a failure — web3.js would otherwise choke on it with a
+ // error is treated as a failure: web3.js would otherwise choke on it with a
// `StructError`, and the /api/solana-rpc proxy would forward the garbage (an
// empty `[]`) straight to the browser.
// The batch this request carries, if it is one. Null for a single call, which
@@ -1241,7 +1241,7 @@ export function makeRotatingFetch(endpoints) {
// back into the array the caller is waiting for. Order is preserved (web3.js
// matches on id, but a caller reading positionally must not be surprised).
// Throws on the first sub-request that fails validation, so the caller rotates
- // exactly as it would for any other lane failure — never a partial array.
+ // exactly as it would for any other lane failure: never a partial array.
const sendUnbatched = async (url, signal) => {
const envelopes = new Array(batch.length);
let cursor = 0;
@@ -1281,7 +1281,7 @@ export function makeRotatingFetch(endpoints) {
// is cheaper to rotate than to unroll against a lane that caps at 1.
const splittable = !!batch && batch.length <= MAX_BATCH_SPLIT;
try {
- // This lane already told us it caps batches for these shapes — skip the
+ // This lane already told us it caps batches for these shapes, skip the
// probe request that only re-learns it and go straight to singles.
if (splittable && isBatchCapped(url, methods)) return { response: await sendUnbatched(url, signal) };
@@ -1400,11 +1400,11 @@ export function makeRotatingFetch(endpoints) {
// force a wider sweep that would just re-hammer known-bad lanes.
if (attempted) break;
}
- // Reached the end with every provider failing in this one request — the caller
+ // Reached the end with every provider failing in this one request, the caller
// gets a thrown error (→ a clean 502 from the proxy), never garbage. THIS is
// worth a warning: the whole failover chain is down, not just one lane.
console.warn(
- `[solana-rpc] all ${endpoints.length} endpoints failed this request — ${lastErr?.message || 'unknown error'}`,
+ `[solana-rpc] all ${endpoints.length} endpoints failed this request, ${lastErr?.message || 'unknown error'}`,
);
throw lastErr || new Error('all solana rpc endpoints failed');
};
diff --git a/api/forge.js b/api/forge.js
index 5b5019156..03a3bd8e9 100644
--- a/api/forge.js
+++ b/api/forge.js
@@ -1,5 +1,5 @@
/**
- * Forge — browser-facing text/image → 3D model generator + auto-rigger.
+ * Forge: browser-facing text/image → 3D model generator + auto-rigger.
*
* POST /api/forge { prompt, aspect_ratio?, path?, tier?, backend? } → text→3D
* POST /api/forge { image_urls[], prompt?, path?, tier?, backend? } → image→3D
@@ -9,13 +9,13 @@
* GET /api/forge?catalog → tier/backend/cost matrix
*
* Two request axes select how a mesh is produced (see api/_lib/forge-tiers.js):
- * • path — "image" (image-intermediate: text→image→mesh via FLUX + TRELLIS,
+ * • path : "image" (image-intermediate: text→image→mesh via FLUX + TRELLIS,
* the fast default; or Hunyuan3D self-host), "geometry" (geometry-
* first: native text→mesh / image→mesh via Meshy or Tripo, no
* synthesized intermediate view, higher geometric ceiling), or
* "sketch" (a drawing + a prompt naming it → TripoSG-scribble,
* self-host; untextured geometry).
- * • tier — draft | standard | high — the target polygon budget + texture
+ * • tier : draft | standard | high: the target polygon budget + texture
* richness. The high tier yields a visibly denser mesh.
* Every job result reports the path + tier + backend that produced it.
*
@@ -23,23 +23,23 @@
* (request header `x-forge-provider-key`, or the signed-in user's stored key).
* Without one, the geometry path returns a designed `needs_key` state.
*
- * Optional output controls (every field off by default — see
- * api/_lib/forge-options.js — an old request that never sends any of these
+ * Optional output controls (every field off by default, see
+ * api/_lib/forge-options.js: an old request that never sends any of these
* behaves exactly as before):
- * • seed — integer, reproducible generation on lanes that expose one.
- * • output_format — "glb" (default) | "glb-draco" | "glb-meshopt": a real
+ * • seed : integer, reproducible generation on lanes that expose one.
+ * • output_format : "glb" (default) | "glb-draco" | "glb-meshopt": a real
* post-generation @gltf-transform compression pass (api/_lib/glb-compress.js).
- * • texture_size / target_polycount — poly-aware backends only (Hunyuan3D,
+ * • texture_size / target_polycount: poly-aware backends only (Hunyuan3D,
* Meshy, Tripo, Rodin, TripoSG); ignored (never 422s) on TRELLIS.
- * • director: false — SKIPS the IBM Granite "art director" prompt rewrite
+ * • director: false : SKIPS the IBM Granite "art director" prompt rewrite
* that otherwise runs before a text prompt synthesizes its reference image
* (the same director the free MCP tools use). On by default, because it
* fails soft to the raw prompt and rides the free-first LLM chain, so it
* can only help. Documented at /docs/3d-api.
- * • force_regenerate: true — skip the result cache read for this call (the
+ * • force_regenerate: true: skip the result cache read for this call (the
* cache still gets refreshed with the new result).
* A finished generation's metadata carries `quality` (api/_lib/glb-quality.js
- * — valid/flag/score/reasons) and, when compression was requested,
+ *: valid/flag/score/reasons) and, when compression was requested,
* `compression` (mode + before/after byte counts). A flagged degenerate/low
* result is retried once automatically on the lanes that complete inline
* within one request (free NVIDIA NIM, HuggingFace Spaces, BYOK-sync).
@@ -49,7 +49,7 @@
*
* This is the public, auth-free twin of the 3D Studio MCP server (api/mcp-3d.js).
* No mock paths: if a selected backend isn't configured the endpoint returns a
- * clean 503/501 and the page renders a designed state — it never fabricates a
+ * clean 503/501 and the page renders a designed state, it never fabricates a
* model.
*/
@@ -147,17 +147,17 @@ import { meshDirectorFor, meshSubjectClass, resolveLogoPrompt } from './_lib/for
// Circuit-breaker key + window for the free NVIDIA NIM TRELLIS text→3D lane. The
// hosted NVCF gateway can degrade so a submit neither completes nor hands back a
-// pollable id before our timeout — a single slow window otherwise makes every
+// pollable id before our timeout: a single slow window otherwise makes every
// text prompt re-pay that full timeout before failing over to the reconstruct
// lane. A short cooldown (recorded on a health failure, checked before the lane
// runs) lets subsequent requests skip a degraded lane and go straight to a
// working one; it expires on its own so a recovered lane is retried promptly.
-// Best-effort via the shared cache — a miss just means "not cooling".
+// Best-effort via the shared cache: a miss just means "not cooling".
const NIM_TRELLIS_COOLDOWN_KEY = 'forge-nim-trellis';
// Sideline the free NIM lane after a failure. The cooldown exists to avoid
// re-paying the expensive submit-timeout HANG, so a socket timeout / unreachable
// host (no HTTP status came back) earns the full window. A fast gateway 5xx (a
-// 504/503 the gateway returned promptly — a cold-start/capacity blip the
+// 504/503 the gateway returned promptly: a cold-start/capacity blip the
// in-provider retry already rode) only earns a short window, so a single transient
// 504 doesn't sideline the free lane for two minutes and dump every text prompt on
// the paid lane. See nimCooldownSeconds().
@@ -165,7 +165,7 @@ const NIM_FORGE_COOLDOWN_SECONDS = 120;
const NIM_FORGE_GATEWAY_COOLDOWN_SECONDS = 30;
// The platform-keyed paid reconstruct lane (Replicate TRELLIS) recorded as down.
-// Set only on an out-of-credit/billing failure — which won't self-heal until ops
+// Set only on an out-of-credit/billing failure: which won't self-heal until ops
// tops the account up, so the window is long (reason 'auth'). The NIM-cooldown
// router reads it to avoid skipping the free lane in favour of a dead paid lane.
const REPLICATE_PAID_COOLDOWN_KEY = 'forge-replicate-paid';
@@ -240,7 +240,7 @@ const VALID_ASPECT = new Set(['1:1', '4:3', '3:4', '16:9', '9:16']);
const MAX_VIEWS = 6;
// Guard for caller-supplied reference image / source GLB URLs. http(s) only,
-// bounded length — we forward these to the reconstruction/rig provider, so we
+// bounded length: we forward these to the reconstruction/rig provider, so we
// never accept data: URLs or unbounded strings.
const HTTP_URL_RE = /^https?:\/\/[^\s]+$/i;
@@ -256,7 +256,7 @@ function clientKeyFrom(req) {
return hashClient(Array.isArray(raw) ? raw[0] : raw);
}
-// /forge is auth-free and the overwhelming majority of calls are anonymous —
+// /forge is auth-free and the overwhelming majority of calls are anonymous -
// but when a caller DOES carry a session cookie (the browser /create/studio
// flow while logged in), attach their user_id to the durable creation so it
// surfaces on their public portfolio (/u/:username → "Models" tab). Resolved
@@ -284,7 +284,7 @@ function parseTier(body) {
return TIER_IDS.includes(t) ? t : DEFAULT_TIER;
}
-// "needs a BYOK key" — a designed, branchable state (mirrors rig_unconfigured)
+// "needs a BYOK key": a designed, branchable state (mirrors rig_unconfigured)
// rather than a generic error, so the page can prompt for the key inline.
function needsKey(res, providerName) {
const meta = BACKENDS[providerName];
@@ -297,7 +297,7 @@ function needsKey(res, providerName) {
// Normalize the caller's reference image input into an ordered, de-duplicated
// list of view URLs. Accepts the multi-view `image_urls: string[]` form and the
-// legacy single `image_url: string` (backward compatible — a single string
+// legacy single `image_url: string` (backward compatible, a single string
// still works exactly as before). Empty/blank/duplicate entries are dropped.
function parseImageUrls(body) {
let raw;
@@ -325,8 +325,8 @@ function unconfigured(res) {
});
}
-// Whether a thrown provider error means the upstream itself is unavailable —
-// throttled, over-quota, unreachable, or 5xx — as opposed to a client/config
+// Whether a thrown provider error means the upstream itself is unavailable -
+// throttled, over-quota, unreachable, or 5xx: as opposed to a client/config
// fault. Both never-dead-end fallbacks (image→3D to the self-hosted Hunyuan3D
// worker, text→3D to the free NVIDIA NIM lane) degrade on exactly these so a
// generation rides out a transient upstream outage instead of failing the user.
@@ -342,7 +342,7 @@ function isUpstreamUnavailable(err) {
// A leaked paid-account billing/credit message from the platform's OWN vendor
// (e.g. Replicate "You have insufficient credit to run this model… purchase
-// credit") is internal infra state — surfacing it to the user is both useless
+// credit") is internal infra state: surfacing it to the user is both useless
// (they can't fund our account) and a billing-state leak. Detect it so the
// boundary can answer with an honest, generic "temporarily unavailable" instead.
// BYOK callers are excluded at the call site: a credit message about THEIR OWN
@@ -356,9 +356,9 @@ function isPaidCreditFailure(err) {
// ── Realism modules (land concurrently; imported lazily + fail-open) ───────────
// Two dedicated modules sharpen the realism path without ever becoming a hard
// dependency of it:
-// • forge-reference-image.js — seeds text→3D reconstruction with a Vertex-Gemini
+// • forge-reference-image.js: seeds text→3D reconstruction with a Vertex-Gemini
// photoreal reference image (falls back to the standing text→image provider).
-// • forge-quality-gate.js — scores a finished generation (vision QA) and
+// • forge-quality-gate.js : scores a finished generation (vision QA) and
// supplies the retry hint that drives a bounded auto-retry.
// Both are consumed through the lazy, fail-open shims below: an absent module (not
// yet deployed) or a down Vertex backend degrades to the standing behaviour, so
@@ -374,8 +374,8 @@ function readForgeEnv(name) {
// Photoreal reconstruction reference. Prefers the dedicated Vertex-Gemini module;
// falls back to the standing text→image provider (the FLUX/Imagen/NIM chain) when
-// the module is absent or Vertex is unavailable. Returns { imageUrl, model } —
-// exactly textToImage()'s shape — so the call site is a drop-in swap.
+// the module is absent or Vertex is unavailable. Returns { imageUrl, model } -
+// exactly textToImage()'s shape: so the call site is a drop-in swap.
export async function seedReferenceImage({ prompt, aspect, seed, skipNim }) {
if (readForgeEnv('FORGE_REFERENCE_IMAGE') !== 'off') {
try {
@@ -431,7 +431,7 @@ export function qualityGateAppliesTo(tierId, quality = undefined) {
if (s === 'adaptive') return shouldEscalateToVisionQA(quality);
return false; // 'high' scope, non-high tier
}
-// Bounded retry cap — default 1, clamped 0..2 so a quality retry can never turn one
+// Bounded retry cap: default 1, clamped 0..2 so a quality retry can never turn one
// generation into an unbounded credit/latency sink.
export function qualityGateMaxRetries() {
const raw = readForgeEnv('FORGE_QUALITY_GATE_MAX_RETRIES');
@@ -473,7 +473,7 @@ export async function scoreQualityGate({ glbUrl, prompt, tier, backend, referenc
return { pass: true, skipped: true, qa_available: false };
}
-// True only for an explicit failing verdict — a skipped/absent gate never retries.
+// True only for an explicit failing verdict: a skipped/absent gate never retries.
export function qualityGateFailed(verdict) {
return Boolean(verdict) && verdict.skipped !== true && verdict.pass === false;
}
@@ -559,14 +559,14 @@ async function qualityGateFinalize({ tierId, prompt, path, backend, referenceIma
// degrades to when Replicate is unreachable / over-quota (HTTP 429/5xx).
// Returns true once it has written a 200 response, or false when the lane is
// itself unavailable (so the caller can fall through to the next lane). Prompt
-// is required — NVCF is text-only; photo submissions never reach here.
+// is required: NVCF is text-only; photo submissions never reach here.
async function runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path, opts = null, cacheKey = null }) {
let submitted;
try {
const nv = await loadNvidiaProvider();
submitted = await nv.textTo3d({ prompt, tier, seed: opts?.seed ?? undefined });
} catch (err) {
- // A timed-out / unreachable / throttled / 5xx NIM lane is degraded — cool it
+ // A timed-out / unreachable / throttled / 5xx NIM lane is degraded, cool it
// down so the next request skips the submit-timeout gamble and fails over
// fast. A 4xx (bad input / key) is not a lane-health fault, so it never cools.
if (isUpstreamUnavailable(err)) {
@@ -622,7 +622,7 @@ async function runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path, opt
// One auto-retry on a flagged low-quality/degenerate output (CLAUDE.md: no
// silent mediocrity). Only worth attempting when the free NIM lane already
- // completed synchronously once — a second synchronous completion is the
+ // completed synchronously once: a second synchronous completion is the
// common case, so this stays a bounded, in-request retry rather than a
// background job. Best-effort: any retry failure just keeps the first result.
let retried = false;
@@ -764,14 +764,14 @@ async function runNvidiaTextLane({ req, res, ip, prompt, aspect, tier, path, opt
}
// Free Hugging Face Spaces image→3D lane (Hunyuan3D / TRELLIS / TripoSR on free
-// GPU Spaces — the same provider the avatar reconstruction pipeline runs). The
+// GPU Spaces: the same provider the avatar reconstruction pipeline runs). The
// platform photo→3D default is the Replicate TRELLIS lane; when that account is
// over-quota or unreachable a photo upload would otherwise dead-end, because the
// free NVIDIA NIM fallback is text-only. This lane gives image mode the same
-// "never dead-end" guarantee text mode already has — gated on HF_TOKEN, so it is
+// "never dead-end" guarantee text mode already has: gated on HF_TOKEN, so it is
// a transparent no-op on deployments that don't set it. The provider blocks
// until the GLB is ready (Space queue + inference, within the 300s budget), so
-// this returns status:'done' synchronously like the NVIDIA sync branch — no
+// this returns status:'done' synchronously like the NVIDIA sync branch, no
// poll handle to route. Returns true once a 200 is written, false when the lane
// is unavailable so the caller can surface its own error.
// One-shot guard so the "HuggingFace lane not configured" notice is logged once
@@ -806,7 +806,7 @@ async function runHfImageLane({
const mod = await import('./_providers/huggingface.js');
provider = mod.createRegenProvider();
} catch (err) {
- // HF_TOKEN absent or the Space chain is empty — the lane isn't available
+ // HF_TOKEN absent or the Space chain is empty: the lane isn't available
// on this deployment; fall through so the caller surfaces the real error.
// A missing token is a STATIC deployment condition, not a per-request fault:
// logging it on every forge call floods the function logs (it was the
@@ -826,9 +826,9 @@ async function runHfImageLane({
// The Space call BLOCKS this serverless worker for up to ~280s. Under an influx
// that exhausts the Vercel worker pool and stalls /forge for everyone, so we cap
// fleet-wide concurrent holds with a self-healing TTL lease. Over the cap the
- // lane reports "not served" (false) and the caller degrades — to the paid
+ // lane reports "not served" (false) and the caller degrades, to the paid
// reconstruct fallback on the free-first path, or a designed "free lane busy"
- // error on an explicit free pick — instead of piling onto an exhausted pool.
+ // error on an explicit free pick: instead of piling onto an exhausted pool.
const slot = await acquireBlockingSlot('hf', {
max: SCALE_LIMITS.hfConcurrent,
ttlMs: SCALE_LIMITS.hfSlotTtlMs,
@@ -892,7 +892,7 @@ async function runHfImageLane({
});
// One auto-retry on a flagged low-quality/degenerate output. Only attempted
- // when a concurrency slot is free right now — the HF lane is capacity-capped,
+ // when a concurrency slot is free right now: the HF lane is capacity-capped,
// so a busy fleet keeps the first (flagged) result rather than starving
// other callers of their turn on the free Spaces.
let retried = false;
@@ -1033,18 +1033,18 @@ async function startJob(req, res) {
const body = await readJson(req, 8_000).catch(() => null);
// Two reconstruction modes share this path:
- // • image→3D — a caller supplies one or more reference views (image_url or
+ // • image→3D: a caller supplies one or more reference views (image_url or
// image_urls[]); we reconstruct directly and skip the text-to-image stage.
// With >1 view the provider fuses them (multi-view conditioning). An
// optional prompt may still guide the model where it accepts one.
- // • text→3D — no images; we synthesize the reference image from the prompt
+ // • text→3D: no images; we synthesize the reference image from the prompt
// with FLUX first, then reconstruct.
let imageUrls = parseImageUrls(body);
const isImageMode = imageUrls.length > 0;
const prompt = typeof body?.prompt === 'string' ? body.prompt.trim() : '';
// Optional, additive output controls (seed, output_format/compression,
- // texture_size, target_polycount) — see _lib/forge-options.js. Every field is
+ // texture_size, target_polycount): see _lib/forge-options.js. Every field is
// off by default, so a request that never sends them behaves exactly as
// before. An explicitly-present but invalid value is a 400 with an actionable
// message; an absent field is never an error.
@@ -1067,7 +1067,7 @@ async function startJob(req, res) {
// Subject class (organic / hard-surface / null) steers the High realism tier's
// self-host lane order: Hunyuan3D-2.1 leads on people / creatures / detailed
// organics, self-host TRELLIS leads on hard-surface / mechanical subjects. Pure
- // keyword heuristic on the prompt — zero latency, no LLM — and a no-op for every
+ // keyword heuristic on the prompt: zero latency, no LLM, and a no-op for every
// tier below High (see freeLaneCandidates). An image submission with no guidance
// prompt classifies to null and keeps the default order.
const subjectClass = classifyForgeSubject(prompt);
@@ -1083,7 +1083,7 @@ async function startJob(req, res) {
// can't stack a second submit-timeout window on the same request.
let nimGatewayDegraded = false;
- // Pay-per-use (Token Utility — consumption lever): set to { paymentId, refId,
+ // Pay-per-use (Token Utility: consumption lever): set to { paymentId, refId,
// settledAt, redeemed? } once a non-holder's settled $THREE payment is accepted
// in lieu of holding. The payment is validated at the gate, claimed atomically
// just before dispatch, and released if the generation fails before delivery.
@@ -1100,7 +1100,7 @@ async function startJob(req, res) {
// must never hand one payer's job to another).
let requestHash = null;
- // The geometry path is BYOK-only — no free model does native text→geometry.
+ // The geometry path is BYOK-only: no free model does native text→geometry.
// So when the caller didn't explicitly pick a backend and has no key for the
// default geometry engine, transparently serve the free image lane (NVIDIA
// NIM on draft, TRELLIS otherwise) instead of a dead "needs key" error. The
@@ -1117,7 +1117,7 @@ async function startJob(req, res) {
// Health-aware lane selection: when the caller didn't name a backend, consult a
// cheap, cached liveness snapshot of the free lanes and skip any our probe (or a
- // recent submit failure) marks down — so a cold or unreachable self-host worker
+ // recent submit failure) marks down: so a cold or unreachable self-host worker
// is routed AROUND before submit, not failed-over after. Only the platform free
// lanes (image/sketch) are candidates; geometry is BYOK and unaffected. Pure
// best-effort: any snapshot error leaves the env-resolved backendId in place, so
@@ -1145,7 +1145,7 @@ async function startJob(req, res) {
// Honest cold-start signal for a chosen self-host lane: true only when the
// liveness probe reached the worker but it answered slowly (a scale-to-zero
// container spinning up). Reuses the cached snapshot, so the common path pays no
- // extra probe. Used to widen the ETA + flag `cold_start` in the response — never
+ // extra probe. Used to widen the ETA + flag `cold_start` in the response, never
// to fabricate progress; the client's real polling still drives actual status.
const coldStartFor = async (id) => {
if (!isSelfHostBackend(id) || !coldStartSecondsFor(id)) return false;
@@ -1159,12 +1159,12 @@ async function startJob(req, res) {
};
// Content-addressed result cache (see _lib/forge-cache.js): a text→3D request
- // on a platform-keyed lane (never BYOK — that spends the caller's own account,
+ // on a platform-keyed lane (never BYOK: that spends the caller's own account,
// so it must never be replayed to a stranger) can be served instantly from a
// prior identical generation instead of re-running the GPU pipeline. Captured
// once, before any lane-failover churn reassigns `backendId` below, so the
// same cache key is used to both look up and (on completion) store this
- // request's result — a failover to a different lane just means a miss, never
+ // request's result: a failover to a different lane just means a miss, never
// a wrong hit. `force_regenerate: true` skips the read (a fresh run is still
// written back, keeping the cache warm). High tier is paid/gated per caller
// and is never cached, matching the module's own privacy boundary.
@@ -1195,13 +1195,13 @@ async function startJob(req, res) {
}
}
- // $THREE hold-to-access gate (Token Utility v1) — the High tier (200k poly +
+ // $THREE hold-to-access gate (Token Utility v1): the High tier (200k poly +
// PBR, textured) is the platform's premium quality tier. It now runs on a
// free-for-us engine (HuggingFace Hunyuan3D) like every other tier, so this is
- // a pure monetization gate — we charge for higher quality, not to recover
+ // a pure monetization gate: we charge for higher quality, not to recover
// vendor spend: reserved for holders (Bronze+, $25 hold) or a presented tier
// pass, otherwise a hold-or-pay 402. BYOK backends are exempt (the caller pays
- // their own vendor key — key-gated, not hold-gated). Draft and Standard are
+ // their own vendor key: key-gated, not hold-gated). Draft and Standard are
// never gated, and internal cron seed jobs bypass it entirely.
// requireFeatureAccess writes the 402 (three_hold_required) itself and returns
// { ok:false }; on a holder it writes nothing and lets the job proceed.
@@ -1242,7 +1242,7 @@ async function startJob(req, res) {
price_usd: priceUsd,
balance_usd: acct.balanceUsd,
top_up_url: '/credits',
- message: `Generating a High model costs $${priceUsd.toFixed(2)} in credits — your balance is $${acct.balanceUsd.toFixed(2)}. Top up to continue.`,
+ message: `Generating a High model costs $${priceUsd.toFixed(2)} in credits, your balance is $${acct.balanceUsd.toFixed(2)}. Top up to continue.`,
});
}
creditsCharge = { user: creditUser, action: 'forge.high', ref: refId || randomUUID() };
@@ -1288,7 +1288,7 @@ async function startJob(req, res) {
// above. It stops the influx/abuse failure mode where many callers each stay
// under their own cap but collectively drain spend. BYOK lanes spend the
// caller's own key, so the platform-budget ceiling must never throttle them.
- // When it trips the free NVIDIA / HuggingFace lanes stay open — paid capacity
+ // When it trips the free NVIDIA / HuggingFace lanes stay open, paid capacity
// degrades, it never dead-ends.
if (!isFreeLane && !backendMeta?.byok) {
const globalRl = await limits.mcp3dGenerateGlobal();
@@ -1296,7 +1296,7 @@ async function startJob(req, res) {
return rateLimited(
res,
globalRl,
- 'Paid 3D generation is at capacity right now — switch to a free engine (NVIDIA or Hugging Face), or try again shortly.',
+ 'Paid 3D generation is at capacity right now: switch to a free engine (NVIDIA or Hugging Face), or try again shortly.',
);
}
// Per-identity daily ceiling: closes the rotating-IP abuse path the per-IP
@@ -1341,7 +1341,7 @@ async function startJob(req, res) {
// Vision pre-check (Consumer 1 of the shared vision helper): catch a photo
// that can't be reconstructed BEFORE it burns a generation slot. Validates
- // the primary view only. Fail-open — a vision outage returns ok:true and we
+ // the primary view only. Fail-open: a vision outage returns ok:true and we
// proceed exactly as before (validateForgeImage owns that contract). The
// user can override a verdict they disagree with via `skip_validation:true`
// (e.g. a stylized reference our checker is too cautious about).
@@ -1349,7 +1349,7 @@ async function startJob(req, res) {
// checker is trained to reject, and exactly what TripoSG-scribble wants.
if (body?.skip_validation !== true && path !== 'sketch') {
// The forge client key is a hashed client-supplied header, NOT an OAuth
- // client — it has no row in oauth_clients, so it must never land in the
+ // client: it has no row in oauth_clients, so it must never land in the
// FK-constrained usage_events.client_id (that fails the insert and the
// whole spend event is silently dropped). Attribute it via meta instead.
// Every view is checked in parallel, not just the primary: a bad
@@ -1385,14 +1385,14 @@ async function startJob(req, res) {
return json(res, 400, {
error: 'invalid_prompt',
message:
- 'Describe one subject in 3–1000 characters, or pass image_url / image_urls for image-to-3D.',
+ 'Describe one subject in 3-1000 characters, or pass image_url / image_urls for image-to-3D.',
});
}
const aspect = VALID_ASPECT.has(body?.aspect_ratio) ? body.aspect_ratio : '1:1';
// Sketch→3D is single-view and prompt-conditioned: the drawing is the only
// input image, and the prompt names what it depicts (TripoSG-scribble is a
- // text+scribble model — without the prompt it has nothing to disambiguate
+ // text+scribble model: without the prompt it has nothing to disambiguate
// rough strokes against).
if (path === 'sketch') {
if (!isImageMode) {
@@ -1410,26 +1410,26 @@ async function startJob(req, res) {
if (prompt.length < 3) {
return json(res, 400, {
error: 'invalid_prompt',
- message: 'Say what the sketch depicts (3–1000 characters) — the sketch model is prompt-conditioned.',
+ message: 'Say what the sketch depicts (3-1000 characters), the sketch model is prompt-conditioned.',
});
}
}
// path / tier / backendId were resolved above (the rate limiter is lane-aware).
- // An explicitly selected text-only backend can't serve a photo submission —
+ // An explicitly selected text-only backend can't serve a photo submission -
// say so plainly rather than failing upstream with an opaque 422.
if (isImageMode && BACKENDS[backendId]?.userImages === false) {
return json(res, 422, {
error: 'backend_text_only',
backend: backendId,
message:
- `${BACKENDS[backendId].label} generates from text prompts only — NVIDIA's hosted preview doesn't accept uploaded photos. ` +
+ `${BACKENDS[backendId].label} generates from text prompts only, NVIDIA's hosted preview doesn't accept uploaded photos. ` +
'Drop the backend field to use the default photo engine, or pick TRELLIS, Meshy, or Tripo.',
});
}
try {
- // Pay-per-use: claim the settled $THREE payment now — immediately before any
+ // Pay-per-use: claim the settled $THREE payment now, immediately before any
// provider work, so every cheap failure above (rate limit, moderation, bad
// input) left the payment reusable. The atomic claim (payment_id PRIMARY KEY)
// is the single-use source of truth: a concurrent retry of the same payment
@@ -1485,7 +1485,7 @@ async function startJob(req, res) {
// ── Sketch path (TripoSG-scribble, self-host) ───────────────────────────
// The drawing + prompt go straight to the TripoSG worker's scribble
- // pipeline. Geometry only — no synthesized intermediate view, no textures;
+ // pipeline. Geometry only: no synthesized intermediate view, no textures;
// the result panel's Retexture/Stylize tools pick up from there.
if (path === 'sketch') {
let gcp;
@@ -1522,7 +1522,7 @@ async function startJob(req, res) {
'Sketch-to-3D is not configured on this deployment (GCP_TRIPOSG_URL is not set).',
});
}
- // The sketch model is conditioned on the drawing — no other lane can
+ // The sketch model is conditioned on the drawing: no other lane can
// serve it, so there is nothing to fail over to. Cool the worker so the
// next request skips it while it recovers, and return a designed,
// retryable state instead of a raw provider error.
@@ -1542,7 +1542,7 @@ async function startJob(req, res) {
}
// Wrap the GCP job envelope in a forge token so polling routes back to
- // the GCP provider — same idiom as the Hunyuan3D lane.
+ // the GCP provider: same idiom as the Hunyuan3D lane.
const token = encodeJobToken({ provider: 'gcp', kind: null, taskId: job.extJobId });
const creationId = await createCreation({
clientKey: clientKeyFrom(req),
@@ -1583,12 +1583,12 @@ async function startJob(req, res) {
}
// ── BYOK geometry-style providers (Meshy / Tripo / Rodin / Stability) ────
- // A native 3D model emits mesh geometry directly — from the prompt
- // (text→geometry) or a single photo (image→3D) — with no synthesized
+ // A native 3D model emits mesh geometry directly: from the prompt
+ // (text→geometry) or a single photo (image→3D): with no synthesized
// intermediate view, so detail isn't capped by one image. These backends
// have no platform key; the caller supplies their own. Dispatch is a
// registry lookup on the backend's `byok` name (Replicate BYOK is handled
- // on the image-intermediate path below — it speaks a different interface).
+ // on the image-intermediate path below: it speaks a different interface).
const byokProvider = BACKENDS[backendId].byok;
const byokFactory = BYOK_PROVIDER_FACTORIES[byokProvider];
if (byokFactory) {
@@ -1620,14 +1620,14 @@ async function startJob(req, res) {
return json(res, 422, {
error: 'backend_image_only',
backend: backendId,
- message: `${BACKENDS[backendId].label} reconstructs from a reference image — attach one, or drop the backend to use a text→3D engine.`,
+ message: `${BACKENDS[backendId].label} reconstructs from a reference image, attach one, or drop the backend to use a text→3D engine.`,
});
}
const clientKey = clientKeyFrom(req);
// Synchronous completion (Stable Fast 3D): the provider already persisted
- // the GLB to R2 and handed back a durable url — no task to poll. Record a
+ // the GLB to R2 and handed back a durable url: no task to poll. Record a
// finished creation and return done so the client skips polling, exactly
// like the NVIDIA NIM synchronous path.
if (!submitted.taskId && submitted.resultGlbUrl) {
@@ -1723,8 +1723,8 @@ async function startJob(req, res) {
// TRELLIS on NIM emits the mesh natively from the prompt (no FLUX
// intermediate view) and needs no BYOK key. It serves prompt submissions
// on the image path as the free draft default; photo submissions never
- // resolve here (hosted preview is text-only — see the provider header).
- // The free NVIDIA NIM lane is a flaky synchronous upstream — NVCF can be
+ // resolve here (hosted preview is text-only: see the provider header).
+ // The free NVIDIA NIM lane is a flaky synchronous upstream, NVCF can be
// unreachable, accept the job but drop the request id, or finish with no
// artifact, and a missing module/key throws on load. Per the free-first
// "AI must never fail" policy none of these may surface as a dead 502: a
@@ -1735,12 +1735,12 @@ async function startJob(req, res) {
if (backendId === 'nvidia') {
nvidiaTried = true;
// Skip the submit-timeout gamble when the lane is in a recent-failure
- // cooldown — go straight to the reconstruct lane instead of re-hanging.
+ // cooldown: go straight to the reconstruct lane instead of re-hanging.
// BUT only when that reconstruct lane is a real destination: it free-firsts
// to HuggingFace and then the paid Replicate account, so it's viable when HF
// is configured OR the paid account isn't itself recorded out-of-credit. When
// both are gone, skipping NIM would route straight into a dead paid lane and
- // 503 the user — so we ignore the cooldown and give the free lane a real shot.
+ // 503 the user: so we ignore the cooldown and give the free lane a real shot.
const cooldowns = await providersInCooldown([
NIM_TRELLIS_COOLDOWN_KEY,
REPLICATE_PAID_COOLDOWN_KEY,
@@ -1764,11 +1764,11 @@ async function startJob(req, res) {
}
// ── Image-intermediate path (TRELLIS default, or Hunyuan3D self-host) ────
- // Hunyuan3D runs on its own Cloud Run worker (GCP_HUNYUAN3D_URL) — never
+ // Hunyuan3D runs on its own Cloud Run worker (GCP_HUNYUAN3D_URL), never
// the avatar pipeline controller, whose face pipeline fails every
// non-face image with "no face detected".
// Replicate BYOK runs the same reconstruction models on the caller's own
- // Replicate account — resolve their token up front (distinct from the
+ // Replicate account: resolve their token up front (distinct from the
// platform-keyed TRELLIS default).
let byokReplicateKey = null;
if (backendId === 'replicate_byok') {
@@ -1787,13 +1787,13 @@ async function startJob(req, res) {
} else if (backendId === 'replicate_byok') {
provider = createRegenProvider({ apiToken: byokReplicateKey });
} else if (backendId === 'huggingface') {
- // The free HF Spaces lane is driven by runHfImageLane() below — it
+ // The free HF Spaces lane is driven by runHfImageLane() below, it
// creates its own provider. We deliberately do NOT build a Replicate
// client here: creating one would 503 on a deployment that has no
// REPLICATE_API_TOKEN, breaking an explicitly-chosen free engine.
} else if (backendId === 'trellis_selfhost') {
// Driven by the dedicated self-host TRELLIS lane below, which builds
- // its own GCP provider. Same reasoning as huggingface — never build a
+ // its own GCP provider. Same reasoning as huggingface, never build a
// Replicate client here, or a deployment without REPLICATE_API_TOKEN
// would 503 on an explicitly-chosen free self-hosted engine.
} else {
@@ -1810,11 +1810,11 @@ async function startJob(req, res) {
});
}
if (backendId === 'replicate_byok') return needsKey(res, backendId);
- // The default TRELLIS (Replicate) provider couldn't be built — no
+ // The default TRELLIS (Replicate) provider couldn't be built, no
// REPLICATE_API_TOKEN. That alone is NOT "unconfigured" when the free
// HuggingFace Spaces lane is live: a degraded-from-NVIDIA text prompt, or
// a photo→3D request, must still reconstruct on the free lane rather than
- // dead-ending at a 503. Leave `provider` undefined and fall through — the
+ // dead-ending at a 503. Leave `provider` undefined and fall through, the
// free-first HF block below serves it, and the `!provider` guard further
// down raises a designed unavailable state only if every free lane is gone
// too. Mirrors the self-host TRELLIS failover (provider = undefined) above.
@@ -1856,7 +1856,7 @@ async function startJob(req, res) {
// Resolve the reference views: supplied directly (image→3D) or a single
// view synthesized from the prompt (text→3D). `referenceImageUrl` is the
- // primary view — the durable preview + the synthesis target.
+ // primary view: the durable preview + the synthesis target.
let referenceImageUrl;
let textToImageModel;
let views;
@@ -1874,10 +1874,10 @@ async function startJob(req, res) {
// Granite art-director pass (on by default; pass director:false to skip):
// rewrites the raw prompt into a richer, single-subject spec (form,
// per-part PBR materials, photoreal-by-default cues, composition
- // constraints) before it drives the FLUX/Vertex reference image — the
+ // constraints) before it drives the FLUX/Vertex reference image, the
// same director the free MCP tools use. Fail-soft: any failure (chat
// lane down, timeout) silently keeps the raw prompt, so running it by
- // default can only ever help, never break, a generation — and it rides
+ // default can only ever help, never break, a generation, and it rides
// the free-first LLM chain, so it costs no GCP/vendor spend. This is the
// single biggest lever on "does this look like a real photograph"
// available before the reference image is even generated.
@@ -1899,7 +1899,7 @@ async function startJob(req, res) {
if (directed) promptForReference = directed;
}
}
- // Report the rewrite only when it actually changed the brief — an
+ // Report the rewrite only when it actually changed the brief, an
// unchanged value means the model saw exactly what the user typed.
if (promptForReference && promptForReference !== prompt) directedPrompt = promptForReference;
// Seed the reconstruction reference from the dedicated Vertex-Gemini
@@ -1935,8 +1935,8 @@ async function startJob(req, res) {
}
// Explicitly chosen free HuggingFace lane. Unlike the trellis free-first
- // path below — which degrades to the paid Replicate lane when the free
- // Spaces are down — an explicit pick of the FREE engine must never silently
+ // path below: which degrades to the paid Replicate lane when the free
+ // Spaces are down: an explicit pick of the FREE engine must never silently
// fall through to a paid lane: that would spend credits the user
// deliberately opted out of. So we run the free Spaces and, if every one is
// busy/down, return a designed error the UI can act on (retry / switch engine).
@@ -1971,7 +1971,7 @@ async function startJob(req, res) {
params: {
images: views,
seed: opts.seed ?? undefined,
- // Tier-scaled sampler/export budgets — this is where standard/high
+ // Tier-scaled sampler/export budgets: this is where standard/high
// actually buy more quality on our own GPU (steps, kept geometry,
// texture resolution) instead of only a bigger advertised polycount.
quality: selfhostQualityForTier(tier.id),
@@ -2106,8 +2106,8 @@ async function startJob(req, res) {
}
// Free-first: exhaust the free reconstruct lane (HuggingFace Spaces) BEFORE
- // the paid Replicate default, so a forge call never spends on — or dead-ends
- // against — the paid account while a free lane can serve it. We already hold
+ // the paid Replicate default, so a forge call never spends on, or dead-ends
+ // against: the paid account while a free lane can serve it. We already hold
// the reference views (uploaded, or FLUX-synthesized above), so the free lane
// reconstructs from exactly what Replicate would have. Scoped to the default
// trellis lane: an explicitly chosen Hunyuan3D / Replicate-BYOK backend is
@@ -2156,7 +2156,7 @@ async function startJob(req, res) {
try {
// A self-host failover landed here with no paid provider configured (no
// REPLICATE_API_TOKEN) and the free HF lane above didn't serve the request
- // — there is no reconstruct lane left. Raise it as upstream-unavailable so
+ //: there is no reconstruct lane left. Raise it as upstream-unavailable so
// the catch below runs the remaining free fallbacks (Hunyuan3D → HF) and,
// if those are gone too, surfaces a designed unavailable state.
if (!provider) {
@@ -2167,7 +2167,7 @@ async function startJob(req, res) {
}
// Per-provider submit throttle: shed platform Replicate bursts to the free
// lane BEFORE they hit the account quota and turn into fleet-wide 429s. Only
- // the platform-keyed default lane is capped — BYOK lanes spend the caller's
+ // the platform-keyed default lane is capped: BYOK lanes spend the caller's
// own quota. Over-cap is thrown as upstream-unavailable so the existing
// fallback chain (self-host Hunyuan3D → free HuggingFace) absorbs it.
if (
@@ -2201,7 +2201,7 @@ async function startJob(req, res) {
// referenceImageUrl from textToImage(), so the same reconstruct
// fallbacks apply. Without this branch the outer catch re-checks
// nvidiaTried=true and skips NIM, leaving the user with a 429.
- // Scoped to the default trellis backend only — an explicitly chosen
+ // Scoped to the default trellis backend only: an explicitly chosen
// Hunyuan3D / BYOK backend that fails surfaces its own error. Provenance
// always reports the lane that actually ran so any downgrade is visible.
const upstreamGone =
@@ -2212,7 +2212,7 @@ async function startJob(req, res) {
const mode3d = isImageMode ? 'image→3D' : 'text→3D (via synthesized image)';
- // Fallback #1 — self-hosted TRELLIS Cloud Run worker (workers/model-trellis),
+ // Fallback #1: self-hosted TRELLIS Cloud Run worker (workers/model-trellis),
// when wired and not cooled. FREE_FALLBACK_FOR_PATH prefers it first among
// the free image lanes, so this paid-lane failover walks the same order:
// our own GPU (zero vendor cost) before any external free allocation. It
@@ -2254,7 +2254,7 @@ async function startJob(req, res) {
}
}
- // Fallback #2 — self-hosted Hunyuan3D Cloud Run worker, when wired.
+ // Fallback #2: self-hosted Hunyuan3D Cloud Run worker, when wired.
const hunyuanUrl = process.env.GCP_HUNYUAN3D_URL;
if (!job && hunyuanUrl && process.env.GCP_RECONSTRUCTION_KEY) {
console.warn(
@@ -2262,7 +2262,7 @@ async function startJob(req, res) {
);
backendId = 'hunyuan3d';
provider = createGcpProvider();
- // Hunyuan3D is poly-aware — supply the tier budget the TRELLIS params omit.
+ // Hunyuan3D is poly-aware: supply the tier budget the TRELLIS params omit.
reconstructParams.target_polycount = opts.targetPolycount ?? tier.polycount;
reconstructParams.tier = tier.id;
reconstructParams.path = path;
@@ -2273,7 +2273,7 @@ async function startJob(req, res) {
params: reconstructParams,
});
} else if (!job) {
- // Fallback #3 — free Hugging Face Spaces image→3D (gated on HF_TOKEN).
+ // Fallback #3: free Hugging Face Spaces image→3D (gated on HF_TOKEN).
// It blocks and writes its own status:'done' response; if it does, the
// request is complete. Otherwise fall through to surface the real error.
// For text mode, views=[referenceImageUrl] (the FLUX-synthesized image).
@@ -2305,7 +2305,7 @@ async function startJob(req, res) {
}
// How the job was actually conditioned. The provider reports back which
- // backend handled it and how many views it fused — these can differ from
+ // backend handled it and how many views it fused: these can differ from
// what was requested when a single-view model is configured and we fall
// back to the primary view. Surfaced so a downgrade is never silent.
const viewsRequested = views.length;
@@ -2392,7 +2392,7 @@ async function startJob(req, res) {
}
if (err?.code === 'insufficient_credits' && BACKENDS[backendId]?.byok) {
// BYOK lane: the message names the CALLER'S own provider account, which
- // they can act on — surface it. The platform's own paid lane falls through
+ // they can act on: surface it. The platform's own paid lane falls through
// to the sanitized "temporarily unavailable" state below.
return json(res, 402, {
error: 'insufficient_credits',
@@ -2401,16 +2401,16 @@ async function startJob(req, res) {
}
// Last-resort free fallback: when the paid image-intermediate TRELLIS lane
// (Replicate) is throttled, over-quota, unreachable, OR out of credit, a text
- // prompt must never dead-end — degrade to the free NVIDIA NIM lane so the
+ // prompt must never dead-end: degrade to the free NVIDIA NIM lane so the
// default "type a prompt → get a model" flow always returns something. The
// credit-exhaustion case matters most here: the failure is the paid FLUX
// synthesis step (textToImage throws code:'billing'/402, which is NOT
// upstream-unavailable), but the NIM TRELLIS lane is native text→mesh and
- // needs no FLUX intermediate at all — so a dry Replicate account should hand
+ // needs no FLUX intermediate at all: so a dry Replicate account should hand
// the prompt to the healthy free lane rather than skip straight to the 503.
// Honors the free-first "AI must never fail" policy; provenance reports
// backend:nvidia so the downgrade is visible, not silent. Image uploads have
- // no free reconstruct fallback here (NVCF is text-only — the HF lane already
+ // no free reconstruct fallback here (NVCF is text-only, the HF lane already
// absorbed them above), so they fall through to the designed states below.
// `nvidiaTried` guards against re-running a lane that already failed this
// request (the draft nvidia→trellis→nvidia loop).
@@ -2421,7 +2421,7 @@ async function startJob(req, res) {
prompt
) {
nvidiaTried = true;
- // Don't degrade to NIM when it's already in a recent-failure cooldown — that
+ // Don't degrade to NIM when it's already in a recent-failure cooldown, that
// would just re-pay the submit timeout on a lane we know is down right now.
const trellisCooling = (await providersInCooldown([NIM_TRELLIS_COOLDOWN_KEY])).has(
NIM_TRELLIS_COOLDOWN_KEY,
@@ -2438,35 +2438,35 @@ async function startJob(req, res) {
}
}
- // Upstream throttling is a transient 429, not a server fault — return it as
+ // Upstream throttling is a transient 429, not a server fault, return it as
// such with a retry hint so the page can show a "busy, try again" state.
if (err?.code === 'rate_limited' || err?.providerStatus === 429) {
const retryAfter = typeof err?.retryAfter === 'number' ? err.retryAfter : 10;
res.setHeader('retry-after', String(retryAfter));
// A `queued` throttle is our own rate gate pacing the request to the
- // upstream limit (not an upstream rejection) — tell the user it's in line so
+ // upstream limit (not an upstream rejection): tell the user it's in line so
// a retry reads as "your turn is coming up", not "the system is failing".
const queued = Boolean(err?.queued);
return json(res, 429, {
error: 'rate_limited',
queued,
message: queued
- ? `Your generation is queued behind a few others — retry in ~${retryAfter}s to pick it up.`
+ ? `Your generation is queued behind a few others: retry in ~${retryAfter}s to pick it up.`
: 'The 3D generator is busy right now. Try again in a few seconds.',
retry_after: retryAfter,
});
}
// Free lanes are exhausted and the only remaining lane was the platform's
// PAID vendor account, which is out of credit. The vendor's raw "buy credit"
- // message is our internal billing state and is useless to the user — answer
+ // message is our internal billing state and is useless to the user, answer
// with an honest, generic unavailable state instead of leaking it. (BYOK lanes
// kept their actionable account message via the insufficient_credits branch.)
if (!BACKENDS[backendId]?.byok && isPaidCreditFailure(err)) {
- const creditDetail = err?.providerDetail ? ` — vendor: ${err.providerDetail}` : '';
+ const creditDetail = err?.providerDetail ? `: vendor: ${err.providerDetail}` : '';
console.warn(
`[forge] paid reconstruct lane out of credit and no free lane available: ${err?.message || err}${creditDetail}`,
);
- // Record the paid lane as down (reason 'auth' — a billing fault that won't
+ // Record the paid lane as down (reason 'auth': a billing fault that won't
// self-heal until ops tops the account up). The NIM-cooldown router reads this
// so the next text prompt keeps the free NIM lane in play instead of skipping
// it to route into this now-known-dead paid lane.
@@ -2487,8 +2487,8 @@ async function startJob(req, res) {
message: err?.message || 'The generator could not start this job.',
});
} finally {
- // A claimed pay-per-use payment that did NOT deliver a model — any non-2xx
- // exit (validation 4xx, unconfigured 5xx, provider failure) — is released so
+ // A claimed pay-per-use payment that did NOT deliver a model, any non-2xx
+ // exit (validation 4xx, unconfigured 5xx, provider failure), is released so
// the settled $THREE payment stays reusable on retry. A successful job (200)
// keeps the claim, so one payment can never buy a second generation.
if (paidHigh?.redeemed && res.statusCode >= 400) {
@@ -2512,7 +2512,7 @@ async function startJob(req, res) {
// Auto-rig an existing GLB mesh: skeleton + skin weights via the provider's
// `rerig` mode (VAST-AI UniRig by default). Takes a GLB URL, returns a job id
-// that polls through the same GET ?job=<id> path — provider.status() is
+// that polls through the same GET ?job=<id> path: provider.status() is
// mode-agnostic, so the rigged GLB surfaces exactly like a reconstruction.
async function startRigJob(req, res) {
const ip = clientIp(req);
@@ -2530,8 +2530,8 @@ async function startRigJob(req, res) {
});
}
- // Prefer the self-hosted GCP UniRig pipeline when it's configured — it supports
- // rerig out of the box via its /rig endpoint — and fall back to Replicate when
+ // Prefer the self-hosted GCP UniRig pipeline when it's configured, it supports
+ // rerig out of the box via its /rig endpoint: and fall back to Replicate when
// a REPLICATE_RERIG_MODEL is set. Mirrors the gcp-first resolution the MCP
// studio path uses, so rigging works whenever ANY rerig-capable lane exists,
// not only when the highest-precedence provider happens to be the rigger.
@@ -2560,7 +2560,7 @@ async function startRigJob(req, res) {
}
}
- // Rigging stays dormant until a rerig lane is configured — surface a clean
+ // Rigging stays dormant until a rerig lane is configured, surface a clean
// 501 rather than a generic provider error so callers can branch on it.
if (!provider) {
return json(res, 501, {
@@ -2621,14 +2621,14 @@ async function startRigJob(req, res) {
// 404s. Two production consequences (53 of 134 nvidia jobs in one 36h window
// failed with "NVCF request not found or expired"):
// 1. Concurrent polls for the same job (overlapping browser timers, a second
-// tab, a retried request) race — one consumes the result, the other 404s
+// tab, a retried request) race: one consumes the result, the other 404s
// and flips the creation to failed even though the mesh exists.
// 2. A result that expires out of NVCF's retention window (throttled
// background tab, closed laptop) is genuinely gone.
// Recovery below: single-flight the upstream poll per task id so only one
// request ever touches NVCF at a time; on a 404, first re-check the store for
-// a completion a racing poll already materialized, then — because the prompt
-// is recorded on the creation row — resubmit the SAME generation once and
+// a completion a racing poll already materialized, then, because the prompt
+// is recorded on the creation row: resubmit the SAME generation once and
// alias the old task id to the new one so the client's existing poll handle
// keeps working. The alias lives in the shared cache; the creation row keeps
// its original replicate_job_id, so findByJob/materializeCreation are untouched.
@@ -2660,7 +2660,7 @@ async function pollNvidiaStatus({ nv, upstreamId, clientKey }) {
if (result?.code !== 'nvcf_expired') return result;
// The request id is dead. A racing poll may have already materialized the
- // creation — that's a success, not a failure.
+ // creation: that's a success, not a failure.
const row = await findByJob({ replicateJobId: upstreamId, clientKey });
if (row?.status === 'done' && row.glb_url) {
return { status: 'done', resultGlbUrl: row.glb_url };
@@ -2668,7 +2668,7 @@ async function pollNvidiaStatus({ nv, upstreamId, clientKey }) {
// Genuinely lost (expired / consumed by an aborted socket). The never-dead-end
// rule: regenerate server-side rather than surface a failure the user can only
- // answer by re-clicking Generate. Once per job — the resub lock outlives the
+ // answer by re-clicking Generate. Once per job: the resub lock outlives the
// alias so a second expiry reports the failure honestly.
if (!row?.prompt) return result;
if (!(await acquireLock(`nvcf:resub:${upstreamId}`, NVCF_ALIAS_TTL_S))) {
@@ -2696,11 +2696,11 @@ async function pollNvidiaStatus({ nv, upstreamId, clientKey }) {
// ── Self-host (GCP worker) poll recovery ─────────────────────────────────────
// A self-host /tasks/:id or /jobs/:id poll can 404 ("task not found on gcp
// service") when the durable task record isn't visible to the instance this
-// poll reached — the post-submit cross-instance window (worker at high
+// poll reached: the post-submit cross-instance window (worker at high
// concurrency, no session affinity) or a completion write racing us. That was
// the platform's single largest failure class (410 of 425 trellis failures, all
// path='image'), and the router used to treat the FIRST 404 as terminal. The
-// GCP twin of pollNvidiaStatus: never dead-end on a recoverable signal —
+// GCP twin of pollNvidiaStatus: never dead-end on a recoverable signal -
// re-check the store, grace a young job, and only surface failure once a missing
// task is genuinely orphaned, where the poll handler's lane failover takes over.
async function pollGcpStatus({ gcp, upstreamId, clientKey, createdAt }) {
@@ -2768,9 +2768,9 @@ async function pollJob(req, res, jobId) {
tier: meta.tier ?? null,
path: meta.path ?? null,
// The reference view this job reconstructs from. The submit response
- // already carries it, but a client that never saw that response —
+ // already carries it, but a client that never saw that response -
// a coalesced job, a resumed job after a reload, a poll-time failover
- // successor — otherwise has no way to learn it. Repeating it here lets
+ // successor: otherwise has no way to learn it. Repeating it here lets
// the generation timeline reveal the reference the moment it exists.
preview_image_url: meta.preview_image_url ?? null,
}
@@ -2822,7 +2822,7 @@ async function pollJob(req, res, jobId) {
}
result = await pollNvidiaStatus({ nv, upstreamId, clientKey });
} else if (provider === 'gcp') {
- // Serves every self-host lane (Hunyuan3D, TripoSG sketch) — the job
+ // Serves every self-host lane (Hunyuan3D, TripoSG sketch), the job
// envelope carries the worker URL it was submitted to.
let gcp;
try {
@@ -2846,22 +2846,22 @@ async function pollJob(req, res, jobId) {
result = await rep.status(liveHandle);
}
} catch {
- // A transient poll error shouldn't fail the job — report running so the
+ // A transient poll error shouldn't fail the job: report running so the
// client's loop retries.
return json(res, 200, { job_id: jobId, status: 'running', ...metaFields });
}
if (result.status === 'done' && result.resultGlbUrl) {
// The compression choice a caller requested at submit time (see
- // _lib/forge-job-options.js) — this poll is a LATER, separate invocation
+ // _lib/forge-job-options.js): this poll is a LATER, separate invocation
// with no access to that original request body, so it was bound to the
// job handle then and is looked up now. Absent when nothing non-default
- // was requested, or Redis is unavailable — both fail open to uncompressed.
+ // was requested, or Redis is unavailable: both fail open to uncompressed.
const boundOpts = await optionsForJob(jobId);
// Copy the mesh into our own storage so the model is permanent (provider
// delivery URLs expire) and serve the durable CDN url. Falls back to the
// provider url where the store is unavailable. Always scored for quality
- // (glb-quality.js) — free, deterministic, and the signal every lane's
+ // (glb-quality.js): free, deterministic, and the signal every lane's
// completion should carry regardless of which provider produced it.
const durable = await materializeCreation({
replicateJobId: upstreamId,
@@ -2872,7 +2872,7 @@ async function pollJob(req, res, jobId) {
compress: boundOpts?.compression || null,
});
// Populate the result cache this job was bound to at submit time (text→3D,
- // non-high-tier, platform-keyed lanes only — see forgeResultCacheKey). A
+ // non-high-tier, platform-keyed lanes only: see forgeResultCacheKey). A
// job with no binding (image mode, high tier, BYOK, or no options
// requested) is a no-op here.
const boundCacheKey = await cacheKeyForJob(jobId);
@@ -2920,7 +2920,7 @@ async function pollJob(req, res, jobId) {
await markFailed({ replicateJobId: upstreamId, clientKey, error: result.error });
// Cool the platform lane that actually failed so health-aware routing
- // steers new submits away immediately — the poll-time twin of the
+ // steers new submits away immediately: the poll-time twin of the
// submit-side cooldown. BYOK lanes are excluded (never auto-selected).
const failedBackend = meta?.backend || null;
const platformLaneFailed = Boolean(failedBackend && BACKENDS[failedBackend] && !BACKENDS[failedBackend].byok);
@@ -2928,7 +2928,7 @@ async function pollJob(req, res, jobId) {
// Automatic redispatch (see _lib/forge-failover.js): recover the original
// inputs from the creation row and continue the SAME job on the next
- // configured lane — the client keeps polling this id and sees
+ // configured lane: the client keeps polling this id and sees
// status:"running" with a new backend instead of a dead end. Scoped to
// platform image-path jobs with a stored reference view; sketch stays on
// its purpose-built lane and BYOK vendors are never silently swapped.
@@ -2965,7 +2965,7 @@ async function pollJob(req, res, jobId) {
tier: meta.tier,
path: meta.path,
});
- // Report "running" ONLY once the successor is durably chaseable —
+ // Report "running" ONLY once the successor is durably chaseable -
// otherwise the client would poll a dead handle forever.
const bound = await bindJobSuccessor(jobId, {
handle: submitted.handle,
@@ -2997,7 +2997,7 @@ async function pollJob(req, res, jobId) {
}
}
- // Terminal — but never a bare dead end: name the configured lanes that can
+ // Terminal: but never a bare dead end: name the configured lanes that can
// still serve a fresh retry of this request, so a client can offer a
// one-click engine switch instead of a bare error. Sketch keeps its single
// purpose-built lane (reconstruct models do badly on drawings).
@@ -3008,7 +3008,7 @@ async function pollJob(req, res, jobId) {
return json(res, 200, {
job_id: jobId,
status: 'failed',
- error: sanitizeJobError(result.error) || '3D generation hit a snag — please try again.',
+ error: sanitizeJobError(result.error) || '3D generation hit a snag, please try again.',
...metaFields,
...(suggestions.length ? { retryable: true, retry_backends: suggestions } : {}),
});
@@ -3031,11 +3031,11 @@ export default wrap(async (req, res) => {
return startJob(req, res);
}
- // ?catalog — the tier + backend + cost/time matrix the composer renders.
+ // ?catalog: the tier + backend + cost/time matrix the composer renders.
// Public, no secrets; lets the UI communicate the time/cost trade-off and
// which backends are live before the user commits. The payload only changes
// on a redeploy (tiers/backends are static; `configured` reflects env
- // presence), so it is heavily CDN-cacheable — one of the hottest GETs on the
+ // presence), so it is heavily CDN-cacheable: one of the hottest GETs on the
// site (every /forge load), now served almost entirely from the edge instead
// of recomputing per request. stale-while-revalidate keeps it instant even as
// the cache refreshes in the background.
@@ -3045,7 +3045,7 @@ export default wrap(async (req, res) => {
});
}
- // ?health — live-probes every platform backend's upstream (auth + quota
+ // ?health: live-probes every platform backend's upstream (auth + quota
// gates, zero vendor spend) so the UI and uptime checks see what a
// generation would actually hit, not just which env vars exist. Cached
// briefly per instance; rate-limited like status polling.
@@ -3056,7 +3056,7 @@ export default wrap(async (req, res) => {
// The probe already memoizes per instance (60s TTL); a short edge cache
// collapses an influx of identical health polls into one shared response
// every ~30s instead of one origin probe per client. stale-while-revalidate
- // means a client never waits on a refresh — it sees the live status surface
+ // means a client never waits on a refresh: it sees the live status surface
// update within ~30s while the CDN absorbs the load.
return json(res, 200, await probeForgeHealth(), {
'cache-control': 'public, max-age=15, s-maxage=30, stale-while-revalidate=120',
diff --git a/docs/smart-contracts.md b/docs/smart-contracts.md
index 081ec6023..5fd66af4b 100644
--- a/docs/smart-contracts.md
+++ b/docs/smart-contracts.md
@@ -4,7 +4,7 @@ Three Solidity contracts make up the ERC-8004 registry system for three.ws ident
| Contract | Source | Purpose |
|---|---|---|
-| `IdentityRegistry` | `contracts/src/IdentityRegistry.sol` | ERC-721 token registry — register and resolve three.ws identities on-chain |
+| `IdentityRegistry` | `contracts/src/IdentityRegistry.sol` | ERC-721 token registry, register and resolve three.ws identities on-chain |
| `ReputationRegistry` | `contracts/src/ReputationRegistry.sol` | Submit and aggregate signed feedback scores for agents |
| `ValidationRegistry` | `contracts/src/ValidationRegistry.sol` | Record immutable attestations of off-chain validation results (glTF schema, behavioral tests, etc.) |
@@ -60,7 +60,7 @@ const { identityRegistry, reputationRegistry, validationRegistry } =
REGISTRY_DEPLOYMENTS[chainId];
```
-### CREATE2 Factory — ThreeWSFactory
+### CREATE2 Factory: ThreeWSFactory
Vanity-prefixed CREATE2 deployer used to obtain matching addresses across chains.
@@ -93,7 +93,7 @@ This section describes `contracts/src/IdentityRegistry.sol`. It extends `ERC721E
Three overloads of `register()` are available depending on how much you want to set at mint time:
```solidity
-// Mint with no URI — set it later with setAgentURI
+// Mint with no URI: set it later with setAgentURI
function register() external returns (uint256 agentId)
// Mint and set the agent URI in one transaction
@@ -106,7 +106,7 @@ function register(
) external returns (uint256 agentId)
```
-`agentURI` should be a URL pointing to the ERC-8004 registration JSON — typically `ipfs://Qm...` or an HTTPS URL. The `MetadataEntry` array lets you attach arbitrary bytes under named keys:
+`agentURI` should be a URL pointing to the ERC-8004 registration JSON, typically `ipfs://Qm...` or an HTTPS URL. The `MetadataEntry` array lets you attach arbitrary bytes under named keys:
```solidity
struct MetadataEntry {
@@ -139,7 +139,7 @@ event URIUpdated(uint256 indexed agentId, string newURI, address indexed updated
### Arbitrary Metadata
-Key/value metadata store per agent. Values are raw bytes — ABI-encode complex types before writing.
+Key/value metadata store per agent. Values are raw bytes, ABI-encode complex types before writing.
```solidity
// Set a metadata value (owner only)
@@ -226,7 +226,7 @@ Emits `AgentDeposit`, `AgentWithdrawal`, `SpendAllowanceSet`, and `AgentPayment(
function balanceOf(address owner) external view returns (uint256)
function ownerOf(uint256 tokenId) external view returns (address)
-// Repo source only — these revert on the canonical deployed addresses
+// Repo source only: these revert on the canonical deployed addresses
function isAgent(uint256 agentId) external view returns (bool)
function DOMAIN_SEPARATOR() external view returns (bytes32)
function totalSupply() external view returns (uint256)
@@ -332,7 +332,7 @@ await tx2.wait();
`ReputationRegistry` stores signed feedback about registered agents. Scores are integers in the range `[-100, 100]`: negative scores indicate poor experiences, positive scores indicate good ones. Each `(reviewer, agentId)` pair can only submit once; there is no update path. Agent owners cannot review their own agents. Alongside plain feedback, the contract also exposes an ETH-staked variant (`stakeReputation(uint256 agentId, uint8 score, string comment)` payable, refundable via `withdrawStake(uint256 agentId)`); `submitFeedback` is the path documented here.
-The registry holds a reference to `IdentityRegistry` — submitting feedback for an unregistered agentId reverts with `UnknownAgent`.
+The registry holds a reference to `IdentityRegistry`, submitting feedback for an unregistered agentId reverts with `UnknownAgent`.
### Submitting Feedback
@@ -345,10 +345,10 @@ function submitFeedback(
```
Reverts with:
-- `ScoreOutOfRange` — if `score < -100 || score > 100`
-- `UnknownAgent` — if `agentId` is not registered in IdentityRegistry
-- `SelfReviewForbidden` — if caller is the agent's NFT owner
-- `AlreadyReviewed` — if caller has already reviewed this agent
+- `ScoreOutOfRange`: if `score < -100 || score > 100`
+- `UnknownAgent`: if `agentId` is not registered in IdentityRegistry
+- `SelfReviewForbidden`: if caller is the agent's NFT owner
+- `AlreadyReviewed`: if caller has already reviewed this agent
Emits:
@@ -364,7 +364,7 @@ event FeedbackSubmitted(
### Reading Reputation
```solidity
-// Returns (average * 100, count) — divide avgX100 by 100 to get the real average.
+// Returns (average * 100, count): divide avgX100 by 100 to get the real average.
// Returns (0, 0) for agents with no reviews.
function getReputation(uint256 agentId)
external view
@@ -639,7 +639,7 @@ These are approximate costs at optimizer 200 runs. Actual cost depends on chain
| `validationResponse` | ~60k | Updates the request in place |
| All `view` functions | 0 | Free off-chain reads |
-On Base at typical gas prices (~0.001 gwei base fee), an agent registration runs to roughly $0.10–$0.25. The same transaction costs 20–50x more on Ethereum mainnet — use Base or another L2 for cost-sensitive flows.
+On Base at typical gas prices (~0.001 gwei base fee), an agent registration runs to roughly $0.10-$0.25. The same transaction costs 20-50x more on Ethereum mainnet, use Base or another L2 for cost-sensitive flows.
---
diff --git a/docs/troubleshooting.md b/docs/troubleshooting.md
index c4778350b..f3adc0e50 100644
--- a/docs/troubleshooting.md
+++ b/docs/troubleshooting.md
@@ -18,13 +18,13 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
**Fix steps:**
-1. Open DevTools → Console (F12). Look for red errors — a failed fetch or a Three.js parse error will be logged there.
+1. Open DevTools → Console (F12). Look for red errors, a failed fetch or a Three.js parse error will be logged there.
2. Open DevTools → Network. Find the GLB request. Check the HTTP status code:
- - `404` — the URL is wrong. Verify `src` attribute.
- - `403` / `401` — access is blocked. Make the file publicly readable.
- - `200` with a CORS error in Console — see the CORS section below.
+ - `404`: the URL is wrong. Verify `src` attribute.
+ - `403` / `401`: access is blocked. Make the file publicly readable.
+ - `200` with a CORS error in Console: see the CORS section below.
3. Paste the GLB URL directly into a new browser tab. If it downloads or previews, the URL is valid.
-4. Check file size. Models over ~100 MB can cause timeouts on slow connections. Compress with Draco (5–10× mesh size reduction). See "Model loads slowly" under Performance.
+4. Check file size. Models over ~100 MB can cause timeouts on slow connections. Compress with Draco (5-10× mesh size reduction). See "Model loads slowly" under Performance.
5. Verify the format. Only **glTF 2.0** (`.glb` or `.gltf`) is supported. glTF 1.0, OBJ, FBX, and USDZ are not. If you're exporting from Blender, use File → Export → glTF 2.0 with "Format: GLB".
---
@@ -43,7 +43,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
- **Apache:** `Header set Access-Control-Allow-Origin "*"` in `.htaccess`.
- **AWS S3 / CloudFront:** Set a CORS policy on the bucket (allow all origins, GET method).
- **Vercel / Netlify:** Add a `headers` rule in the config file.
-2. If you can't modify the server, re-host the file somewhere that sends CORS headers: the platform's hosted storage (uploads via the Studio are CORS-configured automatically), or any CDN/bucket with a permissive CORS rule (Cloudflare R2, S3 + CORS policy). Note that the `key-proxy` attribute is **not** a fetch proxy — it points the element at your LLM API-key proxy endpoint (so the key never reaches the client) and has no effect on GLB loading.
+2. If you can't modify the server, re-host the file somewhere that sends CORS headers: the platform's hosted storage (uploads via the Studio are CORS-configured automatically), or any CDN/bucket with a permissive CORS rule (Cloudflare R2, S3 + CORS policy). Note that the `key-proxy` attribute is **not** a fetch proxy, it points the element at your LLM API-key proxy endpoint (so the key never reaches the client) and has no effect on GLB loading.
---
@@ -58,7 +58,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
**Fix steps:**
1. Open the file in a glTF viewer (e.g. [gltf.report](https://gltf.report)) to isolate the problem from the viewer itself.
-2. If using `.gltf` (not `.glb`): texture PNG/JPG files must be served from the same origin as the JSON and referenced by relative path. The simplest fix is to re-export as `.glb` — this embeds all textures in one file.
+2. If using `.gltf` (not `.glb`): texture PNG/JPG files must be served from the same origin as the JSON and referenced by relative path. The simplest fix is to re-export as `.glb`, this embeds all textures in one file.
3. If using `.glb`: textures are embedded by default. If they're missing, the export settings may have excluded them. In Blender: tick "Include → Textures" when exporting.
---
@@ -68,7 +68,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
**Symptom:** Model appears but with black surfaces, missing reflections, or washed-out colors.
**Likely causes:**
-- No environment map — metallic materials need a reflection source
+- No environment map: metallic materials need a reflection source
- Metalness = 1.0 with no environment (renders black)
- Inverted normal map
@@ -101,7 +101,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
**Symptom:** Chat input works but no reply appears. The agent is silent.
**Likely causes:**
-- `brain` attribute not set on `<agent-3d>` — without it, the element uses `NullProvider` (a no-op)
+- `brain` attribute not set on `<agent-3d>`: without it, the element uses `NullProvider` (a no-op)
- Missing or invalid `ANTHROPIC_API_KEY`
- Rate limit reached
@@ -113,9 +113,9 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
```
Without this attribute, `brain.provider` defaults to `none` and the agent uses `NullProvider`, which returns empty responses silently.
2. Open DevTools → Network. Filter for `/api/chat` or `/api/llm`. Look at the response:
- - `401` — the API key is missing or invalid.
- - `429` — rate limited. Wait a minute and retry.
- - `500` — server error. Check the server logs.
+ - `401`: the API key is missing or invalid.
+ - `429`: rate limited. Wait a minute and retry.
+ - `500`: server error. Check the server logs.
3. Verify `ANTHROPIC_API_KEY` is set in your server environment. On the production Cloud Run service:
```bash
gcloud run services update three-ws-api --region us-central1 \
@@ -134,7 +134,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
1. Tighten the system prompt. A vague `instructions` field produces vague behavior. Be explicit: "You are a guide for [product]. You only discuss [topic]. If asked about anything else, say you can't help with that."
2. Add a boundary statement to the instructions: "Never break character. Never discuss topics outside [domain]."
-3. If you're loading instructions from a `.md` file via `brain.instructions`, verify the file is being fetched correctly — check the Network panel for the `.md` request.
+3. If you're loading instructions from a `.md` file via `brain.instructions`, verify the file is being fetched correctly, check the Network panel for the `.md` request.
---
@@ -151,7 +151,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
1. Check the Console. The avatar module logs a warning if expected morph targets aren't found on load.
2. Verify your GLB has morph targets named exactly as expected (case-sensitive). The emotion system maps to: `mouthSmile`, `mouthFrown`, `mouthOpen`, `cheekPuff`, `browInnerUp`, `browOuterUpLeft` / `browOuterUpRight`, `noseSneerLeft` / `noseSneerRight`, `eyeSquintLeft` / `eyeSquintRight`, `eyesClosed`. These are the standard ARKit / humanoid avatar blendshape names.
3. For head tilt and lean, the skeleton needs a `Head` or `Neck` bone. Open the model in Blender and check the armature.
-4. Confirm the avatar module is initialized: open DevTools Console and run `window.VIEWER?.agent_avatar`. If `undefined`, the avatar layer didn't boot — check for earlier errors in the console.
+4. Confirm the avatar module is initialized: open DevTools Console and run `window.VIEWER?.agent_avatar`. If `undefined`, the avatar layer didn't boot, check for earlier errors in the console.
---
@@ -191,9 +191,9 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
**Fix steps:**
1. Open DevTools → Network. Filter for `/api/tts` or `elevenlabs.io`. Check the response:
- - `401` — `ELEVENLABS_API_KEY` is missing or wrong.
- - `429` — rate limited. The free tier allows 10,000 characters/month.
- - `422` — voice ID is invalid. Verify the `voiceId` in your manifest or config.
+ - `401`: `ELEVENLABS_API_KEY` is missing or wrong.
+ - `429`: rate limited. The free tier allows 10,000 characters/month.
+ - `422`: voice ID is invalid. Verify the `voiceId` in your manifest or config.
2. Confirm `ELEVENLABS_API_KEY` is set in your server environment variables.
---
@@ -227,7 +227,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
**Fix steps:**
-1. Verify the `src` URL is correct — use the full HTTPS URL.
+1. Verify the `src` URL is correct: use the full HTTPS URL.
2. Do not use a URL that ends in `/edit` or `/dashboard`: those pages block framing for security. Use the agent's public embed URL (`/agent/<id>/embed`, `/w/<widget-id>`, or `/widget#widget=<id>`).
3. Only the dedicated embed routes send a `frame-ancestors *` CSP header (set in the route table and applied by the server); regular pages send `frame-ancestors 'self'` and will refuse to load in your iframe. If an embed route is being blocked, the block is coming from the host page's own CSP, the agent's embed policy (domain allowlist), or a browser extension.
@@ -249,8 +249,8 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
```
3. Use the correct envelope shape. There are three related protocols, and none uses a type prefix like `3dagent:`:
- The **agent iframe bridge** (`/agent/<id>/embed`) uses `{ type: 'agent:*', agentId, ... }`: send `{ type: 'agent:hello', agentId }` first, wait for `agent:ready`, then drive it with `{ type: 'agent:action', agentId, action: { type: 'speak', text: '...' } }`. Every message must carry the `agentId`. See example 9 in the [Examples gallery](/docs/examples).
- - The **element bridge** (`src/embed-host-bridge.js`) wraps every message in `{ v: 1, source: 'agent-host' | 'agent-3d', id, kind, op, payload }` — e.g. a speak request is `{ v: 1, source: 'agent-host', id: '<uuid>', kind: 'request', op: 'speak', payload: { text: '...' } }`.
- - The **host protocol** ([specs/EMBED_HOST_PROTOCOL.md](../specs/EMBED_HOST_PROTOCOL.md)) uses `{ v: 1, type: 'host.*' | 'embed.*', id, payload }` — e.g. `{ v: 1, type: 'host.chat.message', payload: { ... } }`.
+ - The **element bridge** (`src/embed-host-bridge.js`) wraps every message in `{ v: 1, source: 'agent-host' | 'agent-3d', id, kind, op, payload }`, e.g. a speak request is `{ v: 1, source: 'agent-host', id: '<uuid>', kind: 'request', op: 'speak', payload: { text: '...' } }`.
+ - The **host protocol** ([specs/EMBED_HOST_PROTOCOL.md](../specs/EMBED_HOST_PROTOCOL.md)) uses `{ v: 1, type: 'host.*' | 'embed.*', id, payload }`, e.g. `{ v: 1, type: 'host.chat.message', payload: { ... } }`.
Messages that don't match the expected envelope (missing `agentId` or `v: 1`, wrong `source`/`type`) are silently ignored.
4. For element embeds, use the `EmbedHostBridge` class (`src/embed-host-bridge.js`) rather than raw `postMessage`: it handles the handshake, queues requests until the iframe is ready, and correlates responses by `id`.
@@ -264,7 +264,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
**Fix steps:**
1. The element sets `z-index: 2147483000` internally via `:host([mode="floating"])`. If another element has a higher z-index, it will cover the agent.
-2. Check parent elements for `overflow: hidden` — this can clip absolutely-positioned children even with a high z-index.
+2. Check parent elements for `overflow: hidden`: this can clip absolutely-positioned children even with a high z-index.
3. If the agent is inside a stacking context (e.g. a `position: relative` container with `z-index`), the z-index is relative to that context. Move `<agent-3d>` to a direct child of `<body>` if possible.
---
@@ -281,7 +281,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
```html
<agent-3d style="width: 100%; height: 50vh;" ...></agent-3d>
```
-2. Avoid `display: inline` on the container — use `block` or `flex`.
+2. Avoid `display: inline` on the container: use `block` or `flex`.
3. For inline mode with automatic aspect ratio, set the **`width` attribute** and omit `height`. Responsive sizing is on by default, so there is no `responsive` attribute to add:
```html
<agent-3d mode="inline" width="320" ...></agent-3d>
@@ -314,7 +314,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
**Fix steps:**
1. Set `PUBLIC_APP_ORIGIN` to exactly the origin users are hitting (e.g. `https://www.yourdomain.com`). `www.yourdomain.com` and `yourdomain.com` are treated as different domains. In production this lives on the Cloud Run service (`gcloud run services update three-ws-api --region us-central1 --update-env-vars PUBLIC_APP_ORIGIN=...`).
-2. For local development, any `localhost` domain is accepted automatically — you don't need to set `PUBLIC_APP_ORIGIN` for local dev.
+2. For local development, any `localhost` domain is accepted automatically, you don't need to set `PUBLIC_APP_ORIGIN` for local dev.
3. For forks deployed on Vercel, the deployment host injected as `VERCEL_URL` is automatically trusted alongside `PUBLIC_APP_ORIGIN`.
---
@@ -327,7 +327,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
**Fix steps:**
-1. Set `JWT_SECRET` once and don't rotate it unless needed. In production it lives on the Cloud Run service env (`gcloud run services describe three-ws-api --region us-central1` to inspect) — it must be the same value across all revisions.
+1. Set `JWT_SECRET` once and don't rotate it unless needed. In production it lives on the Cloud Run service env (`gcloud run services describe three-ws-api --region us-central1` to inspect), it must be the same value across all revisions.
2. Session duration is 30 days. A session used when fewer than 7 days remain is rotated to a fresh 30-day token (a rolling refresh window), so actively returning users stay signed in indefinitely.
---
@@ -338,7 +338,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
**Fix steps:**
-1. The key must be sent as `Authorization: Bearer <key>` — include the `Bearer ` prefix with a space.
+1. The key must be sent as `Authorization: Bearer <key>`, include the `Bearer ` prefix with a space.
2. Check if the key has been revoked in the dashboard (Settings → API Keys).
3. Verify the key's scope includes the endpoint you're calling. For example, reading avatar data requires `avatars:read`; creating or updating requires `avatars:write`.
@@ -352,7 +352,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
**Fix steps:**
-1. Increase the gas limit by 20% — registration involves IPFS CID storage and can exceed estimates.
+1. Increase the gas limit by 20%: registration involves IPFS CID storage and can exceed estimates.
2. Check your ETH balance on Base. Bridge more if needed.
3. Verify the manifest CID resolves on IPFS before calling the contract. A CID that doesn't resolve yet may cause the contract to reject it depending on the registry version.
4. Confirm MetaMask is on the chain you intend to register on. The platform default is Base (chain ID 8453). The registry contracts are deployed at the same addresses on all major EVM chains, but your wallet must be on the chain the registration flow targets, with gas funds on that chain.
@@ -365,7 +365,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
**Fix steps:**
-1. Retry — IPFS providers go down occasionally. Wait a minute and try again.
+1. Retry: IPFS providers go down occasionally. Wait a minute and try again.
2. Check `PINATA_JWT` (or your configured IPFS provider key) in your environment variables.
3. The default backend uses R2 storage (via `/api/erc8004/pin`). If you're supplying a Pinata JWT directly to the client, verify the token is valid and not expired in the Pinata dashboard.
@@ -377,8 +377,8 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
**Fix steps:**
-1. Wait 1–2 minutes. The indexer polls the chain periodically.
-2. Access the agent directly by URL: `https://three.ws/a/<chainId>/<agentId>` — this bypasses the index.
+1. Wait 1-2 minutes. The indexer polls the chain periodically.
+2. Access the agent directly by URL: `https://three.ws/a/<chainId>/<agentId>`, this bypasses the index.
3. Confirm the transaction was actually confirmed (not just submitted) on the block explorer for Base.
---
@@ -404,7 +404,7 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
**Symptom:** The agent starts fresh with no memory of previous conversations.
**Likely causes:**
-- Memory mode is `"none"` — conversations are never persisted
+- Memory mode is `"none"`: conversations are never persisted
- localStorage was cleared
**Fix steps:**
@@ -434,8 +434,8 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
**Fix steps:**
1. Check file size. Over 10 MB is noticeable on mobile; over 50 MB is slow on most connections.
-2. Enable Draco compression on export. In Blender's glTF exporter: Geometry → Compression → enable. This typically reduces mesh data by 5–10×.
-3. Scale down textures. 4096×4096 textures are rarely necessary — 1024×1024 is fine for most avatars. Use KTX2 format for GPU-compressed textures that decompress on the GPU rather than in JavaScript.
+2. Enable Draco compression on export. In Blender's glTF exporter: Geometry → Compression → enable. This typically reduces mesh data by 5-10×.
+3. Scale down textures. 4096×4096 textures are rarely necessary, 1024×1024 is fine for most avatars. Use KTX2 format for GPU-compressed textures that decompress on the GPU rather than in JavaScript.
4. Merge meshes in Blender before exporting. Fewer objects = fewer draw calls = faster load.
---
@@ -446,10 +446,10 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
**Fix steps:**
-1. Open the stats panel (visible in the dat.gui panel on the right side of the viewer). Check which metric is the bottleneck — GPU time or JavaScript time.
+1. Open the stats panel (visible in the dat.gui panel on the right side of the viewer). Check which metric is the bottleneck, GPU time or JavaScript time.
2. Reduce polygon count. Under 100k triangles renders at 60fps on most desktop GPUs; under 50k for mobile.
-3. Disable environment maps on mobile — IBL (image-based lighting) is GPU-expensive. Set `preset="none"` or use a simple directional light preset.
-4. Limit the number of `<agent-3d>` elements on a single page. Each one creates a WebGL context. Most browsers cap WebGL contexts at 8–16; 4–6 is a safe limit, fewer on mobile.
+3. Disable environment maps on mobile: IBL (image-based lighting) is GPU-expensive. Set `preset="none"` or use a simple directional light preset.
+4. Limit the number of `<agent-3d>` elements on a single page. Each one creates a WebGL context. Most browsers cap WebGL contexts at 8-16; 4-6 is a safe limit, fewer on mobile.
---
@@ -461,9 +461,9 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
**Fix steps:**
-1. Compress with Draco — the WASM decoder is more efficient and has less UI thread impact than uncompressed mesh parsing.
+1. Compress with Draco: the WASM decoder is more efficient and has less UI thread impact than uncompressed mesh parsing.
2. Split the model into multiple smaller files if possible, and load non-essential parts after the main avatar appears.
-3. Moving model loading to a Web Worker is technically possible but requires custom viewer configuration — advanced use case.
+3. Moving model loading to a Web Worker is technically possible but requires custom viewer configuration, advanced use case.
---
@@ -488,9 +488,9 @@ Organized by symptom. Find your problem, check the likely causes, follow the fix
**Symptom:** API routes and crons throw `NeonDbError: relation "agent_custody_events" does not exist` (or `forge_creations`, `x_triggers`, `club_tips`, `unstoppable_activity`, …). Often hundreds or thousands of identical errors.
-**Cause:** The database was provisioned with only part of the schema — typically `apply-schema.mjs` was run but the incremental migrations under `api/_lib/migrations/` were not. The base schema does **not** create migration-defined tables.
+**Cause:** The database was provisioned with only part of the schema, typically `apply-schema.mjs` was run but the incremental migrations under `api/_lib/migrations/` were not. The base schema does **not** create migration-defined tables.
-**Fix:** Point `DATABASE_URL` at the affected database and run the complete bootstrap. It is idempotent — it only creates what is missing:
+**Fix:** Point `DATABASE_URL` at the affected database and run the complete bootstrap. It is idempotent, it only creates what is missing:
```bash
DATABASE_URL=<prod connection string> npm run db:bootstrap
```
@@ -509,7 +509,7 @@ Run `npm run db:status` first to preview which migrations are pending.
gcloud logging read 'resource.type="cloud_run_revision" resource.labels.service_name="three-ws-api" severity>=ERROR' \
--freshness=1h --limit 20 --format="value(textPayload)"
```
- Deploys ship via `npm run deploy:gcp` (run `npm run build` first for frontend changes) — the full runbook lives in the repo at `docs/ops/gcp-production.md`. On a self-hosted fork, check whatever your host surfaces as function/process logs.
+ Deploys ship via `npm run deploy:gcp` (run `npm run build` first for frontend changes), the full runbook lives in the repo at `docs/ops/gcp-production.md`. On a self-hosted fork, check whatever your host surfaces as function/process logs.
2. The most common cause is a missing environment variable. All required vars must be set: `DATABASE_URL`, `JWT_SECRET`, `PUBLIC_APP_ORIGIN`. The `env.js` module throws on startup if required vars are absent. In production, inspect and set them on the Cloud Run service: `gcloud run services describe three-ws-api --region us-central1` / `gcloud run services update three-ws-api --region us-central1 --update-env-vars KEY=value`.
---
@@ -522,7 +522,7 @@ Run `npm run db:status` first to preview which migrations are pending.
1. Hard-refresh: Ctrl+Shift+R (Windows/Linux) or Cmd+Shift+R (Mac).
2. Clear the service worker manually: DevTools → Application → Service Workers → "Unregister", then DevTools → Application → Clear Storage → "Clear site data".
-3. Service workers cache aggressively and can serve stale content for up to 24 hours. This is expected behavior — users will update automatically when the SW checks for a new version.
+3. Service workers cache aggressively and can serve stale content for up to 24 hours. This is expected behavior, users will update automatically when the SW checks for a new version.
---
@@ -532,17 +532,17 @@ Run `npm run db:status` first to preview which migrations are pending.
**Symptom:** The `<agent-3d ar>` element renders correctly, but no AR button is visible on an iPhone or Android phone.
-**Check 1 — `ar` attribute is present:**
+**Check 1: `ar` attribute is present:**
```html
<agent-3d id="..." ar></agent-3d>
```
Without `ar`, the button is never rendered, even on supported devices.
-**Check 2 — correct browser:**
+**Check 2: correct browser:**
- iPhone: must be **Safari**. Chrome, Firefox, and all other iOS browsers use WebKit but lack the Quick Look integration that triggers AR. The button is hidden for non-Safari iOS browsers.
- Android: must be **Chrome** (or a Chromium-based browser with ARCore). Firefox on Android does not support Scene Viewer or WebXR AR.
-**Check 3 — inside an iframe:**
+**Check 3: inside an iframe:**
Add `allow="xr-spatial-tracking"` to the `<iframe>` element. Without it, the browser blocks `navigator.xr` inside the frame.
```html
@@ -552,17 +552,17 @@ Add `allow="xr-spatial-tracking"` to the `<iframe>` element. Without it, the bro
></iframe>
```
-**Check 4 — model not yet loaded:**
+**Check 4: model not yet loaded:**
The AR button is only shown after the GLB finishes loading. If the model is large or on a slow connection, the button appears late. Check the console for load errors.
-**Check 5 — HTTP origin:**
+**Check 5: HTTP origin:**
`navigator.xr` is `undefined` on `http://` origins. All AR methods require HTTPS for the page or the model URL. Use an ngrok tunnel or a deployed HTTPS environment during development.
---
### AR button appears but tapping it does nothing
-**iOS:** The model URL is `http://`. Quick Look silently refuses non-HTTPS model URLs — it opens briefly then closes immediately, or never opens. Use an HTTPS URL for both the page and the GLB.
+**iOS:** The model URL is `http://`. Quick Look silently refuses non-HTTPS model URLs, it opens briefly then closes immediately, or never opens. Use an HTTPS URL for both the page and the GLB.
**Android:** ARCore is not installed. Chrome shows a "Get ARCore" prompt on first use; if dismissed, nothing happens. Direct the user to install ARCore from the Play Store, then try again.
@@ -574,16 +574,16 @@ The AR button is only shown after the GLB finishes loading. If the model is larg
Almost always a model problem:
-1. **File too large.** Quick Look on older devices struggles above ~15 MB. Compress textures and simplify geometry — see [model optimization](ar.md#model-optimization-for-ar).
-2. **Draco-compressed GLB.** Quick Look doesn't include a Draco decoder — the file may load partially then fail. Decompress it: `npx @gltf-transform/cli optimize model.glb out.glb --no-draco`.
+1. **File too large.** Quick Look on older devices struggles above ~15 MB. Compress textures and simplify geometry, see [model optimization](ar.md#model-optimization-for-ar).
+2. **Draco-compressed GLB.** Quick Look doesn't include a Draco decoder, the file may load partially then fail. Decompress it: `npx @gltf-transform/cli optimize model.glb out.glb --no-draco`.
3. **CORS missing on the model URL.** Quick Look fetches the file separately from the browser, and CORS failures are silent. Verify `Access-Control-Allow-Origin: *` is present on the response headers for the GLB URL.
-4. **USDZ conversion failed.** Check the browser console for errors *before* Quick Look opens — the in-browser USDZExporter logs any failures. A corrupt or oversize USDZ causes immediate dismissal.
+4. **USDZ conversion failed.** Check the browser console for errors *before* Quick Look opens, the in-browser USDZExporter logs any failures. A corrupt or oversize USDZ causes immediate dismissal.
---
### The model is invisible or floating in WebXR
-**Background not cleared:** Verify the scene background is `null` when the XR session starts. If it's opaque, it occludes the camera passthrough — the agent is there but hidden behind the background color.
+**Background not cleared:** Verify the scene background is `null` when the XR session starts. If it's opaque, it occludes the camera passthrough, the agent is there but hidden behind the background color.
**Agent placed off-screen:** If `activateAR()` is called before the agent is positioned in the viewport, the model may be anchored outside the camera frustum. Ensure the agent is visible in the standard 3D view before activating AR.
@@ -593,11 +593,11 @@ Almost always a model problem:
### USDZ conversion is slow or fails
-The in-browser GLB → USDZ conversion runs in the main thread and can take 5–15 seconds for complex models. If it fails:
+The in-browser GLB → USDZ conversion runs in the main thread and can take 5-15 seconds for complex models. If it fails:
- Check the browser console for errors from `USDZExporter`.
-- Try the model in the [glTF Validator](/validation) first — invalid GLBs often cause export failures.
-- Skinned/rigged meshes export as static poses in USDZ (animations are lost — this is expected).
+- Try the model in the [glTF Validator](/validation) first, invalid GLBs often cause export failures.
+- Skinned/rigged meshes export as static poses in USDZ (animations are lost, this is expected).
- Models over ~30 MB may time out or exhaust memory during conversion on mobile. Reduce the model size before attempting Quick Look.
Pre-generate USDZ files on the server and set `ios-src` to skip in-browser conversion entirely.
@@ -608,15 +608,15 @@ Pre-generate USDZ files on the server and set `ios-src` to skip in-browser conve
All three AR methods require HTTPS. `navigator.xr` is undefined on insecure origins; Quick Look and Scene Viewer require the model URL to be HTTPS regardless of the page origin.
-**Option 1 — ngrok:**
+**Option 1: ngrok:**
```bash
npm run dev # starts dev server on port 3000
ngrok http 3000 # creates an HTTPS tunnel
# Open the ngrok URL on your phone
```
-**Option 2 — a deployed HTTPS environment:**
-Deploy your change and test against the live HTTPS URL. There are no per-branch preview deployments in the production flow — three.ws production deploys with `npm run deploy:gcp` to Cloud Run. A fork hosted on Vercel or Netlify does get an HTTPS URL per deploy, which works the same way for AR testing.
+**Option 2: a deployed HTTPS environment:**
+Deploy your change and test against the live HTTPS URL. There are no per-branch preview deployments in the production flow, three.ws production deploys with `npm run deploy:gcp` to Cloud Run. A fork hosted on Vercel or Netlify does get an HTTPS URL per deploy, which works the same way for AR testing.
**Chrome WebXR emulator (desktop testing):**
Chrome 127+ includes a WebXR device simulator under DevTools → More Tools → WebXR. It won't show camera passthrough but lets you test the session lifecycle and model placement logic without a physical device.
@@ -629,19 +629,19 @@ See the [AR & WebXR guide](/docs/ar) for the full platform compatibility matrix
**Is three.ws free?**
-The core platform is free. API usage costs (Anthropic for LLM, ElevenLabs for TTS) are charged at cost — you supply your own API keys. IPFS pinning for on-chain registration requires a Pinata JWT or uses the default R2 backend.
+The core platform is free. API usage costs (Anthropic for LLM, ElevenLabs for TTS) are charged at cost, you supply your own API keys. IPFS pinning for on-chain registration requires a Pinata JWT or uses the default R2 backend.
**Can I use any 3D model, or does it have to be a humanoid?**
-Any glTF 2.0 / GLB model works. Humanoid models with the correct skeleton and morph targets unlock the full emotion system (facial expressions, head movement). Non-humanoid models display and animate fine — they just won't show emotions.
+Any glTF 2.0 / GLB model works. Humanoid models with the correct skeleton and morph targets unlock the full emotion system (facial expressions, head movement). Non-humanoid models display and animate fine, they just won't show emotions.
**Does the agent work without an Anthropic API key?**
-The 3D viewer, animations, and widget system all work without a key. The LLM conversation feature requires setting the `brain` attribute on the element and a valid API key. If no key is configured, the element uses `NullProvider` (no-op) — it won't respond to chat messages.
+The 3D viewer, animations, and widget system all work without a key. The LLM conversation feature requires setting the `brain` attribute on the element and a valid API key. If no key is configured, the element uses `NullProvider` (no-op), it won't respond to chat messages.
**Can I self-host without Vercel?**
-Yes — production itself doesn't run on Vercel. Since 2026-07-07, three.ws production is a single container on Google Cloud Run: `server/index.mjs` serves the static frontend and every `api/**` handler, and reads `vercel.json`'s route table at runtime as its routing config. That server is the reference implementation for self-hosting on any Node.js host. If you'd rather use your own routing layer (Express routes, Nginx `proxy_pass`, etc.), replicate the `vercel.json` rewrite rules there — the API routes are standard Node.js async functions. Deploying a fork to Vercel also still works.
+Yes: production itself doesn't run on Vercel. Since 2026-07-07, three.ws production is a single container on Google Cloud Run: `server/index.mjs` serves the static frontend and every `api/**` handler, and reads `vercel.json`'s route table at runtime as its routing config. That server is the reference implementation for self-hosting on any Node.js host. If you'd rather use your own routing layer (Express routes, Nginx `proxy_pass`, etc.), replicate the `vercel.json` rewrite rules there, the API routes are standard Node.js async functions. Deploying a fork to Vercel also still works.
**Is the agent data private?**
diff --git a/docs/tutorials/animate-your-avatar.md b/docs/tutorials/animate-your-avatar.md
index acc601c31..87eba4e3f 100644
--- a/docs/tutorials/animate-your-avatar.md
+++ b/docs/tutorials/animate-your-avatar.md
@@ -1,8 +1,8 @@
# Animate your avatar
-By the end of this tutorial you'll be able to take any rigged avatar, browse the three.ws clip library, apply a motion to it live, control its speed and looping, and export an animated GLB you can use anywhere. You'll also understand *why* a clip authored for one skeleton plays correctly on yours — the runtime retargeting that makes the library universal.
+By the end of this tutorial you'll be able to take any rigged avatar, browse the three.ws clip library, apply a motion to it live, control its speed and looping, and export an animated GLB you can use anywhere. You'll also understand *why* a clip authored for one skeleton plays correctly on yours, the runtime retargeting that makes the library universal.
-**Prerequisites:** a three.ws account and at least one rigged avatar ([create one](/create), or load any public avatar). No code required — everything here happens in the browser. Light JavaScript familiarity helps only for the optional "how retargeting works" section.
+**Prerequisites:** a three.ws account and at least one rigged avatar ([create one](/create), or load any public avatar). No code required, everything here happens in the browser. Light JavaScript familiarity helps only for the optional "how retargeting works" section.
---
@@ -16,7 +16,7 @@ Pick an avatar ──► Browse the clip library ──► Click a clip
tune speed / loop ──► export animated GLB
```
-You don't author motion from scratch (you can — that's the keyframe timeline, a separate workflow). Here you *apply* and *remix* the shared library: dozens of pre-baked clips — idle, walk, dances, gestures, reactions — that drive **any** humanoid rig without manual bone mapping.
+You don't author motion from scratch (you can: that's the keyframe timeline, a separate workflow). Here you *apply* and *remix* the shared library: dozens of pre-baked clips, idle, walk, dances, gestures, reactions, that drive **any** humanoid rig without manual bone mapping.
Two surfaces do this, and they're connected:
@@ -33,18 +33,18 @@ The Gallery is where you *discover* a clip; the Studio is where you *apply* it.
The thing that makes the library work is that **motion and body are stored separately**.
-- An avatar is a **GLB** — geometry, skeleton, skin, textures.
-- A motion is a **clip JSON** — keyframe tracks only, no geometry. One clip can play on every avatar.
+- An avatar is a **GLB**: geometry, skeleton, skin, textures.
+- A motion is a **clip JSON**: keyframe tracks only, no geometry. One clip can play on every avatar.
-A clip's tracks are named against a **canonical skeleton** — the 52-bone humanoid set exported as `CANONICAL_BONES` (`Hips → Spine → Spine1 → Spine2 → Neck → Head`, both arms `Shoulder → Arm → ForeArm → Hand` with finger chains, both legs `UpLeg → Leg → Foot → ToeBase`). Every clip in [public/animations/clips](../../public/animations/clips) is baked against the reference rig `public/avatars/cz.glb`.
+A clip's tracks are named against a **canonical skeleton**, the 52-bone humanoid set exported as `CANONICAL_BONES` (`Hips → Spine → Spine1 → Spine2 → Neck → Head`, both arms `Shoulder → Arm → ForeArm → Hand` with finger chains, both legs `UpLeg → Leg → Foot → ToeBase`). Every clip in [public/animations/clips](../../public/animations/clips) is baked against the reference rig `public/avatars/cz.glb`.
-Your avatar almost certainly names its bones differently — `mixamorig:Hips`, `DEF-spine`, `J_Bip_C_Hips`, `pelvis`, `leftUpperArm`. Two runtime modules bridge that gap:
+Your avatar almost certainly names its bones differently, `mixamorig:Hips`, `DEF-spine`, `J_Bip_C_Hips`, `pelvis`, `leftUpperArm`. Two runtime modules bridge that gap:
-1. **Bone-name canonicalization** ([src/glb-canonicalize.js](../../src/glb-canonicalize.js)) recognizes the common skeleton conventions — Mixamo (`mixamorig:`), Blender (`Armature_`, `.L`/`.R`), Rigify (`DEF-`/`ORG-`), Unreal (`upperarm_l`), VRM/VRoid (`J_Bip_L_UpperArm`), VRM 1.0 (`leftUpperArm`), Daz/Genesis (`lShldr`), MakeHuman, and simple rigs (`shoulderL`) — and maps each bone to its canonical name.
+1. **Bone-name canonicalization** ([src/glb-canonicalize.js](../../src/glb-canonicalize.js)) recognizes the common skeleton conventions, Mixamo (`mixamorig:`), Blender (`Armature_`, `.L`/`.R`), Rigify (`DEF-`/`ORG-`), Unreal (`upperarm_l`), VRM/VRoid (`J_Bip_L_UpperArm`), VRM 1.0 (`leftUpperArm`), Daz/Genesis (`lShldr`), MakeHuman, and simple rigs (`shoulderL`), and maps each bone to its canonical name.
2. **Retargeting** ([src/animation-retarget.js](../../src/animation-retarget.js)) rewrites each track onto your rig's actual bone names, applies a per-bone bind-pose correction (so an A-pose clip plays right on a T-pose rig, and a hip baked at −90°X doesn't tip the body over), and rescales hip translation by your avatar's height so root motion lands where it should.
-**There is no rig allowlist.** Any humanoid avatar drives the library through this canonicalize-then-retarget path. The only gates are sanity thresholds: a rig needs **≥8** recognizable humanoid bones, and a clip must map **≥50%** of its tracks onto the rig to land. Below that the motion would read as a few twitching joints, so the Studio refuses it with an actionable message instead of playing garbage. If you hit a brand-new skeleton convention the canonicalizer doesn't know, the fix is to add its bone-name mapping to `glb-canonicalize.js` — never to hardcode a curated list of supported rigs.
+**There is no rig allowlist.** Any humanoid avatar drives the library through this canonicalize-then-retarget path. The only gates are sanity thresholds: a rig needs **≥8** recognizable humanoid bones, and a clip must map **≥50%** of its tracks onto the rig to land. Below that the motion would read as a few twitching joints, so the Studio refuses it with an actionable message instead of playing garbage. If you hit a brand-new skeleton convention the canonicalizer doesn't know, the fix is to add its bone-name mapping to `glb-canonicalize.js`, never to hardcode a curated list of supported rigs.
---
@@ -52,7 +52,7 @@ Your avatar almost certainly names its bones differently — `mixamorig:Hips`, `
![The Pose Studio at /pose: viewport in the middle, clip library and playback controls on the right.](figure:page:/pose?settle=6000)
-Open **[/pose](/pose)**. You'll land on the built-in **mannequin** — a primitive figure for FK/IK posing. The mannequin has no skinned skeleton to export, so the preset library stays locked until you load a real avatar.
+Open **[/pose](/pose)**. You'll land on the built-in **mannequin**, a primitive figure for FK/IK posing. The mannequin has no skinned skeleton to export, so the preset library stays locked until you load a real avatar.
![The mannequin itself. It poses, but it carries no skinned skeleton, which is why the preset library stays locked until you load a rigged avatar over it.](figure:live:/avatars/mannequin.glb)
@@ -66,7 +66,7 @@ If you'd rather skip the picker, deep-link directly:
The Studio reads `?avatar=` on boot and loads it for you (swap in your own avatar's id from its `/avatars/<id>` page). Add `&anim=<clip-id>` and it also opens that saved clip; this is exactly what the Gallery's **Open in Studio** button does.
-If the right panel shows **"Load a rigged avatar to animate"**, you're still on the mannequin — load an avatar. If it shows **"This rig can't be retargeted,"** the model exposes fewer than 8 recognizable humanoid bones (see Troubleshooting).
+If the right panel shows **"Load a rigged avatar to animate"**, you're still on the mannequin, load an avatar. If it shows **"This rig can't be retargeted,"** the model exposes fewer than 8 recognizable humanoid bones (see Troubleshooting).
---
@@ -78,7 +78,7 @@ With an avatar loaded, the **Animation** section on the right fills with a searc
- **Search** ("Search animations…") matches clip labels and names as you type.
- Each **card** shows an icon, a label, and a **loop** / **once** badge so you know up front whether a clip cycles forever or plays a single shot.
-The library covers a wide range — idle breaths, walks, dances, celebrations, reactions, sitting and crouching poses, and more. Browse by category, or search for what you want (e.g. `dance`, `wave`, `idle`).
+The library covers a wide range: idle breaths, walks, dances, celebrations, reactions, sitting and crouching poses, and more. Browse by category, or search for what you want (e.g. `dance`, `wave`, `idle`).
> Want to browse the *full* community catalog first? Open the **[Animation Gallery](/animations)** in another tab. It lists public clips with hover-to-preview on a live avatar, a loop/one-shot filter, and infinite scroll. When you find one you like, click **Open in Studio** and it lands back here applied to your avatar.
@@ -92,32 +92,32 @@ Click any card. The Studio:
2. Retargets it onto your loaded rig (rewrites bone names, corrects the bind pose, scales the hips).
3. Plays it live on the figure in the viewport.
-The shared 3D stage **is** the preview — one figure performing the motion, the way Mixamo previews look, rather than a wall of video thumbnails. The active card gets a "now playing" equalizer animation and a highlighted border.
+The shared 3D stage **is** the preview: one figure performing the motion, the way Mixamo previews look, rather than a wall of video thumbnails. The active card gets a "now playing" equalizer animation and a highlighted border.
The status line at the bottom of the stage confirms the retarget, e.g.:
```
-Playing "Cheering" — 96% retargeted (51/53 bones matched).
+Playing "Cheering": 96% retargeted (51/53 bones matched).
```
-That percentage is the coverage — how many of the clip's tracks found a home on your rig. (The counter is tracks, which the status line labels "bones": a full library clip carries 53 of them, one rotation track per canonical bone plus the hips' position track.) A couple of dropped bones (often fingers a simpler rig lacks) is normal and fine. If coverage falls below 50%, the clip won't apply and the status explains why (see Troubleshooting).
+That percentage is the coverage: how many of the clip's tracks found a home on your rig. (The counter is tracks, which the status line labels "bones": a full library clip carries 53 of them, one rotation track per canonical bone plus the hips' position track.) A couple of dropped bones (often fingers a simpler rig lacks) is normal and fine. If coverage falls below 50%, the clip won't apply and the status explains why (see Troubleshooting).
Clips marked **once** play a single shot and hold the final frame; **loop** clips cycle until you stop them or pick another.
---
-## Step 4: Control playback — speed and loop
+## Step 4: Control playback: speed and loop
Once a clip is playing, a **transport bar** appears under the gallery:
- A pulsing **now-playing** indicator with the clip's name.
-- A **Speed** slider, `0.25×` to `2.5×`. Drag it to taste — `1.8×` turns a walk into something close to a jog; `0.5×` slows a gesture down for emphasis. The value updates live.
+- A **Speed** slider, `0.25×` to `2.5×`. Drag it to taste, `1.8×` turns a walk into something close to a jog; `0.5×` slows a gesture down for emphasis. The value updates live.
- **⏹ Stop** ends the preview and hands the figure back to a clean rest pose.
- **Export animated GLB** (covered next).
-Looping follows the clip's own `loop` flag (the **loop** / **once** badge). Speed is a live preview control *and* it's baked into the export — the GLB you download carries the tempo you previewed, not a default one.
+Looping follows the clip's own `loop` flag (the **loop** / **once** badge). Speed is a live preview control *and* it's baked into the export, the GLB you download carries the tempo you previewed, not a default one.
-To swap clips, just click a different card — the new motion retargets and replaces the old one. To compare two dances, apply one, watch it, then click the other; the transport always reflects what's currently playing.
+To swap clips, just click a different card: the new motion retargets and replaces the old one. To compare two dances, apply one, watch it, then click the other; the transport always reflects what's currently playing.
---
@@ -126,10 +126,10 @@ To swap clips, just click a different card — the new motion retargets and repl
The preset library is finite; your imagination isn't. At the top of the **Animation** section is a text-to-motion box:
```
-Generate a motion — "waving confidently" [ ✨ Generate ]
+Generate a motion: "waving confidently" [ ✨ Generate ]
```
-Type a short description (e.g. `waving confidently`, `a slow bow`, `excited jumping`) and click **Generate**. The Studio submits a motion job, polls until the clip is ready (typically ~10–30s on a warm GPU; up to ~90s), then **retargets and plays it on your rig through the exact same path as a preset.** A generated motion behaves identically — same transport, speed slider, loop, and export. The status line counts the seconds while it works.
+Type a short description (e.g. `waving confidently`, `a slow bow`, `excited jumping`) and click **Generate**. The Studio submits a motion job, polls until the clip is ready (typically ~10-30s on a warm GPU; up to ~90s), then **retargets and plays it on your rig through the exact same path as a preset.** A generated motion behaves identically, same transport, speed slider, loop, and export. The status line counts the seconds while it works.
If the deployment hasn't enabled text-to-animation, you'll get a clear "isn't enabled on this deployment yet" message rather than a hang. Either way, the preset library is always available.
@@ -139,7 +139,7 @@ If the deployment hasn't enabled text-to-animation, you'll get a clear "isn't en
When a clip looks right, click **Export animated GLB** in the transport bar.
-The Studio bakes the retargeted clip — at your chosen speed — onto your avatar's rig and downloads a single self-contained file:
+The Studio bakes the retargeted clip: at your chosen speed, onto your avatar's rig and downloads a single self-contained file:
```
<avatar-name>-<clip-name>.glb
@@ -147,9 +147,9 @@ The Studio bakes the retargeted clip — at your chosen speed — onto your avat
This closes the loop: you started with a GLB (body) and a separate clip (motion), and you end with **one GLB that has the motion embedded.** It loads in any standard glTF viewer or in any three.ws surface, no retargeting required at play time.
-The figure is parked on the clip's first frame before export, so the file's rest pose is the animation's actual start — not wherever the live preview happened to pause.
+The figure is parked on the clip's first frame before export, so the file's rest pose is the animation's actual start, not wherever the live preview happened to pause.
-> The Studio can also export **clip JSON** (motion only, reusable on other rigs) and a **PNG screenshot** from the top bar, and — if you author your own motion on the keyframe timeline — save it to your account and list it. Those are adjacent workflows; this tutorial is the apply-and-remix path.
+> The Studio can also export **clip JSON** (motion only, reusable on other rigs) and a **PNG screenshot** from the top bar, and, if you author your own motion on the keyframe timeline, save it to your account and list it. Those are adjacent workflows; this tutorial is the apply-and-remix path.
---
@@ -158,7 +158,7 @@ The figure is parked on the clip's first frame before export, so the file's rest
The **[Animation Gallery](/animations)** is the social, browse-first side of the same system. It lists public, community-authored clips:
- **Search** and a **loop / one-shot** filter narrow the grid.
-- **Hover or click a card** to launch a live preview — an embedded viewer plays the clip on the reference CZ avatar, so you see real motion, not a static thumbnail.
+- **Hover or click a card** to launch a live preview: an embedded viewer plays the clip on the reference CZ avatar, so you see real motion, not a static thumbnail.
- **Open in Studio** deep-links to `/pose?anim=<id>`, dropping the clip into the Studio so you can apply it to *your* avatar, tune its speed, and export.
This is the remix loop: find a motion someone else published, open it in the Studio, retarget it onto your own avatar, adjust it, export. Because every clip is format-light JSON addressed by canonical bone names, the same clip that previewed on the CZ avatar drives your custom rig with no extra work.
@@ -167,38 +167,38 @@ This is the remix loop: find a motion someone else published, open it in the Stu
## Emotion and expression on the live agent
-Applying clips in the Studio is the **authoring** side. On a *running* agent, the same library drives emotion and gesture automatically through two channels that share one emotional state — the avatar's **Empathy Layer** ([src/agent-avatar.js](../../src/agent-avatar.js)):
+Applying clips in the Studio is the **authoring** side. On a *running* agent, the same library drives emotion and gesture automatically through two channels that share one emotional state, the avatar's **Empathy Layer** ([src/agent-avatar.js](../../src/agent-avatar.js)):
-**Gesture slots** ([src/runtime/animation-slots.js](../../src/runtime/animation-slots.js)) — a fixed vocabulary the agent plays in conversation. The conversational slots are `idle`, `wave`, `nod`, `shake`, `think`, `celebrate`, `concern`, `bow`, `point`, `shrug`, `fidget`, `dance`; a second group exists because skills emit the matching hint: `inspect`, `present`, `sign`, `curiosity`, `patience`, `manipulate`, `conjure`. Each slot resolves to a concrete library clip at runtime through `DEFAULT_ANIMATION_MAP` — most map to the clip of the same name (`celebrate` → `celebrate`, `think` → `think`), and a few borrow the closest baked motion where no dedicated clip exists yet (`concern` → `defeated`, `bow` → `sitclap`, `dance` → `rumba`). An agent picks a slot when the moment calls for it; the clip retargets onto that agent's avatar exactly as in the Studio. You can override any slot per agent via `meta.edits.animations` — point `wave` at a different clip, or map a slot to a motion you authored yourself.
+**Gesture slots** ([src/runtime/animation-slots.js](../../src/runtime/animation-slots.js)), a fixed vocabulary the agent plays in conversation. The conversational slots are `idle`, `wave`, `nod`, `shake`, `think`, `celebrate`, `concern`, `bow`, `point`, `shrug`, `fidget`, `dance`; a second group exists because skills emit the matching hint: `inspect`, `present`, `sign`, `curiosity`, `patience`, `manipulate`, `conjure`. Each slot resolves to a concrete library clip at runtime through `DEFAULT_ANIMATION_MAP`, most map to the clip of the same name (`celebrate` → `celebrate`, `think` → `think`), and a few borrow the closest baked motion where no dedicated clip exists yet (`concern` → `defeated`, `bow` → `sitclap`, `dance` → `rumba`). An agent picks a slot when the moment calls for it; the clip retargets onto that agent's avatar exactly as in the Studio. You can override any slot per agent via `meta.edits.animations`, point `wave` at a different clip, or map a slot to a motion you authored yourself.
-**Facial expression** ([src/runtime/arkit52.js](../../src/runtime/arkit52.js)) — driven from the same blend of morph targets as the gesture layer, not a separate track. If your avatar carries ARKit-52 blendshapes (most modern avatar-platform exports do, as do VRoid models), the runtime resolves those morph targets and drives expression and lip-sync directly on the face. A skeletal clip plays the body; the blendshape layer plays the eyes, brows, and mouth on top.
+**Facial expression** ([src/runtime/arkit52.js](../../src/runtime/arkit52.js)), driven from the same blend of morph targets as the gesture layer, not a separate track. If your avatar carries ARKit-52 blendshapes (most modern avatar-platform exports do, as do VRoid models), the runtime resolves those morph targets and drives expression and lip-sync directly on the face. A skeletal clip plays the body; the blendshape layer plays the eyes, brows, and mouth on top.
The two channels are wired to the *same* emotional state, at two different timescales, so the body and the face never disagree:
-- **Momentary events** (an error just happened, a skill just finished) inject a transient emotion spike — `concern`, `celebration`, `curiosity`, and friends — that decays over seconds. A spike crossing threshold both reshapes the face immediately *and* biases the gesture slot the avatar plays next (e.g. sustained `celebration` picks the `celebrate` slot).
-- **Sustained mood** — the agent's resting valence/arousal, set via `setMood()` (see [docs/tutorials/emotion-from-data.md](emotion-from-data.md)) — is the continuous baseline between events. It biases the resting face (a soft smile at high valence, a worried brow at low) and posture (lean, gaze) every frame, and, once nothing more urgent claims the gesture slot, biases *which* ambient gesture plays too: a sustained up-and-energetic mood leans toward the `celebrate` slot, a sustained down-and-subdued mood toward `concern` — the opposite bias, never the energetic one. A momentary event always takes priority over the ambient mood bias, and slot overrides via `meta.edits.animations` apply identically whether the trigger was a spike or the resting mood.
+- **Momentary events** (an error just happened, a skill just finished) inject a transient emotion spike, `concern`, `celebration`, `curiosity`, and friends, that decays over seconds. A spike crossing threshold both reshapes the face immediately *and* biases the gesture slot the avatar plays next (e.g. sustained `celebration` picks the `celebrate` slot).
+- **Sustained mood**: the agent's resting valence/arousal, set via `setMood()` (see [docs/tutorials/emotion-from-data.md](emotion-from-data.md)), is the continuous baseline between events. It biases the resting face (a soft smile at high valence, a worried brow at low) and posture (lean, gaze) every frame, and, once nothing more urgent claims the gesture slot, biases *which* ambient gesture plays too: a sustained up-and-energetic mood leans toward the `celebrate` slot, a sustained down-and-subdued mood toward `concern`, the opposite bias, never the energetic one. A momentary event always takes priority over the ambient mood bias, and slot overrides via `meta.edits.animations` apply identically whether the trigger was a spike or the resting mood.
-The division of labor: **clips move the body, blendshapes move the face, slots choose *which* body motion fits the emotion — and one emotional state, not two independent tracks, drives all of it.** All three ride the same universal-rig foundation — name your bones (and your blendshapes) in a convention the resolvers know, and everything just works.
+The division of labor: **clips move the body, blendshapes move the face, slots choose *which* body motion fits the emotion, and one emotional state, not two independent tracks, drives all of it.** All three ride the same universal-rig foundation, name your bones (and your blendshapes) in a convention the resolvers know, and everything just works.
---
## Troubleshooting
-- **The Animation section says "Load a rigged avatar to animate."** You're on the built-in mannequin. The mannequin has no skinned skeleton to retarget or export — click **Load avatar** in the top bar (or open `/pose?avatar=<id>`).
+- **The Animation section says "Load a rigged avatar to animate."** You're on the built-in mannequin. The mannequin has no skinned skeleton to retarget or export, click **Load avatar** in the top bar (or open `/pose?avatar=<id>`).
-- **"This rig can't be retargeted — only N recognizable humanoid bones."** The model exposes fewer than 8 canonical bones. It's likely non-humanoid, a static prop, or a rig whose bone names the canonicalizer doesn't recognize. Re-export it as a standard humanoid (Mixamo, VRM, or any common avatar-platform export all work), or auto-rig a rig-less mesh first.
+- **"This rig can't be retargeted: only N recognizable humanoid bones."** The model exposes fewer than 8 canonical bones. It's likely non-humanoid, a static prop, or a rig whose bone names the canonicalizer doesn't recognize. Re-export it as a standard humanoid (Mixamo, VRM, or any common avatar-platform export all work), or auto-rig a rig-less mesh first.
-- **A clip won't apply: "can't retarget to this rig — only X/Y tracks mapped."** Coverage fell below 50%. The rig is missing too many of the clip's bones (often a stripped-down skeleton with no spine subdivisions or no fingers). Try a clip that uses fewer bones, or use a more complete humanoid rig. The fix for a recurring convention is to add its bone-name mapping in [src/glb-canonicalize.js](../../src/glb-canonicalize.js) — never a hardcoded allowlist.
+- **A clip won't apply: "can't retarget to this rig: only X/Y tracks mapped."** Coverage fell below 50%. The rig is missing too many of the clip's bones (often a stripped-down skeleton with no spine subdivisions or no fingers). Try a clip that uses fewer bones, or use a more complete humanoid rig. The fix for a recurring convention is to add its bone-name mapping in [src/glb-canonicalize.js](../../src/glb-canonicalize.js), never a hardcoded allowlist.
- **The motion plays but limbs look skewed or the body lies down.** This is the symptom the bind-pose correction exists to prevent, so it should be rare. It usually means the rig rests in an unusual pose the canonicalizer mapped but couldn't fully correct. Verify the avatar imports upright and T- or A-posed; re-export from the source tool if it doesn't.
-- **A few bones are "not on this rig" but it still plays.** Expected. The status note (`51/53 bones · 2 not on this rig`) just lists dropped tracks — usually fingers or toes a simpler rig lacks. As long as coverage is ≥50% the performance reads correctly.
+- **A few bones are "not on this rig" but it still plays.** Expected. The status note (`51/53 bones · 2 not on this rig`) just lists dropped tracks, usually fingers or toes a simpler rig lacks. As long as coverage is ≥50% the performance reads correctly.
- **"Text-to-animation isn't enabled on this deployment yet."** The motion generator isn't configured on this instance. Use the preset library, which is always available.
- **Generation times out.** The job exceeded the poll window. Try a shorter, simpler prompt.
-- **Export downloads nothing / fails.** Make sure a clip is actively playing (the transport bar is visible) before clicking **Export animated GLB** — export bakes the *currently previewing* clip onto the rig.
+- **Export downloads nothing / fails.** Make sure a clip is actively playing (the transport bar is visible) before clicking **Export animated GLB**, export bakes the *currently previewing* clip onto the rig.
---
@@ -206,17 +206,17 @@ The division of labor: **clips move the body, blendshapes move the face, slots c
You learned the apply-and-remix workflow for motion on three.ws:
-- **The library is universal.** Motion is stored as canonical-skeleton clip JSON, separate from the avatar GLB. [glb-canonicalize.js](../../src/glb-canonicalize.js) maps any humanoid's bone names to canonical; [animation-retarget.js](../../src/animation-retarget.js) rewrites tracks, corrects the bind pose, and scales the hips so one clip drives every rig. No rig allowlist — only an 8-bone / 50%-coverage sanity gate.
-- **[/pose](/pose) is where you apply.** Load a rigged avatar, browse or search the categorized gallery, click to retarget and preview live, tune speed (0.25×–2.5×) and loop in the transport bar, and **export an animated GLB** with the motion baked in.
+- **The library is universal.** Motion is stored as canonical-skeleton clip JSON, separate from the avatar GLB. [glb-canonicalize.js](../../src/glb-canonicalize.js) maps any humanoid's bone names to canonical; [animation-retarget.js](../../src/animation-retarget.js) rewrites tracks, corrects the bind pose, and scales the hips so one clip drives every rig. No rig allowlist, only an 8-bone / 50%-coverage sanity gate.
+- **[/pose](/pose) is where you apply.** Load a rigged avatar, browse or search the categorized gallery, click to retarget and preview live, tune speed (0.25×-2.5×) and loop in the transport bar, and **export an animated GLB** with the motion baked in.
- **[/animations](/animations) is where you discover.** Browse public community clips with live hover-preview, then **Open in Studio** to apply any of them to your own avatar.
- **Generate what doesn't exist.** Text-to-motion synthesizes a brand-new clip and runs it through the identical retarget-and-apply path as a preset.
-- **On a live agent**, the same clips drive emotion through gesture **slots**, while **ARKit-52 blendshapes** drive facial expression independently — clips move the body, blendshapes move the face.
+- **On a live agent**, the same clips drive emotion through gesture **slots**, while **ARKit-52 blendshapes** drive facial expression independently, clips move the body, blendshapes move the face.
**See also:**
-- [docs/animations.md](../animations.md) — the runtime animation registry, manifest, and agent slot reference.
-- [docs/3d-asset-pipeline.md](../3d-asset-pipeline.md) — how FBX, GLB, and clip JSON relate, and how clips are built and retargeted.
-- [docs/tutorials/swap-avatar-in-studio.md](swap-avatar-in-studio.md) — loading and switching avatars in the Studio.
-- [docs/tutorials/upload-custom-glb.md](upload-custom-glb.md) — getting a Mixamo or custom rig into three.ws as a clean, animatable GLB.
+- [docs/animations.md](../animations.md): the runtime animation registry, manifest, and agent slot reference.
+- [docs/3d-asset-pipeline.md](../3d-asset-pipeline.md), how FBX, GLB, and clip JSON relate, and how clips are built and retargeted.
+- [docs/tutorials/swap-avatar-in-studio.md](swap-avatar-in-studio.md), loading and switching avatars in the Studio.
+- [docs/tutorials/upload-custom-glb.md](upload-custom-glb.md), getting a Mixamo or custom rig into three.ws as a clean, animatable GLB.
Primary call to action: open **[/pose](/pose)**, load an avatar, and apply your first clip.
diff --git a/docs/tutorials/connect-ai-brain.md b/docs/tutorials/connect-ai-brain.md
index 4fa123c05..19b1a72aa 100644
--- a/docs/tutorials/connect-ai-brain.md
+++ b/docs/tutorials/connect-ai-brain.md
@@ -2,7 +2,7 @@
The agent's body is the avatar. The agent's voice is the TTS. The agent's *brain* is whatever LLM is generating its replies. By default an embedded agent runs on a **free open-weight lane** (`openai/gpt-oss-20b:free`, routed through OpenRouter on the platform's key), which works out of the box at no cost to you. The moment you want a frontier model, full control over which one runs, or your own usage observability, you bring your own API key.
-This tutorial covers the whole brain layer. Where the LLM call actually happens (and why your key never ends up in HTML), how to attach your Anthropic, OpenAI, or xAI key, choosing between the Claude 5 family, the GPT-5.x family, Grok, and the free lanes, the latency and cost tradeoffs, how streaming and system prompts are configured, tool-use support per model, and where to watch your spend. The embed snippet doesn't change when you switch models — the model lives on the agent's embed policy, not in your HTML.
+This tutorial covers the whole brain layer. Where the LLM call actually happens (and why your key never ends up in HTML), how to attach your Anthropic, OpenAI, or xAI key, choosing between the Claude 5 family, the GPT-5.x family, Grok, and the free lanes, the latency and cost tradeoffs, how streaming and system prompts are configured, tool-use support per model, and where to watch your spend. The embed snippet doesn't change when you switch models, the model lives on the agent's embed policy, not in your HTML.
**What you'll build:**
- An agent powered by your own Anthropic, OpenAI, or xAI key
@@ -14,16 +14,16 @@ This tutorial covers the whole brain layer. Where the LLM call actually happens
---
-## Step 1 — Where the LLM call actually happens
+## Step 1: Where the LLM call actually happens
The single most important architectural detail: **the LLM call is server-side, always**. The browser never talks to Anthropic or OpenAI directly. Your API key never leaves the platform's backend.
When the agent on the page calls `agent.say('hi')`, the flow is:
1. The browser posts an Anthropic-shape body (`{ model, system, messages, tools, stream }`) to `three.ws/api/llm/anthropic?agent=<agentId>` (`api/llm/anthropic.js`).
-2. The proxy reads that agent's **embed policy** and checks the referring origin against its allowlist, its per-minute rate limit, and its monthly quota — all before a single upstream token is spent.
+2. The proxy reads that agent's **embed policy** and checks the referring origin against its allowlist, its per-minute rate limit, and its monthly quota, all before a single upstream token is spent.
3. It resolves which model actually runs (see the clamp below), looks up the matching upstream credential, and calls the provider from the server.
-4. The response streams back as Anthropic-shape Server-Sent Events, whatever the upstream was — Groq, OpenRouter, NVIDIA, Mistral, xAI, and Vertex are all translated into that one wire format so the browser parser never changes.
+4. The response streams back as Anthropic-shape Server-Sent Events, whatever the upstream was, Groq, OpenRouter, NVIDIA, Mistral, xAI, and Vertex are all translated into that one wire format so the browser parser never changes.
5. The runtime fires `brain:stream` events with chunks and a final `brain:message` event with the complete reply. Both are re-dispatched on the `<agent-3d>` host element, so you listen on the element.
This matters for four reasons:
@@ -39,9 +39,9 @@ The corollary: setting `api-key="sk-ant-..."` directly on the `<agent-3d>` tag i
---
-## Step 2 — Add your API key in My Agents
+## Step 2: Add your API key in My Agents
-Keys live at **[/dashboard/account](https://three.ws/dashboard/account)**, in the **AI Provider Keys** panel. The store is per-account, not per-agent — once you've added a key, every agent you own can use it.
+Keys live at **[/dashboard/account](https://three.ws/dashboard/account)**, in the **AI Provider Keys** panel. The store is per-account, not per-agent, once you've added a key, every agent you own can use it.
For Anthropic:
@@ -67,11 +67,11 @@ For xAI (Grok):
You can store all three at once. The same panel also holds keys for the non-LLM providers the platform can call on your behalf (Meshy, Tripo, Rodin, Stability, Replicate, ElevenLabs).
-Under the hood this is `GET`/`PATCH /api/user/provider-keys`. The `GET` returns only which providers are set — never a value — and a `PATCH` with `null` for a provider deletes that key. Keys are stored encrypted at rest and are never displayed back. If you suspect a leak, rotate it on the provider side and replace it here.
+Under the hood this is `GET`/`PATCH /api/user/provider-keys`. The `GET` returns only which providers are set, never a value, and a `PATCH` with `null` for a provider deletes that key. Keys are stored encrypted at rest and are never displayed back. If you suspect a leak, rotate it on the provider side and replace it here.
---
-## Step 3 — Pick a model
+## Step 3: Pick a model
Each agent has a single active brain at a time, pinned as `brain.model` on its embed policy (Step 8 covers changing it). To compare models interactively before you commit, the **model grid and multi-model playground at [/dashboard/brain](https://three.ws/dashboard/brain)** streams the same prompt across several models side by side. That page reads its roster from `GET /api/brain/chat`, which reports every model and whether it is currently available, so it is the live source of truth rather than a hardcoded list.
@@ -79,25 +79,25 @@ Prices below are USD per million tokens (input / output) from the platform's own
### Anthropic models
-**Claude Sonnet 5** (`claude-sonnet-5`) — the default recommendation.
+**Claude Sonnet 5** (`claude-sonnet-5`): the default recommendation.
- **Cost:** $3 / $15. For a typical 20-turn chat this is fractions of a cent.
- **Capability:** Near-Opus quality on coding and agentic work at Sonnet cost. The right default for support, sales, concierge, and personal agents.
- **Context window:** 200K tokens. Plenty of room for long system prompts and memory.
-**Claude Opus 5** (`claude-opus-5`) — when you need depth.
+**Claude Opus 5** (`claude-opus-5`): when you need depth.
- **Cost:** $5 / $25.
- **Capability:** Deep reasoning, agentic and long-horizon work. **Thinks by default**, which is the tradeoff: better answers on hard questions, more latency and more billed output tokens on easy ones.
- **Context window:** 200K tokens.
-**Claude Fable 5** (`claude-fable-5`) — the most capable model on the platform.
+**Claude Fable 5** (`claude-fable-5`): the most capable model on the platform.
- **Cost:** $10 / $50.
- **Capability:** State-of-the-art reasoning, long-horizon agentic work, knowledge work, and vision. Reach for it when a specific quality gap survives prompt iteration on Opus.
- **Note:** thinking is always on and is not configurable; the proxy strips any non-adaptive `thinking` config rather than letting the upstream reject the call.
-**Claude Haiku 4.5** (`claude-haiku-4-5`) — when latency matters more than depth.
+**Claude Haiku 4.5** (`claude-haiku-4-5`): when latency matters more than depth.
- **Cost:** $1 / $5, a third of Sonnet.
- **Capability:** Good for FAQ-style agents, lookups, and short interactions. Drops noticeably below Sonnet on long context or nuanced tone.
@@ -154,7 +154,7 @@ A practical rule of thumb:
| Use case | Recommended model |
|---|---|
-| Kicking the tyres, low-stakes embed | `openai/gpt-oss-20b:free` (the default — no key, no bill) |
+| Kicking the tyres, low-stakes embed | `openai/gpt-oss-20b:free` (the default, no key, no bill) |
| Support / FAQ agent for a SaaS | Sonnet 5 or GPT-5.6 Terra |
| Personal-website-me agent | Sonnet 5 |
| Onboarding co-pilot, sales bot | Sonnet 5 |
@@ -169,7 +169,7 @@ Start at Sonnet 5 for almost everything. Move to Haiku if latency is the bottlen
---
-## Step 4 — Configure the system prompt
+## Step 4: Configure the system prompt
The system prompt and the model are configured separately. You can swap models without touching the prompt, and vice versa.
@@ -197,7 +197,7 @@ There is no top-p knob and no streaming toggle: the client always requests `stre
---
-## Step 5 — Streaming responses
+## Step 5: Streaming responses
By default the platform streams responses from the model as they generate. The browser receives tokens in `brain:stream` events and the full message arrives in `brain:message` once the model finishes.
@@ -207,7 +207,7 @@ You can see this in action:
const agent = document.querySelector('agent-3d');
agent.addEventListener('brain:stream', (e) => {
- // e.detail.chunk is a small string — usually 1-5 tokens
+ // e.detail.chunk is a small string: usually 1-5 tokens
console.log('chunk:', e.detail.chunk);
});
@@ -218,17 +218,17 @@ agent.addEventListener('brain:message', (e) => {
});
```
-For a custom chat UI, build incremental rendering on `brain:stream` so the user sees text arriving instead of waiting for the whole reply. The built-in chat input already does this — assistant messages fill in word by word.
+For a custom chat UI, build incremental rendering on `brain:stream` so the user sees text arriving instead of waiting for the whole reply. The built-in chat input already does this, assistant messages fill in word by word.
-There is no streaming off-switch: the runtime always requests `stream: true`. If you need whole messages only, ignore `brain:stream` and read `brain:message`, which fires once with the complete reply — the same end state, with no wiring change.
+There is no streaming off-switch: the runtime always requests `stream: true`. If you need whole messages only, ignore `brain:stream` and read `brain:message`, which fires once with the complete reply, the same end state, with no wiring change.
Streaming impacts perceived latency *much* more than actual end-to-end latency. A reply that takes 2 seconds to fully generate feels nearly instant with streaming on; without streaming, the same 2-second wait feels like the agent is broken.
---
-## Step 6 — Tool use per model
+## Step 6: Tool use per model
-Tool use (the model invoking a function you've defined — a `searchProducts(query)` skill, a `lookupOrder(id)` skill) is supported across all the models above, but the quality varies.
+Tool use (the model invoking a function you've defined, a `searchProducts(query)` skill, a `lookupOrder(id)` skill) is supported across all the models above, but the quality varies.
| Model | Tool use quality |
|---|---|
@@ -240,9 +240,9 @@ Tool use (the model invoking a function you've defined — a `searchProducts(que
| GPT-5.6 Terra | Very good. Slightly more prone to mis-formatting tool arguments than Sonnet. |
| GPT-5.6 Luna | Functional. Avoid for anything with 2+ tools or non-trivial schemas. |
| Grok 4.5 | Reliable. A fair substitute for Terra when you also want current-events knowledge. |
-| Free lanes (GPT-OSS, NVIDIA NIM, Groq) | Tool-call capable — that is why they are the fallback rungs — but noticeably weaker at picking the right tool. Fine for one or two tools with simple schemas. |
+| Free lanes (GPT-OSS, NVIDIA NIM, Groq) | Tool-call capable, that is why they are the fallback rungs, but noticeably weaker at picking the right tool. Fine for one or two tools with simple schemas. |
-If you're building a skill-heavy agent — one that needs to look up products, check inventory, search documentation, and place orders, all in one conversation — pick Sonnet 5 or GPT-5.6 Terra at minimum. Haiku and Luna are acceptable for single-purpose lookups but get confused on chains.
+If you're building a skill-heavy agent: one that needs to look up products, check inventory, search documentation, and place orders, all in one conversation, pick Sonnet 5 or GPT-5.6 Terra at minimum. Haiku and Luna are acceptable for single-purpose lookups but get confused on chains.
The runtime caps a single turn at 8 tool iterations, so a chain that can't resolve inside 8 round trips returns whatever it has rather than looping forever.
@@ -250,7 +250,7 @@ See the [custom skill tutorial](/tutorials/custom-skill) for the full skill-writ
---
-## Step 7 — Observability and cost
+## Step 7: Observability and cost
Every chat turn costs tokens. For agents handling real traffic, you need to know where your spend is going.
@@ -270,11 +270,11 @@ Note what this is and isn't: it counts **calls**, not tokens, and it is the same
**The account read.** `GET /api/usage/summary` returns your account-level numbers (plan quotas, avatar count and bytes, MCP tool calls in the last 24h, total events in the last 30 days).
-**Cost.** The platform prices every call server-side through `api/_lib/llm-pricing.js` and records it, so the spend cap in `checkUserLlmSpendCap` is enforced on real numbers. What there is *not* today is a self-serve token-and-dollar breakdown chart per conversation, nor threshold email alerts. Budget with `monthly_quota` and `rate_limit_per_min` on the embed policy (Step 8) — those are hard, enforced-before-spend limits, which is a stronger control than an after-the-fact alert.
+**Cost.** The platform prices every call server-side through `api/_lib/llm-pricing.js` and records it, so the spend cap in `checkUserLlmSpendCap` is enforced on real numbers. What there is *not* today is a self-serve token-and-dollar breakdown chart per conversation, nor threshold email alerts. Budget with `monthly_quota` and `rate_limit_per_min` on the embed policy (Step 8), those are hard, enforced-before-spend limits, which is a stronger control than an after-the-fact alert.
Two specific things to watch:
-**Input-token growth across a session.** Long conversations accumulate context — every turn includes the full conversation history as input to the next turn. By turn 50 of a chat, your input tokens per turn might be 20x what they were at turn 1. If you're seeing surprisingly large bills, this is usually the cause. The fix is either tighter session-end heuristics (clear memory after N minutes idle) or summarising older turns into a single context message.
+**Input-token growth across a session.** Long conversations accumulate context, every turn includes the full conversation history as input to the next turn. By turn 50 of a chat, your input tokens per turn might be 20x what they were at turn 1. If you're seeing surprisingly large bills, this is usually the cause. The fix is either tighter session-end heuristics (clear memory after N minutes idle) or summarising older turns into a single context message.
**Tool-call expansion.** A tool that returns 5000 tokens of JSON balloons the next-turn input. If you have a skill that returns large data, summarise the response before it goes back to the model rather than passing the raw payload through.
@@ -282,7 +282,7 @@ For agents handling real volume, set `monthly_quota` deliberately rather than le
---
-## Step 8 — Switch models without changing your embed
+## Step 8: Switch models without changing your embed
This is the part that often surprises people: the embed snippet on your website doesn't know which model is running. Everything is on the agent record.
@@ -330,11 +330,11 @@ This makes A/B testing painless. Common patterns:
- **Capability spike.** Promote an agent to Opus 5 for a busy week (a launch, a marketing campaign), then dial back down to Sonnet 5 for steady-state.
- **Provider failover.** If one vendor has a brief outage, switch `brain.model` to a peer on another provider and keep traffic moving. You don't have to do this for transient errors, though: the proxy already walks a free-lane fallback chain on a quota/billing/rate-limit failure mid-request.
-The trick to making this work cleanly is to write your system prompt in a model-agnostic style. Prompts that lean hard on Claude-specific quirks ("respond in XML tags") can produce slightly different output on GPT. The prompt template in the [agent personality](/tutorials/agent-personality) tutorial is intentionally portable across providers — use that style and your switch-day surprises are minimal.
+The trick to making this work cleanly is to write your system prompt in a model-agnostic style. Prompts that lean hard on Claude-specific quirks ("respond in XML tags") can produce slightly different output on GPT. The prompt template in the [agent personality](/tutorials/agent-personality) tutorial is intentionally portable across providers, use that style and your switch-day surprises are minimal.
---
-## Step 9 — Self-hosted keys via key-proxy (advanced)
+## Step 9: Self-hosted keys via key-proxy (advanced)
The standard path is to store your key in the platform dashboard. If you have a stricter security posture and want to keep the key on infrastructure you control entirely, the platform supports a **key proxy** pattern: you run a tiny endpoint that vends short-lived, scoped tokens, and the platform calls your endpoint instead of holding the long-lived key.
@@ -354,7 +354,7 @@ The flow:
3. Every LLM call for this agent goes through your endpoint, so the long-lived key never leaves your infrastructure.
-This is genuinely advanced — most teams don't need it. The reasons to reach for it:
+This is genuinely advanced: most teams don't need it. The reasons to reach for it:
- Compliance requirements that prohibit storing third-party API keys outside your infrastructure
- Multi-tenant SaaS where each customer brings their own key and you don't want to pool them into a single account
@@ -364,7 +364,7 @@ For everything else, the dashboard key store is the right answer.
---
-## Step 10 — A concrete switch: walk through
+## Step 10: A concrete switch: walk through
To make this concrete, here's the actual sequence for moving a production agent off the free lane and onto Claude, then upgrading it.
@@ -389,7 +389,7 @@ The brain layer in full:
- The embed default is a free open-weight lane. Sonnet 5 is the recommended paid default; Opus 5 and GPT-5.6 Sol are the reasoning-grade upgrades, Fable 5 the ceiling; Haiku 4.5 and GPT-5.6 Luna are the latency picks
- Streaming is always on and matters more than total latency for perceived speed
- A visitor can never escalate you onto a paid model: the proxy clamps any first-party-billed model back to the owner's configured one
-- Tool-use quality varies by model — pick Sonnet 5 or larger for skill-heavy agents
+- Tool-use quality varies by model: pick Sonnet 5 or larger for skill-heavy agents
- `monthly_quota` and `rate_limit_per_min` on the embed policy are the real budget controls, enforced before spend; `GET /api/agents/:id/usage` is the counter to watch
- Switching models is one field on the embed policy; the embed snippet never needs to change
- Key proxies are an advanced option for compliance-heavy setups
@@ -398,6 +398,6 @@ The brain is the part of the agent you'll iterate on most after the system promp
## Next steps
-- [Give your agent a personality](/tutorials/agent-personality) — write a system prompt that holds across thousands of chats
-- [Add a custom skill](/tutorials/custom-skill) — give the brain tools to use
-- [Trigger the agent from page events](/tutorials/trigger-from-page-events) — wire the brain into your product flow
+- [Give your agent a personality](/tutorials/agent-personality), write a system prompt that holds across thousands of chats
+- [Add a custom skill](/tutorials/custom-skill): give the brain tools to use
+- [Trigger the agent from page events](/tutorials/trigger-from-page-events), wire the brain into your product flow
diff --git a/docs/tutorials/custom-skill.md b/docs/tutorials/custom-skill.md
index ab1055d0e..619a46326 100644
--- a/docs/tutorials/custom-skill.md
+++ b/docs/tutorials/custom-skill.md
@@ -1,6 +1,6 @@
# Build a Custom Skill
-By the end of this tutorial you will have a working **weather skill** that an agent can use to answer questions like "What's the weather in Tokyo?" — with the agent calling a live API and responding naturally in conversation.
+By the end of this tutorial you will have a working **weather skill** that an agent can use to answer questions like "What's the weather in Tokyo?", with the agent calling a live API and responding naturally in conversation.
Along the way you'll understand the skill bundle format, how the LLM decides when to invoke your tool, and how to reach back into the agent through the context API.
@@ -17,13 +17,13 @@ Agent: "Tokyo is currently 18°C with overcast skies and light rain.
Might want to pack an umbrella!"
```
-The agent doesn't hardcode weather logic. It reads your skill's tool description, decides when the user is asking about weather, and calls `get_weather` — your handler fetches live data and returns structured results that the agent narrates naturally.
+The agent doesn't hardcode weather logic. It reads your skill's tool description, decides when the user is asking about weather, and calls `get_weather`, your handler fetches live data and returns structured results that the agent narrates naturally.
---
## How skills work (two minutes of theory)
-A skill is a static file bundle — no server, no build step. It has four parts:
+A skill is a static file bundle: no server, no build step. It has four parts:
| File | Purpose |
|---|---|
@@ -37,7 +37,7 @@ When the runtime loads your skill it:
1. Fetches and validates `manifest.json`
2. Merges your tools from `tools.json` into the LLM's tool list
3. Injects `SKILL.md` into the system prompt as a `<skill>` block
-4. Runs `handlers.js` in a **sandboxed Web Worker** — it has no DOM access, no `window`, no direct network; everything goes through the `ctx` API
+4. Runs `handlers.js` in a **sandboxed Web Worker**, it has no DOM access, no `window`, no direct network; everything goes through the `ctx` API
The sandbox is the key safety primitive. Your handler can't accidentally read cookies or touch page state. All side effects go through `ctx.*` methods that the runtime validates and dispatches.
@@ -59,7 +59,7 @@ Create the folder and four empty files. Everything below fills them in.
## Step 2: Write manifest.json
-The manifest declares your skill's identity, what rig types it works with, and what tools it provides. It does **not** embed tool schemas — those live in `tools.json`.
+The manifest declares your skill's identity, what rig types it works with, and what tools it provides. It does **not** embed tool schemas, those live in `tools.json`.
```json
{
@@ -83,11 +83,11 @@ The manifest declares your skill's identity, what rig types it works with, and w
Key fields:
-- **`spec`** — always `"skill/0.1"` for the current format
-- **`provides.tools`** — names that must exactly match function exports in `handlers.js` and entries in `tools.json`
-- **`provides.triggers`** — semantic tags for skill discovery; the runtime can surface your skill when a user query matches these
-- **`requires.rig`** — which avatar rigs this skill supports; `"any"` works everywhere; use `"mixamo"` if your skill plays Mixamo-specific animation clips
-- **`author`** — optional, but used for the `owned-only` trust policy (see the security section)
+- **`spec`**: always `"skill/0.1"` for the current format
+- **`provides.tools`**: names that must exactly match function exports in `handlers.js` and entries in `tools.json`
+- **`provides.triggers`**: semantic tags for skill discovery; the runtime can surface your skill when a user query matches these
+- **`requires.rig`**: which avatar rigs this skill supports; `"any"` works everywhere; use `"mixamo"` if your skill plays Mixamo-specific animation clips
+- **`author`**: optional, but used for the `owned-only` trust policy (see the security section)
---
@@ -115,7 +115,7 @@ Use `get_weather` whenever the user asks about:
- Whether to bring an umbrella, coat, or sunscreen
- What the weather is like anywhere in the world
-When you receive weather data, respond conversationally — don't just repeat
+When you receive weather data, respond conversationally, don't just repeat
the raw fields. Mention conditions, temperature, and any useful context
(e.g. "perfect for a walk" or "might want to stay indoors").
@@ -124,7 +124,7 @@ If the user doesn't specify units, use celsius by default.
The frontmatter `cost: low` tells the runtime this is a cheap skill to load eagerly. For skills that load heavy assets, use `medium` or `high` to defer loading.
-The markdown body is your behavioral contract with the LLM. Write it like you'd write a Claude system prompt — clear, specific about when to invoke the tool, and with guidance on how to present the results.
+The markdown body is your behavioral contract with the LLM. Write it like you'd write a Claude system prompt, clear, specific about when to invoke the tool, and with guidance on how to present the results.
---
@@ -161,8 +161,8 @@ This is what the LLM actually sees as a callable function. The format follows th
The `description` field is doing real work here. The LLM reads it to decide **when** to call `get_weather`. Compare:
-- **Too vague:** `"Get weather"` — the agent might not connect this to "should I bring a jacket?"
-- **Right:** `"Get current weather conditions and temperature for a specific city. Use this when the user asks about weather, temperature, climate, or what to wear."` — the agent knows both the capability and the intent signals
+- **Too vague:** `"Get weather"`: the agent might not connect this to "should I bring a jacket?"
+- **Right:** `"Get current weather conditions and temperature for a specific city. Use this when the user asks about weather, temperature, climate, or what to wear."`, the agent knows both the capability and the intent signals
Every hour you spend writing a good tool description pays back in fewer missed invocations.
@@ -184,7 +184,7 @@ export async function get_weather({ city, units = 'celsius' }, ctx) {
// Pipe, not '+', because %t renders a signed value ("+27°C") and a
// '+' delimiter would split that sign into its own empty field.
// Units come from the `m` (metric) / `u` (USCS) flag, not the format
- // string — %f is "feels like", not Fahrenheit.
+ // string: %f is "feels like", not Fahrenheit.
const fmt = '%C|%t|%w|%p';
const unitFlag = units === 'celsius' ? 'm' : 'u';
const url = `${WEATHER_API_BASE}/${encodeURIComponent(city)}?format=${encodeURIComponent(fmt)}&lang=en&${unitFlag}`;
@@ -214,19 +214,19 @@ export async function get_weather({ city, units = 'celsius' }, ctx) {
Walk through what's happening:
-**`({ city, units = 'celsius' }, ctx)`** — the first argument is the validated parameters object the LLM passed; the second is the context object. Always destructure with defaults for optional params.
+**`({ city, units = 'celsius' }, ctx)`**: the first argument is the validated parameters object the LLM passed; the second is the context object. Always destructure with defaults for optional params.
-**`ctx.fetch(url)`** — this is the only way to make network calls from a handler. It's the worker's native `fetch` with standard CORS rules applied. You can't reach `window.fetch` directly (the handler runs in a Worker with no `window`).
+**`ctx.fetch(url)`**: this is the only way to make network calls from a handler. It's the worker's native `fetch` with standard CORS rules applied. You can't reach `window.fetch` directly (the handler runs in a Worker with no `window`).
-**`{ ok: true, ...data }` / `{ ok: false, error: "..." }`** — the runtime expects this shape. On `ok: false`, the runtime surfaces the error cleanly in the LLM conversation without crashing.
+**`{ ok: true, ...data }` / `{ ok: false, error: "..." }`**, the runtime expects this shape. On `ok: false`, the runtime surfaces the error cleanly in the LLM conversation without crashing.
-**No imports** — because the handler runs inside a sandboxed Web Worker loaded from a `blob:` URL, there's no module resolution context. You can't `import` external packages. Everything you need must come from `ctx.*` or be self-contained in the file.
+**No imports**: because the handler runs inside a sandboxed Web Worker loaded from a `blob:` URL, there's no module resolution context. You can't `import` external packages. Everything you need must come from `ctx.*` or be self-contained in the file.
---
## Step 6: Host the skill
-Skills must be accessible over HTTPS. They're static files — any static host works.
+Skills must be accessible over HTTPS. They're static files, any static host works.
**GitHub Pages (free, permanent URL):**
```bash
@@ -244,7 +244,7 @@ git push -u origin main
```bash
cd weather-skill
npx vercel
-# Follow the prompts — done in about 30 seconds
+# Follow the prompts: done in about 30 seconds
# Your manifest URL: https://weather-skill-abc123.vercel.app/manifest.json
```
@@ -255,12 +255,12 @@ npx serve .
# Terminal 2: expose it
npx ngrok http 3000
-# Copy the https://... URL — use it as your manifest URL
+# Copy the https://... URL: use it as your manifest URL
```
One thing to check after deploying: open the manifest URL directly in your browser. You should see raw JSON. If you see an error page or HTML, something's wrong with the hosting setup before you go further.
-Also verify that your host is sending CORS headers (`Access-Control-Allow-Origin: *`). GitHub Pages and Vercel do this by default. If you're using a custom server, add the header — the runtime's `fetch` calls will fail silently otherwise.
+Also verify that your host is sending CORS headers (`Access-Control-Allow-Origin: *`). GitHub Pages and Vercel do this by default. If you're using a custom server, add the header, the runtime's `fetch` calls will fail silently otherwise.
---
@@ -283,7 +283,7 @@ There are three ways, depending on how you're working.
}
```
-The `uri` points to the **directory**, not the manifest file. The runtime appends `manifest.json`, `SKILL.md`, `tools.json`, and `handlers.js` automatically. Make sure the URI ends with a trailing slash — the runtime uses it as a base for relative asset resolution.
+The `uri` points to the **directory**, not the manifest file. The runtime appends `manifest.json`, `SKILL.md`, `tools.json`, and `handlers.js` automatically. Make sure the URI ends with a trailing slash, the runtime uses it as a base for relative asset resolution.
**In the web component attribute** (comma-separated skill URIs, installed on top of any manifest skills):
@@ -310,19 +310,19 @@ With the agent running, type: **"What's the weather in Tokyo?"**
Watch what happens in DevTools → Network: you should see a fetch to `wttr.in` originating from the worker. The agent will receive the structured data back, and respond with something like:
-> "Tokyo is currently 18°C with overcast skies and wind at 15 km/h. Looks a bit grey today — maybe a good day for an indoor museum."
+> "Tokyo is currently 18°C with overcast skies and wind at 15 km/h. Looks a bit grey today, maybe a good day for an indoor museum."
If it doesn't invoke the tool:
- **Check the console** for skill load errors. A 404 on any of the four files silently skips the tool registration.
- **Verify the manifest URL** returns valid JSON when opened directly in a browser.
-- **Check CORS** — if the browser blocks the `manifest.json` fetch, the skill won't load.
-- **Check handler function name** — `get_weather` in `handlers.js` must match `"get_weather"` in `tools.json` and `provides.tools` in `manifest.json`. One character off and the tool silently fails.
+- **Check CORS**: if the browser blocks the `manifest.json` fetch, the skill won't load.
+- **Check handler function name**: `get_weather` in `handlers.js` must match `"get_weather"` in `tools.json` and `provides.tools` in `manifest.json`. One character off and the tool silently fails.
If the tool calls but returns an error:
- The wttr.in API is free and generally reliable, but city names need to be recognizable. Try a major city like `London` first.
-- Check that the worker can reach `wttr.in` — some corporate networks block unusual hostnames.
+- Check that the worker can reach `wttr.in`: some corporate networks block unusual hostnames.
---
@@ -332,8 +332,8 @@ Once you've confirmed the happy path, sharpen the tool description to handle edg
The LLM currently calls `get_weather` when it sees words like "weather" or "temperature." But what about:
-- "Should I pack a coat for my trip to Oslo next week?" — intent is weather, but the word isn't there
-- "Is it a good beach day in Sydney?" — the user wants weather but asked about activities
+- "Should I pack a coat for my trip to Oslo next week?", intent is weather, but the word isn't there
+- "Is it a good beach day in Sydney?": the user wants weather but asked about activities
Update `tools.json`:
@@ -410,7 +410,7 @@ export async function get_forecast({ city, days = 3 }, ctx) {
}
```
-One skill, two tools. The LLM picks `get_weather` for "what's the weather now" and `get_forecast` for "what will the weather be like this week" — because the descriptions tell it to.
+One skill, two tools. The LLM picks `get_weather` for "what's the weather now" and `get_forecast` for "what will the weather be like this week", because the descriptions tell it to.
---
@@ -443,27 +443,27 @@ export async function get_weather({ city, units = 'celsius' }, ctx) {
The full context surface:
```
-ctx.fetch(url) — safe network call (CORS applies)
-ctx.memory.read(key) — read a stored value
-ctx.memory.write(key, val) — write a value
-ctx.memory.note(type, data) — append to a timeline (good for history)
-ctx.memory.recall(query) — substring search over notes
-ctx.speak(text) — make the agent say something mid-tool
-ctx.listen() — wait for user voice/text input
-ctx.call(toolName, args) — invoke another tool (cross-skill calls)
-ctx.loadGLB(uri) — load a 3D model
-ctx.loadClip(uri) — load an animation clip
-ctx.loadJSON(uri) — load a JSON file from a URL
-ctx.viewer.play(clip) — play a loaded clip on the avatar
-ctx.viewer.setExpression(p) — set facial expression preset
-ctx.viewer.lookAt(target) — direct the avatar's gaze
-ctx.llm.complete(prompt) — call the LLM directly (advanced)
-ctx.skillBaseURI — base URL of this skill bundle
+ctx.fetch(url) : safe network call (CORS applies)
+ctx.memory.read(key) : read a stored value
+ctx.memory.write(key, val) : write a value
+ctx.memory.note(type, data): append to a timeline (good for history)
+ctx.memory.recall(query) : substring search over notes
+ctx.speak(text) : make the agent say something mid-tool
+ctx.listen() : wait for user voice/text input
+ctx.call(toolName, args) : invoke another tool (cross-skill calls)
+ctx.loadGLB(uri) : load a 3D model
+ctx.loadClip(uri) : load an animation clip
+ctx.loadJSON(uri) : load a JSON file from a URL
+ctx.viewer.play(clip) : play a loaded clip on the avatar
+ctx.viewer.setExpression(p): set facial expression preset
+ctx.viewer.lookAt(target) : direct the avatar's gaze
+ctx.llm.complete(prompt) : call the LLM directly (advanced)
+ctx.skillBaseURI : base URL of this skill bundle
```
-`ctx.memory.note` is useful for building history without explicit keys — it appends to an internal timeline that you can later query with `ctx.memory.recall('weather')`. Good for tracking what the user has asked about across a session.
+`ctx.memory.note` is useful for building history without explicit keys, it appends to an internal timeline that you can later query with `ctx.memory.recall('weather')`. Good for tracking what the user has asked about across a session.
-`ctx.speak` runs mid-handler, before you return. Use it to give the user feedback when a fetch might take a moment. Don't overdo it — a quick `"Let me check..."` is good; narrating every internal step is annoying.
+`ctx.speak` runs mid-handler, before you return. Use it to give the user feedback when a fetch might take a moment. Don't overdo it, a quick `"Let me check..."` is good; narrating every internal step is annoying.
---
@@ -477,7 +477,7 @@ Understanding the sandbox helps you write handlers that work with it rather than
**No imports.** Because handlers load from a `blob:` URL with no base URL context, relative `import` statements silently fail. All logic must be self-contained in `handlers.js`. If you need utilities, inline them.
-**`trusted-main-thread` opt-out.** Owner-signed skills that need direct Three.js access can set `"sandboxPolicy": "trusted-main-thread"` in `manifest.json`. This runs the handler in the main thread. Only meaningful for skills that pass the agent's trust policy — default is `owned-only`, which requires `manifest.json`'s `author` to match the agent owner's wallet address.
+**`trusted-main-thread` opt-out.** Owner-signed skills that need direct Three.js access can set `"sandboxPolicy": "trusted-main-thread"` in `manifest.json`. This runs the handler in the main thread. Only meaningful for skills that pass the agent's trust policy, default is `owned-only`, which requires `manifest.json`'s `author` to match the agent owner's wallet address.
For the weather skill and most API-integration skills, the default sandbox is all you need.
@@ -489,11 +489,11 @@ Your weather skill is a template for any external API integration. The pattern i
Good skills to build next:
-- **Financial data** — token prices, portfolio values, DCA calculations
-- **GitHub integration** — open PRs, recent commits, issue status
-- **Spotify** — currently playing, queue management
-- **Notion / Linear** — read and write tickets or docs
-- **Domain knowledge** — a skill that's pure `SKILL.md` with no tools, injecting specialized context (legal, medical, culinary)
+- **Financial data**: token prices, portfolio values, DCA calculations
+- **GitHub integration**: open PRs, recent commits, issue status
+- **Spotify**: currently playing, queue management
+- **Notion / Linear**: read and write tickets or docs
+- **Domain knowledge**: a skill that's pure `SKILL.md` with no tools, injecting specialized context (legal, medical, culinary)
Sharing your skill is as simple as posting the manifest URL. Add the topic `3dagent-skill` to your GitHub repo so others can find it, and browse what the community has built on the [Skills Marketplace](/skills).
@@ -503,10 +503,10 @@ Sharing your skill is as simple as posting the manifest URL. Add the topic `3dag
You built a weather skill with these four files:
-- **`manifest.json`** — declares identity, rig compatibility, and what tools the skill provides
-- **`SKILL.md`** — the behavioral contract injected into the LLM's system prompt; tells the agent *when* and *how* to use the tool
-- **`tools.json`** — the tool schema the LLM invokes; `input_schema` in Anthropic format; the `description` is prompt-engineered
-- **`handlers.js`** — exports one function per tool; runs sandboxed in a Web Worker; all I/O through `ctx.*`
+- **`manifest.json`**: declares identity, rig compatibility, and what tools the skill provides
+- **`SKILL.md`**: the behavioral contract injected into the LLM's system prompt; tells the agent *when* and *how* to use the tool
+- **`tools.json`**: the tool schema the LLM invokes; `input_schema` in Anthropic format; the `description` is prompt-engineered
+- **`handlers.js`**: exports one function per tool; runs sandboxed in a Web Worker; all I/O through `ctx.*`
The skill installs via a URI in the agent manifest, runs entirely client-side, and adds new capabilities to any compatible agent without modifying the agent itself. That's the composability primitive: agents are extensible at runtime through content-addressed skill bundles.
diff --git a/docs/tutorials/emotion-from-data.md b/docs/tutorials/emotion-from-data.md
index cfd402ac1..b54b9c89a 100644
--- a/docs/tutorials/emotion-from-data.md
+++ b/docs/tutorials/emotion-from-data.md
@@ -1,6 +1,6 @@
# Animations from data: wire your agent's gestures to real APIs and AI
-An agent that just idles is furniture. An agent that visibly *reacts* — dances when something spikes, flinches when something drops, celebrates a milestone — reads as alive. three.ws ships a full animation library (idle, wave, dance, celebrate, jump, dozens more — browse them at [/animations](/animations)) and a public JS API to trigger any of it on command. This tutorial shows you how to point that at data you actually have: a live feed, a webhook, or a real AI model classifying arbitrary text.
+An agent that just idles is furniture. An agent that visibly *reacts*, dances when something spikes, flinches when something drops, celebrates a milestone, reads as alive. three.ws ships a full animation library (idle, wave, dance, celebrate, jump, dozens more, browse them at [/animations](/animations)) and a public JS API to trigger any of it on command. This tutorial shows you how to point that at data you actually have: a live feed, a webhook, or a real AI model classifying arbitrary text.
You'll build two working pipelines. One uses zero AI (a lexicon sentiment score, free, no key, triggering a real body animation), one puts a real model in the loop (IBM Granite reading arbitrary documents, feeding a graded set of gestures). Both use the cooldown pattern that keeps an automated agent from spamming animations every tick.
@@ -10,17 +10,17 @@ You'll build two working pipelines. One uses zero AI (a lexicon sentiment score,
- A cooldown/dedupe pattern so a fast-moving data source doesn't retrigger the same animation every poll
- The two real, documented entry points for animation: `agent.play(clipName)` (exact clip) and `agent.playEmote(name)` (semantic, with a fallback chain)
-**Prerequisites:** You've completed [first agent](/tutorials/first-agent) or have an `<agent-3d>` element on a page, and ideally [the JS API tutorial](/tutorials/js-api-events) (Step 5 covers the animation basics this one builds on). For the AI lane, a small amount of USDC and familiarity with the [x402 payment flow](/tutorials/pay-for-x402-service) — the call costs $0.04.
+**Prerequisites:** You've completed [first agent](/tutorials/first-agent) or have an `<agent-3d>` element on a page, and ideally [the JS API tutorial](/tutorials/js-api-events) (Step 5 covers the animation basics this one builds on). For the AI lane, a small amount of USDC and familiarity with the [x402 payment flow](/tutorials/pay-for-x402-service), the call costs $0.04.
---
-## Step 1 — The two animation entry points
+## Step 1: The two animation entry points
-Every `<agent-3d>` element exposes two public methods for triggering body animation, and — per the [JS API tutorial](/tutorials/js-api-events#step-5--animations-exact-clip-vs-emote) — they answer different questions.
+Every `<agent-3d>` element exposes two public methods for triggering body animation, and, per the [JS API tutorial](/tutorials/js-api-events#step-5--animations-exact-clip-vs-emote), they answer different questions.
-**`agent.play(clipName)`** — plays the clip with that *exact* name from the loaded library or GLB. Case-sensitive; if the name isn't found, nothing plays. Use this once you know what's actually in the rig — e.g. `agent.play('rumba')`, `agent.play('thriller')`, `agent.play('celebrate')`. The full catalog (idle, locomotion, dance, gesture, action, sport, reaction, fitness — every clip a real, retargetable library entry, never hardcoded per-rig) is browsable at [/animations](/animations).
+**`agent.play(clipName)`**: plays the clip with that *exact* name from the loaded library or GLB. Case-sensitive; if the name isn't found, nothing plays. Use this once you know what's actually in the rig, e.g. `agent.play('rumba')`, `agent.play('thriller')`, `agent.play('celebrate')`. The full catalog (idle, locomotion, dance, gesture, action, sport, reaction, fitness, every clip a real, retargetable library entry, never hardcoded per-rig) is browsable at [/animations](/animations).
-**`agent.playEmote(name)`** — a higher-level wrapper for the small set of product-moment reactions with a built-in fallback chain, so it's guaranteed to do *something* regardless of which clips the loaded rig actually has:
+**`agent.playEmote(name)`**: a higher-level wrapper for the small set of product-moment reactions with a built-in fallback chain, so it's guaranteed to do *something* regardless of which clips the loaded rig actually has:
```js
agent.playEmote('celebrate'); // celebrate → wave
@@ -28,17 +28,17 @@ agent.playEmote('cheer'); // cheer → celebrate → wave
agent.playEmote('flinch'); // flinch → defeated → concern → shake
```
-If none of a chain's names exist on the rig, `playEmote` falls back to a small head-bob rather than doing nothing — so it's the safe default for "react to this event" code, and `play()` is for "I know exactly which clip I want."
+If none of a chain's names exist on the rig, `playEmote` falls back to a small head-bob rather than doing nothing, so it's the safe default for "react to this event" code, and `play()` is for "I know exactly which clip I want."
Convenience shortcut: `agent.wave()`.
-The pattern for "animation from data" is: **your data source picks a discrete outcome** (celebrate / flinch / a specific dance), and you call `playEmote()` or `play()` with that name. Unlike the sustained facial-mood layer (`setMood()` — covered separately, see the note at the end), these are one-shot performances that play out and settle back to idle on their own.
+The pattern for "animation from data" is: **your data source picks a discrete outcome** (celebrate / flinch / a specific dance), and you call `playEmote()` or `play()` with that name. Unlike the sustained facial-mood layer (`setMood()`, covered separately, see the note at the end), these are one-shot performances that play out and settle back to idle on their own.
---
-## Step 2 — The free lane: sentiment → animation, no AI required
+## Step 2: The free lane: sentiment → animation, no AI required
-The platform runs a public, unauthenticated sentiment scorer over live pump.fun token chat: [`POST /api/social/sentiment-pulse`](../../api/social/sentiment-pulse.js). It pulls recent comments for a token and scores them with an in-repo lexicon (no LLM call, no key) — good enough to prove the wiring before you reach for a model.
+The platform runs a public, unauthenticated sentiment scorer over live pump.fun token chat: [`POST /api/social/sentiment-pulse`](../../api/social/sentiment-pulse.js). It pulls recent comments for a token and scores them with an in-repo lexicon (no LLM call, no key), good enough to prove the wiring before you reach for a model.
```html
<!DOCTYPE html>
@@ -69,7 +69,7 @@ The platform runs a public, unauthenticated sentiment scorer over live pump.fun
function reactTo(overall) {
// scoreSentiment() returns score in [-1, 1] and posPct/negPct/count.
- // Require both a strong score AND enough chatter to trust it — a
+ // Require both a strong score AND enough chatter to trust it, a
// single glowing comment shouldn't trigger a full celebration.
const confident = overall.count >= 5;
const now = performance.now();
@@ -99,20 +99,20 @@ The platform runs a public, unauthenticated sentiment scorer over live pump.fun
</html>
```
-Save that as `index.html` and open it — no build step, no server, no wallet. Swap `TOKEN` for any Solana mint and the agent physically celebrates or flinches as that token's live chat swings.
+Save that as `index.html` and open it: no build step, no server, no wallet. Swap `TOKEN` for any Solana mint and the agent physically celebrates or flinches as that token's live chat swings.
---
-## Step 3 — The AI lane: real classification over arbitrary data, richer gestures
+## Step 3: The AI lane: real classification over arbitrary data, richer gestures
A lexicon scorer only works on short, informal text, and it only fires on words it already knows. For real documents (support tickets, product reviews, meeting transcripts, incident reports) you want a model that actually reads the thing and returns *structured* output: a graded sentiment score plus the findings and risk flags behind it, so the reaction tracks the document's real tone instead of its vocabulary. `ibm_granite_analyze` (part of the [IBM Granite x402 MCP suite](../ibm-x402-mcp.md)) does exactly this for $0.04/call, no IBM account needed: you pay in USDC, it pays IBM.
The tool returns a fixed set of keys: `summary`, `entities`, `sentiment` (`{ overall, score }`, score in -1..1), `key_findings`, `risk_flags` (each with a `severity`), and `next_steps`. The two the animation layer cares about are `sentiment.score` and `risk_flags`.
-This is a server-side call (it needs a wallet to sign the payment), so it lives behind a small endpoint you host yourself and the browser polls. The `@three-ws/x402-fetch` package does the 402 → sign → retry dance for you — see [pay-for-x402-service](/tutorials/pay-for-x402-service) for the full protocol if you want the mechanics.
+This is a server-side call (it needs a wallet to sign the payment), so it lives behind a small endpoint you host yourself and the browser polls. The `@three-ws/x402-fetch` package does the 402 → sign → retry dance for you, see [pay-for-x402-service](/tutorials/pay-for-x402-service) for the full protocol if you want the mechanics.
```js
-// gesture-from-ai.js — run with `node gesture-from-ai.js`, or drop the body of
+// gesture-from-ai.js: run with `node gesture-from-ai.js`, or drop the body of
// gestureFor() into any serverless handler (Vercel/Cloud Run/etc).
import { withX402, privateKeyToWallet } from '@three-ws/x402-fetch';
@@ -168,7 +168,7 @@ async function gestureFor(document) {
}
```
-Wire that into a one-route endpoint (`GET /gesture?text=...` returning the JSON above), and the browser side reuses the same cooldown-gated `reactTo()` shape from Step 2 — swap the fetch call and the trigger:
+Wire that into a one-route endpoint (`GET /gesture?text=...` returning the JSON above), and the browser side reuses the same cooldown-gated `reactTo()` shape from Step 2, swap the fetch call and the trigger:
```js
async function tick() {
@@ -182,16 +182,16 @@ async function tick() {
}
```
-Now anything you can turn into a string — a webhook payload, a scraped page, a batch of reviews — can drive a specific, visible body performance instead of a static idle loop.
+Now anything you can turn into a string: a webhook payload, a scraped page, a batch of reviews, can drive a specific, visible body performance instead of a static idle loop.
---
-## Step 4 — Don't let fast data spam the animation queue
+## Step 4: Don't let fast data spam the animation queue
-Two rules worth copying from the platform's own production reaction engine ([`src/widgets/pumpfun-reactions.js`](../../src/widgets/pumpfun-reactions.js) — the pump.fun live-trade avatar reactor, 23 distinct clips across dozens of event shapes):
+Two rules worth copying from the platform's own production reaction engine ([`src/widgets/pumpfun-reactions.js`](../../src/widgets/pumpfun-reactions.js), the pump.fun live-trade avatar reactor, 23 distinct clips across dozens of event shapes):
-1. **Cooldown, not "react to every event."** A fast feed (trades, comments, ticks) will fire far more often than a physical performance can play out. Gate triggers behind a minimum interval (`COOLDOWN_MS` above) — the production reactor goes further and queues lower-priority events behind an in-flight gesture instead of dropping or interrupting it.
-2. **Require confidence before you interrupt idle.** A single data point (one comment, one weak signal) shouldn't yank the avatar out of idle. Both examples above gate on a minimum sample size / signal strength (`overall.count >= 5`, `strength >= 0.3`) — tune the threshold to your own data's noise floor.
+1. **Cooldown, not "react to every event."** A fast feed (trades, comments, ticks) will fire far more often than a physical performance can play out. Gate triggers behind a minimum interval (`COOLDOWN_MS` above), the production reactor goes further and queues lower-priority events behind an in-flight gesture instead of dropping or interrupting it.
+2. **Require confidence before you interrupt idle.** A single data point (one comment, one weak signal) shouldn't yank the avatar out of idle. Both examples above gate on a minimum sample size / signal strength (`overall.count >= 5`, `strength >= 0.3`), tune the threshold to your own data's noise floor.
```js
let lastFired = 0;
@@ -210,16 +210,16 @@ function reactIfConfident(clipOrEmoteName, { confident, useExactClip = false } =
## A note on the facial layer
-`agent.play()` / `agent.playEmote()` drive the *body* directly — the skeleton, via the shared animation-clip library, for a one-shot performance you chose explicitly. `agent.setMood(valence, arousal)` / `agent.expressEmotion(trigger, weight)` primarily drive the *face* — ARKit-52 blendshapes (smile, brow, gaze) on avatars that carry them, without touching the skeleton. They're still distinct APIs for distinct calls (`play`/`playEmote` for "perform this exact gesture now" vs. `setMood`/`expressEmotion` for "this is how the agent feels"), but they're not fully independent: once nothing more urgent (like a `play()`/`playEmote()` call or a fresh `expressEmotion()` spike) already claims the ambient gesture slot, a *sustained* `setMood()` also lightly biases which idle-time gesture the body reaches for — energetic-positive moods lean toward `celebrate`, subdued-negative moods toward `concern` — so a happy agent doesn't just smile while standing dead still. See [Animate your avatar → Emotion and expression on the live agent](animate-your-avatar.md#emotion-and-expression-on-the-live-agent) for the full wiring. This tutorial covers explicit body triggers; if you want the face (and the ambient body bias) to track data too, the same fetch/cooldown pattern above applies, just swapping in `setMood()`/`expressEmotion()`.
+`agent.play()` / `agent.playEmote()` drive the *body* directly, the skeleton, via the shared animation-clip library, for a one-shot performance you chose explicitly. `agent.setMood(valence, arousal)` / `agent.expressEmotion(trigger, weight)` primarily drive the *face*, ARKit-52 blendshapes (smile, brow, gaze) on avatars that carry them, without touching the skeleton. They're still distinct APIs for distinct calls (`play`/`playEmote` for "perform this exact gesture now" vs. `setMood`/`expressEmotion` for "this is how the agent feels"), but they're not fully independent: once nothing more urgent (like a `play()`/`playEmote()` call or a fresh `expressEmotion()` spike) already claims the ambient gesture slot, a *sustained* `setMood()` also lightly biases which idle-time gesture the body reaches for, energetic-positive moods lean toward `celebrate`, subdued-negative moods toward `concern`, so a happy agent doesn't just smile while standing dead still. See [Animate your avatar → Emotion and expression on the live agent](animate-your-avatar.md#emotion-and-expression-on-the-live-agent) for the full wiring. This tutorial covers explicit body triggers; if you want the face (and the ambient body bias) to track data too, the same fetch/cooldown pattern above applies, just swapping in `setMood()`/`expressEmotion()`.
---
## Troubleshooting
-- **Nothing plays.** Confirm `agent:ready` fired before your first `play()`/`playEmote()` call — calling either before boot is silently a no-op. Wrap your first tick in the `agent:ready` listener as shown in Step 2.
-- **`agent.play('someClip')` does nothing.** The name is case-sensitive and must match a clip actually present on the rig — check the exact name at [/animations](/animations) or fall back to `playEmote()`, which degrades gracefully instead of silently failing.
+- **Nothing plays.** Confirm `agent:ready` fired before your first `play()`/`playEmote()` call, calling either before boot is silently a no-op. Wrap your first tick in the `agent:ready` listener as shown in Step 2.
+- **`agent.play('someClip')` does nothing.** The name is case-sensitive and must match a clip actually present on the rig, check the exact name at [/animations](/animations) or fall back to `playEmote()`, which degrades gracefully instead of silently failing.
- **The agent keeps re-celebrating every poll.** You skipped the cooldown gate in Step 4, or your confidence threshold is too low for a noisy feed. Widen `COOLDOWN_MS` or raise the sample-size/strength floor.
-- **AI lane 402 loop / never resolves.** Your `SOLANA_PRIVATE_KEY` wallet has no USDC. Fund it with a few cents — see the [x402 payment flow](/tutorials/pay-for-x402-service).
+- **AI lane 402 loop / never resolves.** Your `SOLANA_PRIVATE_KEY` wallet has no USDC. Fund it with a few cents, see the [x402 payment flow](/tutorials/pay-for-x402-service).
- **`analysis.sentiment` is undefined.** Granite returned something that wasn't a clean JSON analysis object; the tool falls back to `{ ok: true, raw_response, parse_error }` in that case. Log `analysis.parse_error` and `analysis.raw_response` to see what came back. The `gestureFor()` above already treats a missing score as "no gesture" rather than crashing.
- **Every document scores middling and nothing ever plays.** `analysis_type: 'sentiment'` tunes the model toward tone; the other five types (`general`, `contract`, `financial`, `technical`, `medical`) return the same keys but reason about different things, so a contract analyzed as `general` often lands near 0. Match the type to your data (see [ibm-x402-mcp](../ibm-x402-mcp.md)).
@@ -227,9 +227,9 @@ function reactIfConfident(clipOrEmoteName, { confident, useExactClip = false } =
## Recap
-- `agent.play(clipName)` for an exact clip, `agent.playEmote(name)` for a safer semantic trigger with a fallback chain — both are public methods on every `<agent-3d>` element, no library beyond the CDN script.
+- `agent.play(clipName)` for an exact clip, `agent.playEmote(name)` for a safer semantic trigger with a fallback chain, both are public methods on every `<agent-3d>` element, no library beyond the CDN script.
- The free lane (`/api/social/sentiment-pulse`) proves the wiring with zero AI and zero cost.
- The AI lane (`ibm_granite_analyze` over x402) turns arbitrary documents into a graded sentiment score plus risk flags, which drives more of the animation library than a lexicon's positive/negative split can reach.
-- Gate every automated trigger behind a cooldown and a confidence floor — [`pumpfun-reactions.js`](../../src/widgets/pumpfun-reactions.js) is the production-grade version of this exact pattern, queueing and prioritizing real trade-feed events across 23 distinct clips.
+- Gate every automated trigger behind a cooldown and a confidence floor, [`pumpfun-reactions.js`](../../src/widgets/pumpfun-reactions.js) is the production-grade version of this exact pattern, queueing and prioritizing real trade-feed events across 23 distinct clips.
-**Related tutorials:** [The JS API — animations, exact name vs. hint](/tutorials/js-api-events) · [Trigger the agent from page events](/tutorials/trigger-from-page-events) · [Animate your avatar](/tutorials/animate-your-avatar) · [Discover and pay for an x402 service](/tutorials/pay-for-x402-service)
+**Related tutorials:** [The JS API: animations, exact name vs. hint](/tutorials/js-api-events) · [Trigger the agent from page events](/tutorials/trigger-from-page-events) · [Animate your avatar](/tutorials/animate-your-avatar) · [Discover and pay for an x402 service](/tutorials/pay-for-x402-service)
diff --git a/docs/tutorials/js-api-events.md b/docs/tutorials/js-api-events.md
index 88ddf6e87..b33527e49 100644
--- a/docs/tutorials/js-api-events.md
+++ b/docs/tutorials/js-api-events.md
@@ -1,21 +1,21 @@
# Drive the agent with the JavaScript API
-The script tag is the easy mode. It drops a 3D agent on your page, gives it a chat input, and walks away. That's enough for a contact widget. But once you start treating the agent like a real part of your product — something that reacts to clicks, scroll position, form submits, and checkout success — you need the JavaScript API.
+The script tag is the easy mode. It drops a 3D agent on your page, gives it a chat input, and walks away. That's enough for a contact widget. But once you start treating the agent like a real part of your product, something that reacts to clicks, scroll position, form submits, and checkout success, you need the JavaScript API.
-This tutorial covers the full handle-to-event lifecycle. By the end you will know how to grab the agent element, wait for it to be truly ready, fire animations and speech in response to user actions, listen for the events the agent emits back, and chain everything together into a real product moment — a checkout celebration sequence that fires on a successful order.
+This tutorial covers the full handle-to-event lifecycle. By the end you will know how to grab the agent element, wait for it to be truly ready, fire animations and speech in response to user actions, listen for the events the agent emits back, and chain everything together into a real product moment, a checkout celebration sequence that fires on a successful order.
**What you'll build:**
- A live page where the agent reacts to clicks and form events
- A "wait until ready" pattern that never tries to drive an unbooted agent
- A queue that chains `ask`, `play`, and `lookAt` without overlap
- A listener that reads back every word the agent says
-- A checkout celebration flow — submit a form, the agent cheers, narrates, and goes idle
+- A checkout celebration flow: submit a form, the agent cheers, narrates, and goes idle
**Prerequisites:** Comfort with vanilla DOM APIs (`querySelector`, `addEventListener`), promises, and async/await. You should have completed the [first-agent tutorial](/tutorials/first-agent) or have an agent ID from [three.ws/my-agents](https://three.ws/my-agents).
---
-## Step 1 — Drop the agent on the page
+## Step 1: Drop the agent on the page
Start with the simplest possible embed. Create `index.html` and paste this:
@@ -83,13 +83,13 @@ function logLine(text) {
logLine('Page loaded. Waiting for agent to boot...');
```
-Serve it locally — `python3 -m http.server 8080` works — and open `http://localhost:8080`. The agent appears. Nothing else does. Good.
+Serve it locally: `python3 -m http.server 8080` works, and open `http://localhost:8080`. The agent appears. Nothing else does. Good.
---
-## Step 2 — Get a handle to the agent
+## Step 2: Get a handle to the agent
-The `<agent-3d>` element is a custom element. `document.getElementById('agent')` gives you back an `Agent3DElement` instance with the full API attached — the CDN script's only job is registering that element, so every `<agent-3d>` tag on the page is a live API handle.
+The `<agent-3d>` element is a custom element. `document.getElementById('agent')` gives you back an `Agent3DElement` instance with the full API attached, the CDN script's only job is registering that element, so every `<agent-3d>` tag on the page is a live API handle.
If you didn't put an `id` on the tag (or you're writing code that runs on pages you don't control), grab the first agent on the page instead:
@@ -101,7 +101,7 @@ Either lookup returns the same element with the same JavaScript API from this po
---
-## Step 3 — Wait for ready, always
+## Step 3: Wait for ready, always
This is the rule that prevents 90% of the headaches you would otherwise hit. The agent does a lot at boot: fetches the manifest, downloads a GLB body (often several megabytes), warms up the runtime, registers skills, and resolves the brain. None of `.speak()`, `.wave()`, or `.say()` will do anything useful until that finishes.
@@ -113,7 +113,7 @@ agent.addEventListener('agent:ready', (e) => {
});
```
-`e.detail.manifest` contains the resolved manifest — name, description, body URL, brain config, the lot. If you need anything from it, grab it here.
+`e.detail.manifest` contains the resolved manifest, name, description, body URL, brain config, the lot. If you need anything from it, grab it here.
But what if you have code that runs *after* the page might have already booted? A common case: a button handler that fires whenever the user clicks, where the click could happen before or after boot. You need a promise that resolves when the agent is ready, no matter when you call it.
@@ -132,7 +132,7 @@ function whenReady(el) {
}
```
-The `_mounted` flag is set by the runtime once boot finishes, so if the agent is already ready the promise resolves immediately. Otherwise it waits for the event. This pattern is in the element's own `_waitForReady` helper — we're just exposing it as a public utility.
+The `_mounted` flag is set by the runtime once boot finishes, so if the agent is already ready the promise resolves immediately. Otherwise it waits for the event. This pattern is in the element's own `_waitForReady` helper, we're just exposing it as a public utility.
Now every action handler starts the same way:
@@ -147,15 +147,15 @@ No race conditions, no "I clicked but nothing happened on the first try" bugs.
---
-## Step 4 — The two ways to speak
+## Step 4: The two ways to speak
The agent has two methods that look similar but do different things. Picking the right one matters.
-**`agent.speak(text)`** — plays a talking *gesture* sized to the length of the text (roughly 0.3s per word, minimum 1.5s). It is silent: no LLM, no audio, no chat bubble. Use it to add life to a scripted moment where the page itself supplies the words on screen. Cheap, instant, deterministic.
+**`agent.speak(text)`**: plays a talking *gesture* sized to the length of the text (roughly 0.3s per word, minimum 1.5s). It is silent: no LLM, no audio, no chat bubble. Use it to add life to a scripted moment where the page itself supplies the words on screen. Cheap, instant, deterministic.
-**`agent.say(text)`** — sends `text` to the brain as a user message. The reply renders in the chat bubble and is spoken aloud when the `voice` attribute is set. This is what the built-in chat input calls. It's fire-and-forget: it returns immediately, and if you call it again while a turn is in flight, the newest message replaces the queued one.
+**`agent.say(text)`**: sends `text` to the brain as a user message. The reply renders in the chat bubble and is spoken aloud when the `voice` attribute is set. This is what the built-in chat input calls. It's fire-and-forget: it returns immediately, and if you call it again while a turn is in flight, the newest message replaces the queued one.
-**`agent.ask(text)`** — same brain turn as `say`, but returns a promise that resolves with the reply text once the response (and its speech, if voice is on) has finished. Reach for it whenever you need to await the turn or use the reply.
+**`agent.ask(text)`**: same brain turn as `say`, but returns a promise that resolves with the reply text once the response (and its speech, if voice is on) has finished. Reach for it whenever you need to await the turn or use the reply.
Most page-driven interactions want `say` or `ask`. Use `speak` when all you need is the gesture.
@@ -164,13 +164,13 @@ Wire up two buttons:
```js
document.getElementById('btn-greet').addEventListener('click', async () => {
await whenReady(agent);
- // Silent talking gesture — pair it with your own on-page caption.
+ // Silent talking gesture: pair it with your own on-page caption.
agent.speak('Hey there. Glad you stopped by.');
});
document.getElementById('btn-think').addEventListener('click', async () => {
await whenReady(agent);
- // Goes through the LLM — the model decides what to say.
+ // Goes through the LLM: the model decides what to say.
agent.say('Tell me a one-sentence fun fact.');
});
```
@@ -179,13 +179,13 @@ Click both. The first animates instantly and makes no sound. The second pauses b
---
-## Step 5 — Animations: exact clip vs emote
+## Step 5: Animations: exact clip vs emote
The agent has two ways to pick an animation clip. They map to two different mental models.
-**`agent.play(name)`** — plays the clip with that name from the loaded rig: an exact match first, then a case-insensitive one, then a case-insensitive substring match. If the GLB carries no such clip, it looks the name up in the shared animation library instead, and only returns `false` when neither source can supply it. Use this when you know what's in the rig — for instance, if you've baked a `WaveLoop` clip yourself.
+**`agent.play(name)`**: plays the clip with that name from the loaded rig: an exact match first, then a case-insensitive one, then a case-insensitive substring match. If the GLB carries no such clip, it looks the name up in the shared animation library instead, and only returns `false` when neither source can supply it. Use this when you know what's in the rig, for instance, if you've baked a `WaveLoop` clip yourself.
-**`agent.playEmote(name)`** — the resilient one. Instead of a clip name it takes an intent — `'celebrate'`, `'cheer'`, or `'flinch'` — and walks a fallback chain of clips until one exists in the rig (`celebrate` → `wave`; `cheer` → `celebrate` → `wave`; `flinch` → `defeated` → `concern` → `shake`). If none of them are present, it finishes with a small head-bob, so it's guaranteed to do *something* regardless of the rig.
+**`agent.playEmote(name)`**: the resilient one. Instead of a clip name it takes an intent, `'celebrate'`, `'cheer'`, or `'flinch'`, and walks a fallback chain of clips until one exists in the rig (`celebrate` → `wave`; `cheer` → `celebrate` → `wave`; `flinch` → `defeated` → `concern` → `shake`). If none of them are present, it finishes with a small head-bob, so it's guaranteed to do *something* regardless of the rig.
For product moments, prefer the emote version:
@@ -215,9 +215,9 @@ document.getElementById('btn-clear').addEventListener('click', async () => {
---
-## Step 6 — Listen back: the event lifecycle
+## Step 6: Listen back: the event lifecycle
-So far we've been issuing commands. The agent also emits events you can listen for — and they're the foundation of most useful integrations.
+So far we've been issuing commands. The agent also emits events you can listen for, and they're the foundation of most useful integrations.
Here are the events that actually fire, in the order you'll usually see them in one chat turn:
@@ -230,7 +230,7 @@ Here are the events that actually fire, in the order you'll usually see them in
| `skill:tool-start` | A tool/skill is about to run | `{ tool, args }` |
| `skill:tool-called` | A tool returned | `{ tool, args, result }` |
| `voice:speech-start` | The agent began speaking out loud | `{ text }` |
-| `voice:speech-end` | The agent finished speaking | — |
+| `voice:speech-end` | The agent finished speaking | - |
| `voice:transcript` | Mic input was transcribed | `{ text, final }` |
| `memory:write` | Something was written to memory | `{ scope, key, value }` |
@@ -262,18 +262,18 @@ Click "Think about something" and watch the order. Boot → ready → thinking s
Every one of these is a hook for your app. A few common patterns:
-- **Show a typing indicator** — switch a CSS class on `brain:thinking` and clear it on `brain:message`.
-- **Mirror chat to your own UI** — listen to `brain:message` and append `e.detail.content` to your message log when `role === 'assistant'`.
-- **Track skill usage** — `skill:tool-called` tells you which skill ran (`e.detail.tool`), with what arguments, and what came back. Log it to your analytics.
-- **React to speech state** — disable an input while `voice:speech-start` is active, re-enable on `voice:speech-end`. Stops the user from interrupting the agent mid-sentence.
+- **Show a typing indicator**: switch a CSS class on `brain:thinking` and clear it on `brain:message`.
+- **Mirror chat to your own UI**: listen to `brain:message` and append `e.detail.content` to your message log when `role === 'assistant'`.
+- **Track skill usage**: `skill:tool-called` tells you which skill ran (`e.detail.tool`), with what arguments, and what came back. Log it to your analytics.
+- **React to speech state**: disable an input while `voice:speech-start` is active, re-enable on `voice:speech-end`. Stops the user from interrupting the agent mid-sentence.
---
-## Step 7 — Sequencing: do A, then B, then C
+## Step 7: Sequencing: do A, then B, then C
A common pitfall: fire `speak` and `play` back-to-back, and they overlap. The second clip steps on the talking gesture and things look broken.
-For LLM turns the clean fix is `ask()` — it resolves only after the reply is complete (including its speech, when `voice` is on), so a plain `await` sequences everything:
+For LLM turns the clean fix is `ask()`: it resolves only after the reply is complete (including its speech, when `voice` is on), so a plain `await` sequences everything:
```js
async function intro() {
@@ -286,9 +286,9 @@ async function intro() {
}
```
-Each line waits for the previous one to land before the next runs. The result feels deliberate — not a stuttering pile-up.
+Each line waits for the previous one to land before the next runs. The result feels deliberate, not a stuttering pile-up.
-For the silent `speak()` gesture there is no completion event — but its duration is deterministic (0.3s per word, minimum 1.5s), so you can mirror it:
+For the silent `speak()` gesture there is no completion event, but its duration is deterministic (0.3s per word, minimum 1.5s), so you can mirror it:
```js
function gestureAndWait(el, text) {
@@ -298,7 +298,7 @@ function gestureAndWait(el, text) {
}
```
-And if you're reacting to real speech (an LLM reply being voiced), `voice:speech-end` is still the event to wait on — it fires when the spoken sentence is done:
+And if you're reacting to real speech (an LLM reply being voiced), `voice:speech-end` is still the event to wait on, it fires when the spoken sentence is done:
```js
function nextSpeechEnd(el) {
@@ -310,7 +310,7 @@ function nextSpeechEnd(el) {
---
-## Step 8 — Error patterns
+## Step 8: Error patterns
The bulk of mistakes fall into three buckets.
@@ -328,9 +328,9 @@ function getAgent() {
}
```
-Or use a small reactive wrapper if you're inside a framework — see the [Web Component end-to-end tutorial](/tutorials/web-component-end-to-end) for React and Vue patterns.
+Or use a small reactive wrapper if you're inside a framework, see the [Web Component end-to-end tutorial](/tutorials/web-component-end-to-end) for React and Vue patterns.
-**LLM errors during a turn.** Network glitch, brain provider rate-limit, no API key. `say()` never rejects — it shows the error in the chat bubble and fires an `agent:error` event. When you need to handle the failure programmatically, use `ask()`, which rejects:
+**LLM errors during a turn.** Network glitch, brain provider rate-limit, no API key. `say()` never rejects, it shows the error in the chat bubble and fires an `agent:error` event. When you need to handle the failure programmatically, use `ask()`, which rejects:
```js
try {
@@ -342,11 +342,11 @@ try {
}
```
-The fallback `agent.speak(...)` does *not* go through the brain (it's a silent gesture), so it works even when the LLM path is broken — pair it with your own on-page error message for the words.
+The fallback `agent.speak(...)` does *not* go through the brain (it's a silent gesture), so it works even when the LLM path is broken, pair it with your own on-page error message for the words.
---
-## Step 9 — The checkout celebration flow
+## Step 9: The checkout celebration flow
Time to put it all together. You run a Shopify store, a Stripe checkout, or any form-driven flow. When a user submits a successful order, you want the agent to celebrate, narrate, and settle back to idle. The whole sequence should run on the success page.
@@ -415,12 +415,12 @@ async function placeOrder({ name, item }) {
A few things this gets right:
- The form submit is intercepted with `preventDefault` so we control the flow.
-- The real network call is awaited before the celebration runs — no fake confetti on a failed order.
+- The real network call is awaited before the celebration runs, no fake confetti on a failed order.
- An explicit error branch speaks an apology if the order didn't go through.
- The celebration sequences animation → speech → animation cleanly, so each beat lands.
- `whenReady` is called even though we expect the agent to already be booted by submit time. Cheap insurance.
-If you also wanted to log the celebration upstream — to your analytics, to a CRM — you'd subscribe to `voice:speech-end` once and fire an event:
+If you also wanted to log the celebration upstream, to your analytics, to a CRM, you'd subscribe to `voice:speech-end` once and fire an event:
```js
agent.addEventListener('voice:speech-end', () => {
@@ -454,6 +454,6 @@ The `whenReady`, awaited-`ask()`, and try/catch patterns are small but they remo
## Next steps
-- [Use the &lt;agent-3d&gt; web component end-to-end](/tutorials/web-component-end-to-end) — same API, in React, Vue, and your component system
-- [Trigger the agent from page events](/tutorials/trigger-from-page-events) — scroll, route changes, idle time, onboarding flows
-- [Give your agent a personality](/tutorials/agent-personality) — write a system prompt that holds across thousands of chats
+- [Use the &lt;agent-3d&gt; web component end-to-end](/tutorials/web-component-end-to-end), same API, in React, Vue, and your component system
+- [Trigger the agent from page events](/tutorials/trigger-from-page-events), scroll, route changes, idle time, onboarding flows
+- [Give your agent a personality](/tutorials/agent-personality), write a system prompt that holds across thousands of chats
diff --git a/docs/tutorials/mint-pumpfun-token.md b/docs/tutorials/mint-pumpfun-token.md
index 843026d48..504168099 100644
--- a/docs/tutorials/mint-pumpfun-token.md
+++ b/docs/tutorials/mint-pumpfun-token.md
@@ -1,8 +1,8 @@
# Mint an Agent Token on Pump.fun
-By the end of this tutorial your agent has a live, tradable token on Solana — bonded to its three.ws identity, indexed by the platform's live mint stream, and discoverable from your agent's profile card. The token is real. The bonding curve is real. The Pump.fun graduation event, if it happens, is real.
+By the end of this tutorial your agent has a live, tradable token on Solana, bonded to its three.ws identity, indexed by the platform's live mint stream, and discoverable from your agent's profile card. The token is real. The bonding curve is real. The Pump.fun graduation event, if it happens, is real.
-This is the canonical path for turning a 3D agent into a community-owned asset. It does not make your agent more capable. It makes your agent **owned** — by its holders, transparently, on a chain anyone can read.
+This is the canonical path for turning a 3D agent into a community-owned asset. It does not make your agent more capable. It makes your agent **owned**, by its holders, transparently, on a chain anyone can read.
**What you'll build:**
@@ -18,22 +18,22 @@ This is the canonical path for turning a 3D agent into a community-owned asset.
- A Solana wallet. Phantom, Solflare, or any wallet that supports Solana mainnet works. Email-based embedded wallets created on three.ws are also acceptable for this flow.
- Approximately **0.05 SOL** in that wallet on Solana mainnet. This covers Pump.fun's mint fee, a small initial dev buy, and rent + transaction fees with a healthy margin for retries.
- A square image (PNG or JPG, 512x512 minimum, under 1 MB) to use as the token icon. Pump.fun uploads it to its CDN and bakes it into the mint metadata.
-- A clear name and ticker symbol you have already verified is available — Step 2 covers how.
+- A clear name and ticker symbol you have already verified is available, Step 2 covers how.
- Familiarity with the fact that **tokens minted on Pump.fun are public, immutable, and economically real**. Read the legal note at the end of this tutorial before launching anything you'd regret.
---
-## Step 1 — Understand what Pump.fun actually is
+## Step 1: Understand what Pump.fun actually is
-Pump.fun is a Solana token launch protocol. Every token launched on Pump.fun starts on a **fair-launch bonding curve** — no presale, no team allocation, no insider rounds. The first buyer pays the lowest price; every subsequent buyer pays slightly more along a deterministic curve. The curve holds the SOL collected on the buy side and the unsold token supply on the sell side. Selling burns the position and returns SOL.
+Pump.fun is a Solana token launch protocol. Every token launched on Pump.fun starts on a **fair-launch bonding curve**, no presale, no team allocation, no insider rounds. The first buyer pays the lowest price; every subsequent buyer pays slightly more along a deterministic curve. The curve holds the SOL collected on the buy side and the unsold token supply on the sell side. Selling burns the position and returns SOL.
There are three states a Pump.fun token can be in:
-1. **Bonding** — the curve is active, trades route through the Pump.fun program, prices follow the curve formula. This is the first life of every token. Almost all activity happens here.
-2. **Graduated** — the curve has accumulated enough SOL (currently around 85 SOL at the time of writing; Pump.fun adjusts this threshold). The protocol burns the remaining curve supply, takes the collected SOL, and seeds a Raydium liquidity pool. From then on the token trades like any other Solana SPL token on the open market.
-3. **Stalled** — the curve never fills. The token continues to trade on the curve indefinitely. No timer. No expiry. It will sit there at whatever price the last trade left it.
+1. **Bonding**: the curve is active, trades route through the Pump.fun program, prices follow the curve formula. This is the first life of every token. Almost all activity happens here.
+2. **Graduated**: the curve has accumulated enough SOL (currently around 85 SOL at the time of writing; Pump.fun adjusts this threshold). The protocol burns the remaining curve supply, takes the collected SOL, and seeds a Raydium liquidity pool. From then on the token trades like any other Solana SPL token on the open market.
+3. **Stalled**: the curve never fills. The token continues to trade on the curve indefinitely. No timer. No expiry. It will sit there at whatever price the last trade left it.
-The vast majority of tokens stall. Graduation is rare. This tutorial assumes the bonding stage is the destination, not a milestone. Building real utility into your agent is what gives the curve a reason to fill — not the launch itself.
+The vast majority of tokens stall. Graduation is rare. This tutorial assumes the bonding stage is the destination, not a milestone. Building real utility into your agent is what gives the curve a reason to fill, not the launch itself.
**Why bond a token to your agent?**
@@ -41,20 +41,20 @@ A few legitimate reasons:
- **Skin in the game for skill authors.** If your agent is monetized via paid skills or x402 endpoints, holders of the token participate in the upside of usage growth. See [paid-x402-endpoint](/tutorials/paid-x402-endpoint).
- **Community ownership.** Anyone can buy. There is no allowlist, no KYC, no permission required. The set of holders becomes a public record on Solana.
-- **A canonical pointer.** The mint address becomes the single canonical identifier for "this agent's token" — useful for treasury tools, voting, or distribution.
+- **A canonical pointer.** The mint address becomes the single canonical identifier for "this agent's token", useful for treasury tools, voting, or distribution.
- **Curiosity-driven distribution.** The three.ws Pump.fun feed surfaces new agent mints in real time, sending eyeballs to your agent page.
None of these justify launching a token if your agent does not yet do anything users want. The launch is the easy part. The token is a wrapper around whatever utility already exists.
---
-## Step 2 — Lock down name, ticker, and image
+## Step 2: Lock down name, ticker, and image
Before the launch dialog opens, decide three things and verify them.
-**Name** — readable, related to your agent. If your agent's name is `Atlas Concierge`, a token name like `Atlas Concierge Token` or `Atlas` is fine. Names are not unique on Pump.fun; collisions are common. Don't fight over a generic name.
+**Name**: readable, related to your agent. If your agent's name is `Atlas Concierge`, a token name like `Atlas Concierge Token` or `Atlas` is fine. Names are not unique on Pump.fun; collisions are common. Don't fight over a generic name.
-**Ticker symbol** — 3 to 10 uppercase letters, ideally 3–5. The ticker is what traders type. `$ATLAS` is good; `$ACAGENTTOKEN` is bad.
+**Ticker symbol**: 3 to 10 uppercase letters, ideally 3-5. The ticker is what traders type. `$ATLAS` is good; `$ACAGENTTOKEN` is bad.
**Symbol availability check.** Pump.fun does not enforce ticker uniqueness, but the three.ws agent registry warns when a ticker is already used by another listed agent. Hit the platform's symbol-availability endpoint from your terminal:
@@ -64,31 +64,31 @@ curl 'https://three.ws/api/x402/symbol-availability?symbol=ATLAS' \
-H 'accept: application/json'
```
-The first call returns a 402 because the endpoint is paid (see [paid-x402-endpoint](/tutorials/paid-x402-endpoint) for the full flow). For a one-off check, the agent dashboard at `https://three.ws/dashboard` runs the same query for free against the cached symbol index — open your agent's settings, the Pump.fun tab includes an inline availability indicator.
+The first call returns a 402 because the endpoint is paid (see [paid-x402-endpoint](/tutorials/paid-x402-endpoint) for the full flow). For a one-off check, the agent dashboard at `https://three.ws/dashboard` runs the same query for free against the cached symbol index, open your agent's settings, the Pump.fun tab includes an inline availability indicator.
-**Image** — a square PNG or JPG, at least 512x512 pixels. This becomes the token's permanent icon on every Solana wallet, explorer, and aggregator. Once minted, you cannot change it. Use a stable, high-contrast asset; avoid text that gets crushed at 24px favicon sizes.
+**Image**: a square PNG or JPG, at least 512x512 pixels. This becomes the token's permanent icon on every Solana wallet, explorer, and aggregator. Once minted, you cannot change it. Use a stable, high-contrast asset; avoid text that gets crushed at 24px favicon sizes.
The image is uploaded to Pump.fun's storage and pinned. The CID is written into the SPL token's metadata account.
---
-## Step 3 — Fund the wallet you'll launch from
+## Step 3: Fund the wallet you'll launch from
Open Phantom (or your wallet of choice). Switch the network to **Solana Mainnet**. Confirm the balance shows at least 0.05 SOL.
If you need to fund the wallet:
-- **From a centralized exchange** — Coinbase, Binance, Kraken, and most others let you withdraw SOL to a Solana address. Confirm you're withdrawing to **Solana mainnet** (not Wormhole-wrapped, not BSC, not Polygon). Withdrawals usually confirm in under a minute.
-- **From another Solana wallet** — standard SPL transfer to your launch wallet's public key.
-- **From a card** — Phantom and Solflare both support on-ramp via MoonPay / Coinbase Pay. Slower and more expensive (3–5% fee) but works in two minutes.
+- **From a centralized exchange**: Coinbase, Binance, Kraken, and most others let you withdraw SOL to a Solana address. Confirm you're withdrawing to **Solana mainnet** (not Wormhole-wrapped, not BSC, not Polygon). Withdrawals usually confirm in under a minute.
+- **From another Solana wallet**: standard SPL transfer to your launch wallet's public key.
+- **From a card**: Phantom and Solflare both support on-ramp via MoonPay / Coinbase Pay. Slower and more expensive (3-5% fee) but works in two minutes.
-Pump.fun charges a flat **0.02 SOL creation fee** plus a small Solana rent allocation (~0.003 SOL). The dev buy is optional but recommended — see Step 5. Reserve 0.005 SOL on top for transaction signing buffer.
+Pump.fun charges a flat **0.02 SOL creation fee** plus a small Solana rent allocation (~0.003 SOL). The dev buy is optional but recommended, see Step 5. Reserve 0.005 SOL on top for transaction signing buffer.
Once funded, **double-check the wallet's public key** matches the wallet you plan to connect to three.ws. The mint will be authored by whichever wallet signs the launch transaction. If that wallet is different from the one that owns your three.ws account, bonding the mint to the agent in Step 7 requires an extra signature linking the two.
---
-## Step 4 — Open the Pump.fun launch flow on three.ws
+## Step 4: Open the Pump.fun launch flow on three.ws
Navigate to:
@@ -96,17 +96,17 @@ Navigate to:
https://three.ws/pumpfun
```
-This is the live Pump.fun feed. It shows every Pump.fun mint on Solana mainnet in real time, plus a separate ribbon for agent-bonded mints originating from three.ws agents. Watch the feed for thirty seconds — you will see new tokens scroll past every few seconds. Most are noise. The ribbon at the top is where your token will appear after launch.
+This is the live Pump.fun feed. It shows every Pump.fun mint on Solana mainnet in real time, plus a separate ribbon for agent-bonded mints originating from three.ws agents. Watch the feed for thirty seconds, you will see new tokens scroll past every few seconds. Most are noise. The ribbon at the top is where your token will appear after launch.
In the upper right of that page is a button **Launch your agent's token**. Click it.
-You can also reach the same launch dialog from your dashboard at `https://three.ws/dashboard` — pick an agent, open its detail panel, and click **Mint Pump.fun token** on the right-side action rail. Both paths open the same modal.
+You can also reach the same launch dialog from your dashboard at `https://three.ws/dashboard`, pick an agent, open its detail panel, and click **Mint Pump.fun token** on the right-side action rail. Both paths open the same modal.
---
-## Step 5 — Fill in the launch form
+## Step 5: Fill in the launch form
-The launch modal has six fields. Fill them in deliberately — once the mint transaction confirms, none of them can be changed.
+The launch modal has six fields. Fill them in deliberately, once the mint transaction confirms, none of them can be changed.
**1. Agent.** A dropdown of your saved agents. Pick the one you want to bond the token to. The agent's name, avatar, and on-chain ID (if registered) appear in the preview pane on the right.
@@ -118,7 +118,7 @@ The launch modal has six fields. Fill them in deliberately — once the mint tra
**5. Description.** A 280-character bio that gets written into Pump.fun's token page. Treat this like a tweet. State what the agent does and link to its three.ws page if it has a public profile.
-**6. Initial dev buy (optional).** A small SOL amount the form will use to immediately buy your own token after the mint succeeds. Setting this to **0.01–0.05 SOL** is conventional. Two reasons it helps:
+**6. Initial dev buy (optional).** A small SOL amount the form will use to immediately buy your own token after the mint succeeds. Setting this to **0.01-0.05 SOL** is conventional. Two reasons it helps:
- It sets a non-zero floor on the curve. A token with a zero-buy initial state looks abandoned in the feed and is easier to ignore.
- It registers you as a holder. Some downstream tools (treasury dashboards, holder leaderboards) treat zero-balance creators differently from non-zero-balance creators.
@@ -129,9 +129,9 @@ When everything looks right, click **Continue**.
---
-## Step 6 — Sign the mint transaction
+## Step 6: Sign the mint transaction
-Phantom (or your connected wallet) pops a transaction prompt. It will be a complex transaction with multiple instructions — at minimum:
+Phantom (or your connected wallet) pops a transaction prompt. It will be a complex transaction with multiple instructions, at minimum:
1. Create the SPL mint account
2. Initialize the Metaplex metadata account
@@ -139,16 +139,16 @@ Phantom (or your connected wallet) pops a transaction prompt. It will be a compl
4. Initialize the curve with the protocol's defaults
5. If you set a dev buy: a buy instruction against the just-created curve
-Phantom shows estimated SOL changes (negative — leaving your wallet) and the program IDs being invoked. The two you should expect to see are:
+Phantom shows estimated SOL changes (negative: leaving your wallet) and the program IDs being invoked. The two you should expect to see are:
- The Pump.fun program (a Solana mainnet program well-known to wallets; Phantom usually labels it)
- The Metaplex Token Metadata program
Confirm. The transaction signs and broadcasts. Pump.fun's program rents the mint account, initializes the curve, and returns the new mint address.
-Confirmation on Solana mainnet typically lands in 5–10 seconds at the current slot time. The launch modal flips to a success state and displays:
+Confirmation on Solana mainnet typically lands in 5-10 seconds at the current slot time. The launch modal flips to a success state and displays:
-- The **mint address** (a base58 public key, 43–44 chars)
+- The **mint address** (a base58 public key, 43-44 chars)
- A link to **pump.fun** for the new token page
- A link to **Solscan** for the mint account
- A button **Bond this mint to your agent on three.ws**
@@ -157,13 +157,13 @@ Copy the mint address. You'll want it.
---
-## Step 7 — Bond the mint into the agent manifest
+## Step 7: Bond the mint into the agent manifest
This is the step that makes the token *your agent's* token rather than a free-floating SPL mint that happens to share a name. Bonding writes the mint address into your agent's manifest under a `tokens.pumpfun` entry.
Click **Bond this mint to your agent**.
-If the wallet that signed the mint matches the wallet on your three.ws account, the modal writes the manifest server-side immediately. The agent's manifest is re-pinned and (if the agent is registered on-chain via ERC-8004) you'll be prompted to also update its on-chain `tokenURI` — see [register-onchain](/tutorials/register-onchain) for the registration mechanics.
+If the wallet that signed the mint matches the wallet on your three.ws account, the modal writes the manifest server-side immediately. The agent's manifest is re-pinned and (if the agent is registered on-chain via ERC-8004) you'll be prompted to also update its on-chain `tokenURI`, see [register-onchain](/tutorials/register-onchain) for the registration mechanics.
If the launching wallet is **different** from your three.ws account wallet (common when you launch from a hot wallet but the agent was created under your hardware wallet, for example), the modal asks for a **link signature**: a short SIWS (Sign-In With Solana) signature from the launching wallet proving you control the mint authority. Approve the signature in Phantom. The link costs no gas.
@@ -195,9 +195,9 @@ The `graduated` field is updated automatically by a cron job that polls the bond
---
-## Step 8 — Verify the listing in the feed
+## Step 8: Verify the listing in the feed
-Open `https://three.ws/pumpfun` again. Your token should appear in the **Agent-bonded** ribbon within thirty seconds — the feed is driven by a Helius webhook on the Pump.fun program plus a server-side filter that joins against bonded mints.
+Open `https://three.ws/pumpfun` again. Your token should appear in the **Agent-bonded** ribbon within thirty seconds, the feed is driven by a Helius webhook on the Pump.fun program plus a server-side filter that joins against bonded mints.
Click your token. The detail panel shows:
@@ -221,28 +221,28 @@ This is the same data surfaced on the per-agent dashboard at:
https://three.ws/pump-dashboard.html?agent=<your-agent-id>
```
-Open that page too. The pump-dashboard is the operator view — it shows aggregate trade volume, holder distribution (top holders, concentration warnings), and a chart of price + curve fill over time. Bookmark it.
+Open that page too. The pump-dashboard is the operator view, it shows aggregate trade volume, holder distribution (top holders, concentration warnings), and a chart of price + curve fill over time. Bookmark it.
---
-## Step 9 — Tell people the token exists
+## Step 9: Tell people the token exists
A token that nobody knows about does nothing. The launch is not the announcement.
A reasonable sequence on launch day:
1. **Update the agent's public card.** The three.ws agent page already shows the Pump.fun panel after bonding, but check it in an incognito tab to confirm.
-2. **Post the agent URL** (not the bare Pump.fun URL — the agent URL frames it correctly). Example: "Just bonded a token to my agent. mint and chart on the page → `https://three.ws/a/<chain>/<agentId>`".
+2. **Post the agent URL** (not the bare Pump.fun URL, the agent URL frames it correctly). Example: "Just bonded a token to my agent. mint and chart on the page → `https://three.ws/a/<chain>/<agentId>`".
3. **Cross-post the Pump.fun link.** Some communities prefer the raw pump.fun page. Both are valid.
4. **Pin the post.** Make it findable.
-The three.ws feed handles in-platform discovery automatically — there's nothing extra to do to appear in the agent-bonded ribbon. External discovery (Twitter, Telegram, Farcaster) is on you.
+The three.ws feed handles in-platform discovery automatically, there's nothing extra to do to appear in the agent-bonded ribbon. External discovery (Twitter, Telegram, Farcaster) is on you.
What not to do: brigade groupchats begging for buys. Tokens that ride this pattern reliably stall and burn the creator's reputation.
---
-## Step 10 — What graduation actually means
+## Step 10: What graduation actually means
A Pump.fun token graduates when the bonding curve accumulates the protocol's graduation threshold of collected SOL. At that moment, atomically:
@@ -257,22 +257,22 @@ The Pump.fun page for the token flips to a **Graduated** state and points to the
---
-## Step 11 — Operate the token, don't promote it
+## Step 11: Operate the token, don't promote it
The most useful thing you can do with a bonded agent token is make the agent more valuable. Concretely:
- Ship more skills. Each new skill is a reason for an existing holder to keep holding and a new user to discover the agent. See [custom-skill](/tutorials/custom-skill) and [skill-with-database-auth](/tutorials/skill-with-database-auth).
- Add a paid x402 endpoint that your agent calls and that you charge for. Revenue accrues to the operator wallet. See [paid-x402-endpoint](/tutorials/paid-x402-endpoint).
- Register the agent on-chain via ERC-8004 so the token's holders have a verifiable identity to anchor reputation to. See [register-onchain](/tutorials/register-onchain).
-- Surface the agent in more places. Embed it on your own site at a real domain — see [deploy-to-vercel-custom-domain](/tutorials/deploy-to-vercel-custom-domain).
+- Surface the agent in more places. Embed it on your own site at a real domain, see [deploy-to-vercel-custom-domain](/tutorials/deploy-to-vercel-custom-domain).
The token will follow the utility, not the other way around. A creator who keeps the agent improving keeps the holders interested.
---
-## Step 12 — Reading the bonding curve programmatically
+## Step 12: Reading the bonding curve programmatically
-If you want to build something on top of your token — a trading bot, a holder-gated chat, an automated buyback funded by skill revenue — you'll need to read the curve state directly.
+If you want to build something on top of your token, a trading bot, a holder-gated chat, an automated buyback funded by skill revenue, you'll need to read the curve state directly.
The three.ws API exposes a normalized view of any bonded curve at:
@@ -302,11 +302,11 @@ The response includes the curve account's raw fields plus computed helpers:
`graduationProgress` is a float between 0 and 1; multiply by 100 for a percentage. `complete` flips to `true` after graduation and stays there. For a holder count, hit `https://three.ws/api/pump/dashboard?agent=<agentId>`.
-If you need raw on-chain reads, point any Solana RPC client (Helius, Triton, or the public mainnet RPC for low-volume use) at the Pump.fun program ID and decode the bonding curve account with the program's published IDL. The three.ws endpoint is just a normalized, rate-limit-friendly convenience layer over that same on-chain data — every field is derivable yourself if you don't want to depend on the platform.
+If you need raw on-chain reads, point any Solana RPC client (Helius, Triton, or the public mainnet RPC for low-volume use) at the Pump.fun program ID and decode the bonding curve account with the program's published IDL. The three.ws endpoint is just a normalized, rate-limit-friendly convenience layer over that same on-chain data, every field is derivable yourself if you don't want to depend on the platform.
---
-## Step 13 — Sell pressure, doxx pressure, and other things to be ready for
+## Step 13: Sell pressure, doxx pressure, and other things to be ready for
A few realities of operating a public token, in roughly the order you'll encounter them:
@@ -314,7 +314,7 @@ A few realities of operating a public token, in roughly the order you'll encount
**Concentration.** If a single wallet holds more than ~5% of the supply, watch it. The pump-dashboard surfaces top holders. If the concentration moves into worrying territory, decide whether to do anything about it (typically: nothing).
-**Impersonation.** Other creators may mint tokens with your agent's name or ticker. Pump.fun does not enforce uniqueness. Your agent's three.ws card is the canonical link — point people there.
+**Impersonation.** Other creators may mint tokens with your agent's name or ticker. Pump.fun does not enforce uniqueness. Your agent's three.ws card is the canonical link, point people there.
**Telegram/Discord requests for "calls."** Trading communities will ask you to coordinate buys. Don't. It is securities-promotion-adjacent in many jurisdictions, and it produces short-lived spikes followed by long drawdowns.
@@ -324,14 +324,14 @@ A few realities of operating a public token, in roughly the order you'll encount
## Legal note (read this)
-Pump.fun tokens trade on a permissionless protocol. Once launched, the token exists, anyone can buy or sell it, and nobody — including you, Pump.fun, or three.ws — can pause it, reverse trades, or recall supply. The platform is a launchpad, not a gatekeeper.
+Pump.fun tokens trade on a permissionless protocol. Once launched, the token exists, anyone can buy or sell it, and nobody, including you, Pump.fun, or three.ws, can pause it, reverse trades, or recall supply. The platform is a launchpad, not a gatekeeper.
Some practical implications:
- **You are responsible for what you launch.** Three.ws does not vet token names, descriptions, or claims attached to a bonded mint. If you launch a token impersonating someone, promising returns, or otherwise breaking the law of your jurisdiction, that is on you.
- **Tokens are not securities offerings by us.** Three.ws is software that integrates with the Pump.fun protocol. We do not custody, broker, or guarantee anything about any token launched through that integration. The same is true of the Pump.fun protocol itself.
- **Some jurisdictions restrict promotion.** Even talking about "buying $TICKER" online, in some jurisdictions, can be regulated. Especially if you are paid to do so. Read the rules where you live.
-- **Reversibility is zero.** A typo in the ticker is permanent. A wrong image is permanent. The mint authority is, by default, retained by the creator wallet and can be renounced — many creators renounce immediately to signal they cannot mint more supply. Renouncing is irreversible.
+- **Reversibility is zero.** A typo in the ticker is permanent. A wrong image is permanent. The mint authority is, by default, retained by the creator wallet and can be renounced, many creators renounce immediately to signal they cannot mint more supply. Renouncing is irreversible.
If you have a lawyer, talk to them before launching. If you don't, default to the conservative interpretation: launch a token only if your agent is providing genuine, ongoing utility, and only if you're comfortable with all of the above being permanent and public.
@@ -344,11 +344,11 @@ If you have a lawyer, talk to them before launching. If you don't, default to th
- How the bonded mint surfaces in the live feed, the agent's public card, and the dashboard
- How to read curve state programmatically via `https://three.ws/api/pump/curve`
- The operational realities of owning a public, irreversible, permissionless token
-- The legal posture you should adopt — not legal advice, but a reasonable default
+- The legal posture you should adopt: not legal advice, but a reasonable default
## Next steps
-- Register the agent on-chain so the token has a verified identity anchor — [register-onchain](/tutorials/register-onchain).
-- Add a paid x402 endpoint and route revenue to the token's operator wallet — [paid-x402-endpoint](/tutorials/paid-x402-endpoint).
-- Build a database-backed skill that uses the token as an access gate — [skill-with-database-auth](/tutorials/skill-with-database-auth).
-- Coordinate the agent with a second one for richer interactions — [multi-agent-coordination](/tutorials/multi-agent-coordination).
+- Register the agent on-chain so the token has a verified identity anchor, [register-onchain](/tutorials/register-onchain).
+- Add a paid x402 endpoint and route revenue to the token's operator wallet, [paid-x402-endpoint](/tutorials/paid-x402-endpoint).
+- Build a database-backed skill that uses the token as an access gate, [skill-with-database-auth](/tutorials/skill-with-database-auth).
+- Coordinate the agent with a second one for richer interactions, [multi-agent-coordination](/tutorials/multi-agent-coordination).
diff --git a/docs/tutorials/upload-custom-glb.md b/docs/tutorials/upload-custom-glb.md
index f5f0101c9..efa0a7cdc 100644
--- a/docs/tutorials/upload-custom-glb.md
+++ b/docs/tutorials/upload-custom-glb.md
@@ -1,6 +1,6 @@
# Upload a custom GLB avatar
-The sample avatar is fine for learning, but at some point you want your agent to look like *yours* — a brand mascot, a stylised version of you, a museum guide in period dress, a character your designer built in Blender. That means uploading a custom GLB.
+The sample avatar is fine for learning, but at some point you want your agent to look like *yours*, a brand mascot, a stylised version of you, a museum guide in period dress, a character your designer built in Blender. That means uploading a custom GLB.
This tutorial covers the whole pipeline. Where compatible GLBs come from, what makes one compatible (and what makes one quietly fail), how to validate before you upload, what the validator output actually tells you, and how to fix the four or five problems that account for almost every upload failure. We'll end-to-end a Mixamo character, the most reliable starting point.
@@ -14,29 +14,29 @@ This tutorial covers the whole pipeline. Where compatible GLBs come from, what m
---
-## Step 1 — Understand what the runtime expects
+## Step 1: Understand what the runtime expects
-A GLB is just a binary glTF — a 3D scene packaged in a single file. The runtime accepts any valid glTF 2.0 GLB. To function as a *conversational agent body*, the one thing that really matters on top of the basic geometry is:
+A GLB is just a binary glTF: a 3D scene packaged in a single file. The runtime accepts any valid glTF 2.0 GLB. To function as a *conversational agent body*, the one thing that really matters on top of the basic geometry is:
-**A humanoid skeleton (armature) the runtime can name-map.** Bones following a humanoid pattern — head, neck, spine, two arms, two legs. There is no rig allowlist: `src/glb-canonicalize.js` maps the common conventions (Mixamo, Avaturn, Unreal, VRM/VRoid, VRM 1.0, Daz/Genesis, MakeHuman, Blender `.L` suffixes, simple `shoulderL` rigs) onto one canonical bone set.
+**A humanoid skeleton (armature) the runtime can name-map.** Bones following a humanoid pattern, head, neck, spine, two arms, two legs. There is no rig allowlist: `src/glb-canonicalize.js` maps the common conventions (Mixamo, Avaturn, Unreal, VRM/VRoid, VRM 1.0, Daz/Genesis, MakeHuman, Blender `.L` suffixes, simple `shoulderL` rigs) onto one canonical bone set.
-**You do not have to ship animation clips.** Once the skeleton canonicalizes, `src/animation-retarget.js` retargets the platform's pre-baked clip library (idle, walk, and the emotes) onto your rig, legs included. A rig that genuinely can't be skeleton-driven — no skin, a non-humanoid prop — falls back to the default rig rather than freezing. And if only *some* bones name-map, `relaxUndrivenArms()` swings the un-driven arms down to a relaxed rest, so an avatar never reads as a broken bind-pose T-pose.
+**You do not have to ship animation clips.** Once the skeleton canonicalizes, `src/animation-retarget.js` retargets the platform's pre-baked clip library (idle, walk, and the emotes) onto your rig, legs included. A rig that genuinely can't be skeleton-driven, no skin, a non-humanoid prop, falls back to the default rig rather than freezing. And if only *some* bones name-map, `relaxUndrivenArms()` swings the un-driven arms down to a relaxed rest, so an avatar never reads as a broken bind-pose T-pose.
-Baking your own clips in is therefore an *upgrade*, not a requirement. Do it when you want motion the shared library doesn't have — a brand-specific gesture, a costume-driven idle. Clips are matched by a case-insensitive substring search on the clip name, so `idle`, `idle_loop`, and `IdleBreathing` all satisfy an "idle" lookup; `talk`, `yes`, and `wave` all match the talk-style hint.
+Baking your own clips in is therefore an *upgrade*, not a requirement. Do it when you want motion the shared library doesn't have, a brand-specific gesture, a costume-driven idle. Clips are matched by a case-insensitive substring search on the clip name, so `idle`, `idle_loop`, and `IdleBreathing` all satisfy an "idle" lookup; `talk`, `yes`, and `wave` all match the talk-style hint.
Beyond the rig, a great avatar has:
- A wave clip (`wave`, `WaveLoop`, etc.) for greetings
- Emote clips (`celebrate`, `cheer`, `flinch`, `concern`) for product moments
-- Sensible material setup — PBR (`pbrMetallicRoughness`) materials, no unsupported extensions
-- Textures sized for the web — 1024×1024 or 2048×2048 at most, JPEG or WebP rather than PNG where possible
+- Sensible material setup: PBR (`pbrMetallicRoughness`) materials, no unsupported extensions
+- Textures sized for the web: 1024×1024 or 2048×2048 at most, JPEG or WebP rather than PNG where possible
- Compressed geometry, bringing the file under ~10 MB
If it lacks the niceties, it works but feels heavy and pops in slowly on mobile.
---
-## Step 2 — Where compatible GLBs come from
+## Step 2: Where compatible GLBs come from
Four reliable sources, ranked by how much work they need from you.
@@ -50,7 +50,7 @@ Workflow:
2. Click **Characters**, pick one.
3. Click **Animations**, find an "idle", a "talk" (search for "talking"), a "wave", and any emotes you want.
4. For each animation, click **Download**. Format: **FBX for Unity**. Skin: **With Skin** for the first download (the character), **Without Skin** for every subsequent one (you're just downloading the motion).
-5. Convert the FBXs to a single GLB with a tool — see Step 4.
+5. Convert the FBXs to a single GLB with a tool: see Step 4.
Mixamo characters work *out of the box* with the runtime. This is the recommended path if you don't already have a model.
@@ -62,7 +62,7 @@ Workflow:
1. Open [Avatar Studio](https://three.ws/avatar-studio).
2. Customise your avatar and click **Save Avatar**.
-3. The GLB has the body and skin but no bespoke animation clips baked in. You don't have to add any: the platform retargets its pre-baked idle/walk/emote library onto any humanoid rig it can canonicalize, so a Studio avatar animates as soon as it is on an agent. Bake your own clips into the file only when you want motion the library doesn't have — Step 4 covers merging clips in.
+3. The GLB has the body and skin but no bespoke animation clips baked in. You don't have to add any: the platform retargets its pre-baked idle/walk/emote library onto any humanoid rig it can canonicalize, so a Studio avatar animates as soon as it is on an agent. Bake your own clips into the file only when you want motion the library doesn't have, Step 4 covers merging clips in.
### Photo-to-avatar
@@ -73,17 +73,17 @@ The three.ws photo pipeline generates a realistic humanoid avatar from three fac
If you have a model you built or commissioned in Blender:
1. Make sure your armature is a Mixamo-style humanoid rig, or rename your bones to match (`mixamorigHead`, `mixamorigSpine`, etc.).
-2. Bake your animations down into NLA strips with sensible names — `Idle`, `Talk`, `Wave`.
+2. Bake your animations down into NLA strips with sensible names, `Idle`, `Talk`, `Wave`.
3. Export as glTF 2.0 (Binary) (`.glb`).
4. In the export dialog, check **Include → Selected Objects** if you only want the character, **Animation → Always Sample Animations**, and **Compression → Draco mesh compression**.
-Blender exports are the most flexible path but also the most error-prone — most upload failures we see in the wild come from Blender exports with missing or misconfigured animation tracks.
+Blender exports are the most flexible path but also the most error-prone, most upload failures we see in the wild come from Blender exports with missing or misconfigured animation tracks.
---
-## Step 3 — Run the validator before you upload
+## Step 3: Run the validator before you upload
-The single best habit you can build is validating *every* GLB before upload. The validator at [three.ws/validation](https://three.ws/validation) wraps the official Khronos glTF Validator with additional runtime-specific checks — does the file have an idle clip, is the skeleton humanoid, are the materials supported.
+The single best habit you can build is validating *every* GLB before upload. The validator at [three.ws/validation](https://three.ws/validation) wraps the official Khronos glTF Validator with additional runtime-specific checks, does the file have an idle clip, is the skeleton humanoid, are the materials supported.
Workflow:
@@ -108,11 +108,11 @@ If there are errors, they almost always fall into the four buckets in Step 4.
---
-## Step 4 — Convert Mixamo FBX to GLB
+## Step 4: Convert Mixamo FBX to GLB
Mixamo's "Download" button gives you FBX. The runtime wants GLB. The conversion is a one-line command.
-If you're working inside the repo, use the built-in converter — it's backed by FBX2glTF and preserves the skeleton, skin weights, animation, and textures, then prints a summary so you can confirm the rig survived:
+If you're working inside the repo, use the built-in converter, it's backed by FBX2glTF and preserves the skeleton, skin weights, animation, and textures, then prints a summary so you can confirm the rig survived:
```bash
# One character FBX with its baked-in animation → public/avatars/<name>.glb:
@@ -122,7 +122,7 @@ npm run convert:fbx -- your-character.fbx
npm run optimize:glb -- public/avatars/your-character.glb
```
-> **`optimize:glb` uses WebP, not Draco.** The avatar runtime *does* decode Draco — the viewer and the avatar body loaders wire a `DRACOLoader` pointed at the vendored `/three/draco/` decoder, so a Draco-compressed GLB loads fine (that's Step 5). `optimize:glb` itself deliberately stays within plain glTF 2.0 and leans on WebP textures for its ~90% size win, so its output needs no decoder at all. See [docs/3d-asset-pipeline.md](../3d-asset-pipeline.md) for the full format and pipeline reference.
+> **`optimize:glb` uses WebP, not Draco.** The avatar runtime *does* decode Draco, the viewer and the avatar body loaders wire a `DRACOLoader` pointed at the vendored `/three/draco/` decoder, so a Draco-compressed GLB loads fine (that's Step 5). `optimize:glb` itself deliberately stays within plain glTF 2.0 and leans on WebP textures for its ~90% size win, so its output needs no decoder at all. See [docs/3d-asset-pipeline.md](../3d-asset-pipeline.md) for the full format and pipeline reference.
Outside the repo, install the same converter directly. [FBX2glTF](https://github.com/facebookincubator/FBX2glTF) (Meta's converter) ships as a prebuilt binary inside the `fbx2gltf` npm package, and it is exactly what `npm run convert:fbx` wraps:
@@ -130,10 +130,10 @@ Outside the repo, install the same converter directly. [FBX2glTF](https://github
npm i -D fbx2gltf
```
-The package exports a function, not a CLI shim — there is no `npx fbx2gltf`. Call it from a small script:
+The package exports a function, not a CLI shim: there is no `npx fbx2gltf`. Call it from a small script:
```js
-// convert.mjs — node convert.mjs your-character.fbx your-character.glb
+// convert.mjs: node convert.mjs your-character.fbx your-character.glb
import { createRequire } from 'node:module';
import { renameSync } from 'node:fs';
@@ -149,7 +149,7 @@ console.log(`wrote ${output}`);
PBR metallic-roughness materials, the skeleton, skin weights, animation clips, and textures all survive the conversion. If you would rather drive the binary straight from a shell, it is at `node_modules/fbx2gltf/bin/<Darwin|Linux|Windows_NT>/FBX2glTF`; run it with `--help` to see the flags (note that its `-o` takes a path *without* a suffix, which is why the wrapper above normalizes the result).
-> **`gltf-transform` cannot read FBX.** It is a glTF-to-glTF toolkit — every command it exposes takes a `.glb`/`.gltf` in and writes one out, so there is no `fbx2glb`. Use it for the *optimization* steps below, after FBX2glTF has produced a GLB. It also has no `rename` and no `script` subcommand; renaming clips is a Blender or Document-API job (below).
+> **`gltf-transform` cannot read FBX.** It is a glTF-to-glTF toolkit, every command it exposes takes a `.glb`/`.gltf` in and writes one out, so there is no `fbx2glb`. Use it for the *optimization* steps below, after FBX2glTF has produced a GLB. It also has no `rename` and no `script` subcommand; renaming clips is a Blender or Document-API job (below).
If you downloaded several animations separately (idle, talk, wave as standalone FBXs), convert each with the script above and merge them into a single GLB:
@@ -158,13 +158,13 @@ If you downloaded several animations separately (idle, talk, wave as standalone
npx @gltf-transform/cli@latest merge your-character.glb idle.glb talk.glb wave.glb out.glb
```
-Then rename the clips. Mixamo names every clip `mixamo.com` by default, which is useless for the runtime's name-based hint matching. Set deliberate names — `Idle`, `Talk`, `Wave`, `Celebrate` — so `playAnimationByHint('idle')` and friends find the right clip. Two ways:
+Then rename the clips. Mixamo names every clip `mixamo.com` by default, which is useless for the runtime's name-based hint matching. Set deliberate names, `Idle`, `Talk`, `Wave`, `Celebrate`, so `playAnimationByHint('idle')` and friends find the right clip. Two ways:
- **Blender (no code):** open the merged GLB, rename each action in the NLA editor, re-export. This is the faster path for a handful of clips.
- **The glTF Transform Document API (scriptable):** the library is a normal npm package, so write a tiny Node script against it. There is no CLI subcommand for this.
```js
-// rename-clips.mjs — node rename-clips.mjs merged.glb renamed.glb
+// rename-clips.mjs: node rename-clips.mjs merged.glb renamed.glb
import { NodeIO } from '@gltf-transform/core';
import { ALL_EXTENSIONS } from '@gltf-transform/extensions';
import { MeshoptDecoder, MeshoptEncoder } from 'meshoptimizer';
@@ -190,11 +190,11 @@ Install its three dependencies first: `npm i -D @gltf-transform/core @gltf-trans
---
-## Step 5 — Draco-compress the file
+## Step 5: Draco-compress the file
-Draco is a mesh-compression format that shrinks vertex data by 5–10x with no visible quality loss. A 14 MB raw GLB drops to 2 MB compressed, which is the difference between a 6-second mobile load and an instant one.
+Draco is a mesh-compression format that shrinks vertex data by 5-10x with no visible quality loss. A 14 MB raw GLB drops to 2 MB compressed, which is the difference between a 6-second mobile load and an instant one.
-The runtime ships with the Draco decoder baked in, so compressed GLBs load transparently — no special attributes or flags needed on the agent side.
+The runtime ships with the Draco decoder baked in, so compressed GLBs load transparently, no special attributes or flags needed on the agent side.
To compress:
@@ -202,7 +202,7 @@ To compress:
npx @gltf-transform/cli@latest draco --quantize-position 14 your.glb your-draco.glb
```
-Quantization is per-attribute, not one global flag: `--quantize-position` (default 14), `--quantize-normal` (10), `--quantize-texcoord` (12), `--quantize-color` (8), and `--quantize-generic` (12), each accepting 1-16 bits. The defaults are fine for almost all humanoid avatars, so the command above is really just being explicit. If you see visible warping in the mesh after compression, raise `--quantize-position` to 16, which is the ceiling — there is nothing above it.
+Quantization is per-attribute, not one global flag: `--quantize-position` (default 14), `--quantize-normal` (10), `--quantize-texcoord` (12), `--quantize-color` (8), and `--quantize-generic` (12), each accepting 1-16 bits. The defaults are fine for almost all humanoid avatars, so the command above is really just being explicit. If you see visible warping in the mesh after compression, raise `--quantize-position` to 16, which is the ceiling, there is nothing above it.
Compare before/after sizes:
@@ -214,7 +214,7 @@ A 12 MB → 2 MB drop is typical for a Mixamo character with three animation cli
---
-## Step 6 — Resize textures
+## Step 6: Resize textures
The biggest GLBs we see in production are 90% textures. A character with three 4K textures (diffuse, normal, ARM) is 50 MB before you've added a single bone.
@@ -226,13 +226,13 @@ npx @gltf-transform/cli@latest resize --width 1024 --height 1024 your.glb your-1
The careful way: open the GLB in [three.ws/validation](https://three.ws/validation), find the largest textures in the report, and resize *just* those in an image editor before repackaging. For faces and skin, keep the diffuse at 2K and downsample the normal/roughness maps to 1K.
-For most product-page avatars, 1K diffuse textures are plenty. The avatar is rendered at 280–400px on screen; 2K texels mostly average out before they hit a pixel.
+For most product-page avatars, 1K diffuse textures are plenty. The avatar is rendered at 280-400px on screen; 2K texels mostly average out before they hit a pixel.
JPEG and WebP are dramatically smaller than PNG for diffuse and ARM maps. PNG is only worth keeping for normal maps where banding shows up otherwise.
---
-## Step 7 — Upload via the dashboard
+## Step 7: Upload via the dashboard
With a validated, compressed GLB in hand, this is two steps: get the file into your avatar library, then point an agent at it.
@@ -251,11 +251,11 @@ With a validated, compressed GLB in hand, this is two steps: get the file into y
The platform stores the GLB on its CDN with the right CORS headers and `Cache-Control` for fast subsequent loads. No further hosting steps needed.
-Once the body is saved, every embed of that agent — `<agent-3d agent-id="...">`, script-tag embeds, iframe widgets — picks up the new body on next page load. No code changes anywhere.
+Once the body is saved, every embed of that agent, `<agent-3d agent-id="...">`, script-tag embeds, iframe widgets, picks up the new body on next page load. No code changes anywhere.
---
-## Step 8 — The five failure modes (and fixes)
+## Step 8: The five failure modes (and fixes)
Almost every upload failure falls into one of these categories. The validator catches them, but knowing what each one means cuts your debug time dramatically.
@@ -268,9 +268,9 @@ Almost every upload failure falls into one of these categories. The validator ca
1. **The skeleton didn't canonicalize.** The retargeting layer couldn't name-map the rig, so the shared clip library has nothing to drive. This is the real failure, and it shows in the validator as a non-humanoid skeleton.
2. **You baked in clips but named them badly.** If the GLB ships its own clips, the runtime prefers them and searches case-insensitively for `idle` in the names. `mixamo.com` matches nothing.
-**Fix for (1):** rename the bones to a convention `glb-canonicalize.js` knows — Mixamo (`mixamorigHead`), VRM, Avaturn, Unreal, Daz, MakeHuman, or Blender `.L`/`.R` suffixes. Hitting a genuinely new skeleton convention is a gap worth reporting rather than working around.
+**Fix for (1):** rename the bones to a convention `glb-canonicalize.js` knows, Mixamo (`mixamorigHead`), VRM, Avaturn, Unreal, Daz, MakeHuman, or Blender `.L`/`.R` suffixes. Hitting a genuinely new skeleton convention is a gap worth reporting rather than working around.
-**Fix for (2):** rename your idle clip to include "idle" — `Idle`, `idle_loop`, `IdleBreathing` all match. Use Blender's NLA editor or the `rename-clips.mjs` script from Step 4; `gltf-transform` has no `rename` command.
+**Fix for (2):** rename your idle clip to include "idle", `Idle`, `idle_loop`, `IdleBreathing` all match. Use Blender's NLA editor or the `rename-clips.mjs` script from Step 4; `gltf-transform` has no `rename` command.
### Failure B: Animation plays but the mesh deforms wrong
@@ -292,7 +292,7 @@ But genuinely broken skinning needs a fresh export.
**Symptom:** Avatar loads, but everything is matte grey or unnaturally bright.
-**Cause:** Unsupported material extension. The most common culprits are `KHR_materials_pbrSpecularGlossiness` (the old material spec — runtime falls back to default PBR), or `KHR_materials_volume` / `KHR_materials_transmission` (advanced extensions some loaders skip).
+**Cause:** Unsupported material extension. The most common culprits are `KHR_materials_pbrSpecularGlossiness` (the old material spec, runtime falls back to default PBR), or `KHR_materials_volume` / `KHR_materials_transmission` (advanced extensions some loaders skip).
**Fix:** Convert the materials to standard PBR (`pbrMetallicRoughness`). In Blender, swap any "Specular BSDF" or "Glass BSDF" nodes for "Principled BSDF" and re-export. In `gltf-transform`:
@@ -304,11 +304,11 @@ This converts `pbrSpecularGlossiness` materials to `pbrMetallicRoughness` automa
### Failure D: File too large, slow to load
-**Symptom:** Avatar loads, but takes 5–15 seconds to appear, especially on mobile. Initial page paint is fine; the avatar pops in late.
+**Symptom:** Avatar loads, but takes 5-15 seconds to appear, especially on mobile. Initial page paint is fine; the avatar pops in late.
**Cause:** Uncompressed mesh, oversized textures, or both.
-**Fix:** Apply Steps 5 and 6 — Draco compression and texture resizing. A combined `transform` invocation does both in one pass:
+**Fix:** Apply Steps 5 and 6: Draco compression and texture resizing. A combined `transform` invocation does both in one pass:
```bash
npx @gltf-transform/cli@latest optimize \
@@ -318,7 +318,7 @@ npx @gltf-transform/cli@latest optimize \
your.glb optimized.glb
```
-The `optimize` command bundles geometry compression, texture resize, image format change, and mesh simplification. Note its default compression is **meshopt**, not Draco: pass `--compress draco` if you specifically want Draco (or `--compress quantize`, or `false` to skip it). For aggressive size reduction it usually drops a 15 MB GLB to 2–3 MB.
+The `optimize` command bundles geometry compression, texture resize, image format change, and mesh simplification. Note its default compression is **meshopt**, not Draco: pass `--compress draco` if you specifically want Draco (or `--compress quantize`, or `false` to skip it). For aggressive size reduction it usually drops a 15 MB GLB to 2-3 MB.
### Failure E: Validator complains "node has no skin"
@@ -330,7 +330,7 @@ The `optimize` command bundles geometry compression, texture resize, image forma
---
-## Step 9 — Complete Mixamo workflow
+## Step 9: Complete Mixamo workflow
Here's the end-to-end. Pick a Mixamo character, ship it as a custom agent body.
@@ -357,7 +357,7 @@ npx @gltf-transform/cli@latest merge \
merged.glb
# 4. Rename clips so the runtime's hint search picks them up.
-# Mixamo names everything "mixamo.com" by default — fix that.
+# Mixamo names everything "mixamo.com" by default: fix that.
# Use a glTF editor (Blender or Gestaltor), or the Step 4 script:
node rename-clips.mjs merged.glb renamed.glb
```
@@ -376,17 +376,17 @@ npx @gltf-transform/cli@latest optimize \
# 7. Upload at https://three.ws/create, then attach it in the agent editor's Outfit panel
```
-Total: 15–25 minutes the first time, 5 minutes once you've done it. The script-based renames step is the only fiddly part; everything else is one-line commands.
+Total: 15-25 minutes the first time, 5 minutes once you've done it. The script-based renames step is the only fiddly part; everything else is one-line commands.
---
-## Step 10 — Verify on the live agent
+## Step 10: Verify on the live agent
Once uploaded:
1. Open any page that embeds the agent (your homepage, or the live preview in the agent editor's Outfit panel).
-2. Confirm the new body loads — no T-pose, no warped limbs.
-3. Send a chat message — the agent should switch to the talk clip while replying.
+2. Confirm the new body loads: no T-pose, no warped limbs.
+3. Send a chat message: the agent should switch to the talk clip while replying.
4. In a browser console, fire each clip by name:
```js
@@ -397,7 +397,7 @@ agent.play('Talk');
agent.play('Idle');
```
-Each one should trigger the corresponding clip. If a clip you expect doesn't fire, run `agent._scene.clips.map(c => c.name)` in the console — that prints the actual clip names the runtime sees. Compare against the names you set in Step 9.
+Each one should trigger the corresponding clip. If a clip you expect doesn't fire, run `agent._scene.clips.map(c => c.name)` in the console, that prints the actual clip names the runtime sees. Compare against the names you set in Step 9.
---
@@ -405,17 +405,17 @@ Each one should trigger the corresponding clip. If a clip you expect doesn't fir
The full custom-GLB pipeline:
-- Compatible avatars come from Mixamo, three.ws Studio, the photo pipeline, or Blender — all produce something the runtime understands
+- Compatible avatars come from Mixamo, three.ws Studio, the photo pipeline, or Blender, all produce something the runtime understands
- The runtime needs a humanoid skeleton, an idle clip, and a talk clip; it likes a wave and a celebrate too
- The validator at [three.ws/validation](https://three.ws/validation) catches every common failure before upload
- Mixamo's `mixamo.com` clip names need renaming so the hint search finds them
- `gltf-transform optimize` is the one command that handles geometry compression, resize, and simplify in one pass (meshopt by default; `--compress draco` for Draco)
-- The dashboard upload path stores the GLB with correct CORS — no separate hosting work needed
+- The dashboard upload path stores the GLB with correct CORS, no separate hosting work needed
Once the body is on the platform, the embed snippet doesn't change. The same `<agent-3d agent-id="...">` tag picks up the new body automatically.
## Next steps
-- [Swap the avatar in Studio](/tutorials/swap-avatar-in-studio) — preview body swaps with no code
-- [Build a personal AI website](/tutorials/personal-ai-site) — put your custom avatar at the centre of a homepage
-- [Give your agent a personality](/tutorials/agent-personality) — match the brain to the new body
+- [Swap the avatar in Studio](/tutorials/swap-avatar-in-studio), preview body swaps with no code
+- [Build a personal AI website](/tutorials/personal-ai-site), put your custom avatar at the centre of a homepage
+- [Give your agent a personality](/tutorials/agent-personality), match the brain to the new body
diff --git a/docs/tutorials/walk-companion.md b/docs/tutorials/walk-companion.md
index ed287b690..fe8ea1857 100644
--- a/docs/tutorials/walk-companion.md
+++ b/docs/tutorials/walk-companion.md
@@ -1,8 +1,8 @@
# Add the Walk Companion to your site
-By the end of this tutorial you'll have a **3D avatar walking across your own website** — a corner mascot that idles, follows the cursor, and waves on navigation, plus a full-page playground the visitor can steer with WASD or a touch joystick. You'll add it two ways: a zero-build iframe you can paste onto any page, and the `@three-ws/walk` npm package when you want the real site-wide companion.
+By the end of this tutorial you'll have a **3D avatar walking across your own website**, a corner mascot that idles, follows the cursor, and waves on navigation, plus a full-page playground the visitor can steer with WASD or a touch joystick. You'll add it two ways: a zero-build iframe you can paste onto any page, and the `@three-ws/walk` npm package when you want the real site-wide companion.
-Along the way you'll see what the [/walk](/walk) product offers — live demos across six environments, the one-tag embed, the Chrome extension that walks the whole web, and the distance leaderboard — and exactly which attributes and APIs are real.
+Along the way you'll see what the [/walk](/walk) product offers, live demos across six environments, the one-tag embed, the Chrome extension that walks the whole web, and the distance leaderboard, and exactly which attributes and APIs are real.
**Prerequisites:** a website you can edit and a WebGL-capable browser. The iframe path needs no tooling at all; the npm path assumes light JavaScript familiarity and that you already bundle [Three.js](https://threejs.org) (>= 0.150).
@@ -22,7 +22,7 @@ Corner companion Full-page playground
└───────────────┘ └───────────────────────────┘
```
-The companion mounts in a corner and stays out of the way: it idles, turns to follow the cursor, waves when the visitor navigates, and greets each page. Click it and it **detaches into a full-page playground** — the visitor steers across the page from a gentle aerial view, or platforms across your real DOM with gravity and jumps. Walk onto a link and it opens like a doorway into the next page.
+The companion mounts in a corner and stays out of the way: it idles, turns to follow the cursor, waves when the visitor navigates, and greets each page. Click it and it **detaches into a full-page playground**, the visitor steers across the page from a gentle aerial view, or platforms across your real DOM with gravity and jumps. Walk onto a link and it opens like a doorway into the next page.
This is the same engine that powers the walking companion on three.ws, published as the `@three-ws/walk` package.
@@ -30,7 +30,7 @@ This is the same engine that powers the walking companion on three.ws, published
## The /walk product (two minutes)
-Before you embed it, it helps to know what the live [/walk](/walk) page exposes — every piece below is something you can link to or reuse:
+Before you embed it, it helps to know what the live [/walk](/walk) page exposes, every piece below is something you can link to or reuse:
| Surface | Route | What it is |
|---|---|---|
@@ -38,7 +38,7 @@ Before you embed it, it helps to know what the live [/walk](/walk) page exposes
| Live demos | embedded on [/walk](/walk) | Real (not video) iframes for `beach`, `night`, `grid`, and more |
| One-tag embed | [/walk-embed](/walk-embed) | The chrome-less iframe you drop on any site |
| Chrome extension | presented on [/walk](/walk) | Your avatar walks over every page you visit, reading them aloud |
-| Distance leaderboard | [/walk-leaderboard](/walk-leaderboard) | The longest strolls on three.ws — daily, weekly, all-time |
+| Distance leaderboard | [/walk-leaderboard](/walk-leaderboard) | The longest strolls on three.ws, daily, weekly, all-time |
The six built-in environments are fixed and need no HDRI downloads: `studio`, `void`, `beach`, `sunset`, `night`, `grid`. You select one with the `env` query param.
@@ -46,10 +46,10 @@ The six built-in environments are fixed and need no HDRI downloads: `studio`, `v
## Step 1: The one-tag embed (no build step)
-The fastest way to put a walking avatar on a page is the [/walk-embed](/walk-embed) iframe. It's intentionally chrome-less — no nav, no footer — so it drops cleanly into a card or a corner.
+The fastest way to put a walking avatar on a page is the [/walk-embed](/walk-embed) iframe. It's intentionally chrome-less, no nav, no footer, so it drops cleanly into a card or a corner.
```html
-<!-- three.ws Walk — drop in anywhere -->
+<!-- three.ws Walk: drop in anywhere -->
<iframe
src="https://three.ws/walk-embed?env=void&autoplay=true"
width="360" height="480"
@@ -98,7 +98,7 @@ The `allow="accelerometer; gyroscope"` attribute lets the joystick respond to de
## Step 2: Drive the embed from the host page (postMessage)
-The embed isn't a black box — it speaks a versioned `postMessage` contract so your page can tell the avatar where to walk, what to say, and which environment to show. The contract is defined in [src/walk-embed-events.js](../../src/walk-embed-events.js) and documented interactively at [/docs/walk-embed-api](/docs/walk-embed-api).
+The embed isn't a black box: it speaks a versioned `postMessage` contract so your page can tell the avatar where to walk, what to say, and which environment to show. The contract is defined in [src/walk-embed-events.js](../../src/walk-embed-events.js) and documented interactively at [/docs/walk-embed-api](/docs/walk-embed-api).
Every message is namespaced to the `three-walk` channel and carries a protocol version, so it never collides with other `message` listeners on your page.
@@ -119,7 +119,7 @@ Every message is namespaced to the `three-walk` channel and carries a protocol v
if (!msg || msg.channel !== 'three-walk') return;
if (msg.type === 'walk:ready') {
- send('walk:say', { text: 'Hi — thanks for visiting.' });
+ send('walk:say', { text: 'Hi: thanks for visiting.' });
send('walk:goto', { x: 4, z: 0 }); // walk to a world spot
}
if (msg.type === 'walk:position') {
@@ -133,10 +133,10 @@ The commands a host can send (inbound) and the events the iframe emits (outbound
| Direction | Message | Payload |
|---|---|---|
-| host → iframe | `walk:goto` | `{ x, z }` — walk to a world position, then stop |
-| host → iframe | `walk:gesture` | `{ gesture }` — one of `idle` `walk` `run` `wave` `jump` |
+| host → iframe | `walk:goto` | `{ x, z }`: walk to a world position, then stop |
+| host → iframe | `walk:gesture` | `{ gesture }`: one of `idle` `walk` `run` `wave` `jump` |
| host → iframe | `walk:say` | `{ text, voice?, durationMs? }` |
-| host → iframe | `walk:env` | `{ env }` — one of the six environments |
+| host → iframe | `walk:env` | `{ env }`: one of the six environments |
| host → iframe | `walk:avatar` | `{ avatarId }` |
| host → iframe | `walk:config` | `{ speed?, bg?, controls? }` |
| iframe → host | `walk:ready` | `{ avatarId, env }` (fires once, when loaded) |
@@ -162,7 +162,7 @@ The iframe is great for a fixed card. For the actual corner-mascot-plus-playgrou
npm install @three-ws/walk three
```
-`three` is a **peer dependency** — the package brings none of its own; you supply >= 0.150 from your app.
+`three` is a **peer dependency**: the package brings none of its own; you supply >= 0.150 from your app.
```js
import { createWalkCompanion } from '@three-ws/walk';
@@ -171,7 +171,7 @@ const walk = createWalkCompanion();
walk.bootstrap();
```
-`createWalkCompanion` is **side-effect free on import** — nothing touches the DOM, and no Three.js is fetched, until you call `bootstrap()` or `enable()`. A page that never turns the companion on pays nothing for shipping the import.
+`createWalkCompanion` is **side-effect free on import**, nothing touches the DOM, and no Three.js is fetched, until you call `bootstrap()` or `enable()`. A page that never turns the companion on pays nothing for shipping the import.
`bootstrap()` is the app-style entry: it auto-mounts based on the visitor's saved preference, honors `?walk=` deep links, and resumes the playground after a page "dive." If you'd rather drive it yourself:
@@ -201,10 +201,10 @@ walk.instance // the live companion (or null)
Once `bootstrap()` is wired, these query params work on any page:
-- `?walk=1` — force the companion on
-- `?walk=0` — force it off
-- `?walk=play` — deep-link straight into the full-page playground
-- `?avatar=<id>` — load a specific avatar (a roster id, or one of your own)
+- `?walk=1`: force the companion on
+- `?walk=0`: force it off
+- `?walk=play`: deep-link straight into the full-page playground
+- `?avatar=<id>`: load a specific avatar (a roster id, or one of your own)
---
@@ -228,9 +228,9 @@ Other options worth knowing: `excludedRoutes` (path prefixes where the companion
---
-## Step 5: Choose who walks — the roster
+## Step 5: Choose who walks: the roster
-Every visitor can pick who walks with them from a built-in roster: a robot mascot, humanoids, a fox, dancers, and showpieces. Each entry declares a rig strategy so it **always moves** — nothing freezes in a bind/T-pose:
+Every visitor can pick who walks with them from a built-in roster: a robot mascot, humanoids, a fox, dancers, and showpieces. Each entry declares a rig strategy so it **always moves**, nothing freezes in a bind/T-pose:
| `rig` | Used for | How it animates |
|---|---|---|
@@ -259,28 +259,28 @@ createWalkCompanion({
}).bootstrap();
```
-User-generated avatars served by the GLB proxy (`/api/avatars/<id>/glb`) resolve at runtime via `makeApiAvatarEntry(id)` — you don't have to list them.
+User-generated avatars served by the GLB proxy (`/api/avatars/<id>/glb`) resolve at runtime via `makeApiAvatarEntry(id)`, you don't have to list them.
---
-## Step 6: Walk the whole web — the Chrome extension
+## Step 6: Walk the whole web: the Chrome extension
The embed and SDK put the avatar on *your* site. The Chrome extension puts it on *every* site the visitor opens. Link to [/walk](/walk) from your page, or just point people there.
What the extension does, per the product page:
-- The avatar walks over any page the user visits — articles, docs, social feeds.
-- It reads pages aloud as it strolls — a living browsing companion.
+- The avatar walks over any page the user visits: articles, docs, social feeds.
+- It reads pages aloud as it strolls: a living browsing companion.
- The visitor picks any of their three.ws avatars from the popup and switches in one click.
- Minimal permissions, no tracking. Privacy details are on [/extension/privacy](/extension/privacy).
-This is the one path you don't embed — you point your visitors at the install. It's the most ambitious surface of the [/walk](/walk) product, and the strongest reason to give your users a three.ws avatar in the first place.
+This is the one path you don't embed: you point your visitors at the install. It's the most ambitious surface of the [/walk](/walk) product, and the strongest reason to give your users a three.ws avatar in the first place.
---
## Step 7: The distance leaderboard
-Every stroll logs distance, and the longest ones climb the global board at [/walk-leaderboard](/walk-leaderboard) — ranked daily, weekly, and all-time. The data is real, served from `/api/walk/leaderboard`, so you can surface a "top walkers" teaser on your own page:
+Every stroll logs distance, and the longest ones climb the global board at [/walk-leaderboard](/walk-leaderboard), ranked daily, weekly, and all-time. The data is real, served from `/api/walk/leaderboard`, so you can surface a "top walkers" teaser on your own page:
```js
async function loadTopWalkers() {
@@ -291,14 +291,14 @@ async function loadTopWalkers() {
if (!res.ok) throw new Error(`HTTP ${res.status}`);
const { rows = [] } = await res.json();
// Each row: { rank, key, username, handle, avatarId, avatar, value, deltaFromYesterday }
- // `value` is the metric you asked for — meters for metric=distance.
+ // `value` is the metric you asked for: meters for metric=distance.
return rows;
}
```
`period` is `daily` / `weekly` (the default) / `all-time`, `metric` is `distance` (the default) / `sites` / `time`, and `limit` is 1 to 100 (default 50). The response also carries `total`, `offset`, and `hasMore` for paging.
-Format distances for display the way the live board does — meters under 1 km, kilometres above:
+Format distances for display the way the live board does, meters under 1 km, kilometres above:
```js
function formatDistance(meters) {
@@ -315,14 +315,14 @@ Always design the empty and error states: a fresh deployment has no walks logged
## Troubleshooting
-- **Iframe is blank / "loading avatar…" never clears** — the host needs WebGL. Confirm the browser is WebGL-capable and the page isn't blocking the iframe with a restrictive `Content-Security-Policy` `frame-src`. The embed ships `frame-ancestors *`, so it's the host CSP that usually blocks it.
-- **postMessage commands do nothing** — you're probably sending before `walk:ready`. Wait for the `walk:ready` event, or send `walk:ping` to re-trigger it. Also confirm your envelope is `{ channel: 'three-walk', v: 1, type, ...payload }` — messages without the channel are ignored unless they use a known legacy `walk:*` type.
-- **`walk:goto` lands somewhere unexpected** — coordinates are clamped to the world radius (~±11.5m). A target outside the ground disc is pulled back in.
-- **`walk:env` rejected with a `walk:error`** — `env` must be exactly one of `studio` `void` `beach` `sunset` `night` `grid`. Anything else is refused.
-- **Avatar shows a frozen T-pose** — that means the rig strategy is wrong for the GLB. A humanoid that ships only a T-pose must use `rig: 'shared'` so the shared clip library is retargeted onto it; `embedded` is only for GLBs that carry their own clips.
-- **SDK throws on import about `three`** — `three` is a peer dependency. Install it (`npm install three`) and make sure your bundle resolves a single copy >= 0.150.
-- **Companion never appears after `bootstrap()`** — check it's not an excluded route. By default the corner mascot skips full-screen 3D paths (`/walk`, `/walk-embed`, `/play`, `/ar`, and similar). Override `excludedRoutes` if your paths overlap.
-- **The companion loaded Three.js on a page that doesn't use it** — it shouldn't: `createWalkCompanion` is side-effect-free on import and fetches nothing until `enable()`/`bootstrap()`. If you see a fetch, something is calling `enable()` unconditionally.
+- **Iframe is blank / "loading avatar…" never clears**, the host needs WebGL. Confirm the browser is WebGL-capable and the page isn't blocking the iframe with a restrictive `Content-Security-Policy` `frame-src`. The embed ships `frame-ancestors *`, so it's the host CSP that usually blocks it.
+- **postMessage commands do nothing**: you're probably sending before `walk:ready`. Wait for the `walk:ready` event, or send `walk:ping` to re-trigger it. Also confirm your envelope is `{ channel: 'three-walk', v: 1, type, ...payload }`, messages without the channel are ignored unless they use a known legacy `walk:*` type.
+- **`walk:goto` lands somewhere unexpected**: coordinates are clamped to the world radius (~±11.5m). A target outside the ground disc is pulled back in.
+- **`walk:env` rejected with a `walk:error`**: `env` must be exactly one of `studio` `void` `beach` `sunset` `night` `grid`. Anything else is refused.
+- **Avatar shows a frozen T-pose**: that means the rig strategy is wrong for the GLB. A humanoid that ships only a T-pose must use `rig: 'shared'` so the shared clip library is retargeted onto it; `embedded` is only for GLBs that carry their own clips.
+- **SDK throws on import about `three`**: `three` is a peer dependency. Install it (`npm install three`) and make sure your bundle resolves a single copy >= 0.150.
+- **Companion never appears after `bootstrap()`**: check it's not an excluded route. By default the corner mascot skips full-screen 3D paths (`/walk`, `/walk-embed`, `/play`, `/ar`, and similar). Override `excludedRoutes` if your paths overlap.
+- **The companion loaded Three.js on a page that doesn't use it**, it shouldn't: `createWalkCompanion` is side-effect-free on import and fetches nothing until `enable()`/`bootstrap()`. If you see a fetch, something is calling `enable()` unconditionally.
---
@@ -330,17 +330,17 @@ Always design the empty and error states: a fresh deployment has no walks logged
You added a walking 3D avatar to your site three ways and learned what the [/walk](/walk) product ships:
-- **One-tag embed** — paste the [/walk-embed](/walk-embed) iframe, pick the world and controls with query params (`env`, `controls`, `orbit`, `avatar`). No build step.
-- **postMessage contract** — drive the embed from the host page with `walk:goto` / `walk:say` / `walk:env` and listen for `walk:ready` / `walk:position`, on the versioned `three-walk` channel. Full reference at [/docs/walk-embed-api](/docs/walk-embed-api).
-- **`@three-ws/walk` SDK** — `createWalkCompanion().bootstrap()` mounts the real corner companion plus the full-page playground, side-effect-free until enabled, with a built-in avatar picker and a two-strategy roster that never T-poses.
-- **The product surfaces** — the Chrome extension presented on [/walk](/walk) that walks the whole web, and the distance [/walk-leaderboard](/walk-leaderboard) you can read from `/api/walk/leaderboard`.
+- **One-tag embed**: paste the [/walk-embed](/walk-embed) iframe, pick the world and controls with query params (`env`, `controls`, `orbit`, `avatar`). No build step.
+- **postMessage contract**: drive the embed from the host page with `walk:goto` / `walk:say` / `walk:env` and listen for `walk:ready` / `walk:position`, on the versioned `three-walk` channel. Full reference at [/docs/walk-embed-api](/docs/walk-embed-api).
+- **`@three-ws/walk` SDK**: `createWalkCompanion().bootstrap()` mounts the real corner companion plus the full-page playground, side-effect-free until enabled, with a built-in avatar picker and a two-strategy roster that never T-poses.
+- **The product surfaces**: the Chrome extension presented on [/walk](/walk) that walks the whole web, and the distance [/walk-leaderboard](/walk-leaderboard) you can read from `/api/walk/leaderboard`.
-The leverage is composability: the same engine renders the corner mascot, the full-page playground, the standalone embed, and the extension — so an avatar you build once walks everywhere.
+The leverage is composability: the same engine renders the corner mascot, the full-page playground, the standalone embed, and the extension, so an avatar you build once walks everywhere.
## See also
-- [3D store guide for Shopify](/tutorials/shopify-store-guide) — the same engine as a guided tour: the avatar walks a storefront, spotlights sections, and narrates each one
-- [Walk docs](/docs/walk) — the full developer + user reference for the walking-avatar system
-- [Walk embed API](/docs/walk-embed-api) — interactive playground for the postMessage contract
-- [Swap your avatar in Studio](/docs/tutorials/swap-avatar-in-studio) — build the avatar that walks
-- [Embed your agent on a website](/docs/tutorials/embed-on-website) — the other side of putting three.ws on your page
+- [3D store guide for Shopify](/tutorials/shopify-store-guide), the same engine as a guided tour: the avatar walks a storefront, spotlights sections, and narrates each one
+- [Walk docs](/docs/walk): the full developer + user reference for the walking-avatar system
+- [Walk embed API](/docs/walk-embed-api): interactive playground for the postMessage contract
+- [Swap your avatar in Studio](/docs/tutorials/swap-avatar-in-studio), build the avatar that walks
+- [Embed your agent on a website](/docs/tutorials/embed-on-website), the other side of putting three.ws on your page
diff --git a/docs/tutorials/web-component-end-to-end.md b/docs/tutorials/web-component-end-to-end.md
index ea76c965c..692fefefb 100644
--- a/docs/tutorials/web-component-end-to-end.md
+++ b/docs/tutorials/web-component-end-to-end.md
@@ -1,8 +1,8 @@
# Use the &lt;agent-3d&gt; web component end-to-end
-The iframe snippet is convenient. Paste it, agent on the page. But once your site has a component system — React, Vue, Svelte, a design system — that opaque iframe starts to feel like a stranger in the codebase. You want the agent to be a real component, with props, refs, lifecycle, and a place in your component library.
+The iframe snippet is convenient. Paste it, agent on the page. But once your site has a component system, React, Vue, Svelte, a design system, that opaque iframe starts to feel like a stranger in the codebase. You want the agent to be a real component, with props, refs, lifecycle, and a place in your component library.
-That's what `<agent-3d>` is for. It's a standards-based custom element that drops cleanly into any framework, exposes the full JavaScript API (methods, events, live attributes), and supports reactive attribute changes — you can swap the loaded agent at runtime by changing one prop.
+That's what `<agent-3d>` is for. It's a standards-based custom element that drops cleanly into any framework, exposes the full JavaScript API (methods, events, live attributes), and supports reactive attribute changes, you can swap the loaded agent at runtime by changing one prop.
By the end of this tutorial you'll know the spec well enough to pick the right embed style for any project, wire the element into React and Vue with refs and reactivity, slot your own UI alongside the avatar, and react to attribute changes after mount.
@@ -14,15 +14,15 @@ By the end of this tutorial you'll know the spec well enough to pick the right e
- A slotted layout where your chat input lives next to the avatar
- A short web-components primer if you've never built a custom element
-**Prerequisites:** Familiarity with React (hooks, refs) or Vue 3 (Composition API). You don't need prior experience with the Custom Elements spec — Step 1 covers the basics.
+**Prerequisites:** Familiarity with React (hooks, refs) or Vue 3 (Composition API). You don't need prior experience with the Custom Elements spec, Step 1 covers the basics.
---
-## Step 1 — A 60-second web components primer
+## Step 1: A 60-second web components primer
If you already know custom elements, skip to Step 2. Otherwise, here's the part of the spec that matters for using `<agent-3d>`.
-A custom element is a tag your browser doesn't ship by default. Someone (us, in this case) registers a JavaScript class against a name, and from that point on the tag works exactly like any built-in element. You can put `<agent-3d>` in HTML, in JSX, in a Vue template — anywhere a `<div>` would go.
+A custom element is a tag your browser doesn't ship by default. Someone (us, in this case) registers a JavaScript class against a name, and from that point on the tag works exactly like any built-in element. You can put `<agent-3d>` in HTML, in JSX, in a Vue template, anywhere a `<div>` would go.
Three things make custom elements powerful:
@@ -40,11 +40,11 @@ From that point on, `<agent-3d>` is a real tag in the document. No further setup
---
-## Step 2 — iframe embed vs the custom element
+## Step 2: iframe embed vs the custom element
The platform offers two embed styles for the same agent. The differences are ergonomic.
-**iframe form** — sandboxed, self-contained, no script tag on your page:
+**iframe form**: sandboxed, self-contained, no script tag on your page:
```html
<iframe
@@ -57,7 +57,7 @@ The platform offers two embed styles for the same agent. The differences are erg
></iframe>
```
-The agent runs entirely inside the iframe. You can't call methods on it or listen to its events from your page — the trade for that isolation is zero integration surface.
+The agent runs entirely inside the iframe. You can't call methods on it or listen to its events from your page, the trade for that isolation is zero integration surface.
This is the right embed when:
@@ -65,7 +65,7 @@ This is the right embed when:
- You want strict sandboxing between the agent and your page
- You don't need to drive the agent from your own JavaScript
-**Custom element form** — explicit, structured, framework-friendly:
+**Custom element form**: explicit, structured, framework-friendly:
```html
<script type="module" src="https://three.ws/agent-3d/1.5.2/agent-3d.js"></script>
@@ -79,7 +79,7 @@ This is the right embed when:
></agent-3d>
```
-You separate "load the runtime" from "place the agent". The agent can appear anywhere in your tree, with explicit attributes you can read from a build system, type-check, or template — and you get the full JS API: `say()`, `ask()`, `wave()`, `play()`, and the event stream.
+You separate "load the runtime" from "place the agent". The agent can appear anywhere in your tree, with explicit attributes you can read from a build system, type-check, or template, and you get the full JS API: `say()`, `ask()`, `wave()`, `play()`, and the event stream.
This is the right embed when:
@@ -91,7 +91,7 @@ The rest of this tutorial uses the custom-element form, because that's the one t
---
-## Step 3 — The attribute surface
+## Step 3: The attribute surface
Here are the attributes you'll actually reach for, by category. (`observedAttributes` in [src/element.js](https://github.com/nirholas/three.ws/blob/main/src/element.js) is the exhaustive list; it also carries niche ones like `avatar-id`, `api-base`, `name-plate`, `tracked-mint`, `clip`, `wallet`, and `sign-language`.)
@@ -101,7 +101,7 @@ Here are the attributes you'll actually reach for, by category. (`observedAttrib
|---|---|
| `agent-id` | The platform-hosted agent ID. Resolves the manifest from three.ws. |
| `manifest` | URL to a JSON manifest file. Use this for self-hosted agents. |
-| `body` | Direct URL to a GLB model. Bypasses the manifest path entirely — useful for quick tests. |
+| `body` | Direct URL to a GLB model. Bypasses the manifest path entirely, useful for quick tests. |
| `src` | Legacy alias for `manifest`. Prefer `manifest` for new code. |
**Layout:**
@@ -125,7 +125,7 @@ Here are the attributes you'll actually reach for, by category. (`observedAttrib
| `avatar-chat` | Set to `off` to drop the avatar out of the chat column and lay the chat out as a plain bottom bar |
| `avatar-walk` | Set to `off` to disable the walk-when-talking behaviour |
| `framing` | Set to `portrait` for a head-and-shoulders camera framing; the default frames the full body |
-| `eager` | Skip the lazy-load wait — boot immediately even when off-screen |
+| `eager` | Skip the lazy-load wait: boot immediately even when off-screen |
| `api-key` | Override the brain API key (use sparingly; backends are safer) |
| `key-proxy` | URL of your own proxy that vends scoped keys |
@@ -133,9 +133,9 @@ Every observed attribute can be changed after mount, and Step 6 shows what that
---
-## Step 4 — A reusable React wrapper
+## Step 4: A reusable React wrapper
-React doesn't know about custom elements out of the box. The DOM does — React just passes attributes and children through. That means most things "just work", with two exceptions:
+React doesn't know about custom elements out of the box. The DOM does, React just passes attributes and children through. That means most things "just work", with two exceptions:
1. **Booleans:** React converts `eager={true}` into the string `"true"`, which is *not* the same as the bare `eager` attribute. Use `eager=""` or omit the attribute entirely.
2. **Events:** React's `onSomething` props only work for events the framework knows about. Custom events need an `addEventListener` in a `useEffect`.
@@ -251,7 +251,7 @@ A few notes on what the wrapper does:
- **Runtime loaded once.** `ensureRuntime()` guards against re-injecting the script on every mount. It checks for an existing tag with `data-agent-3d-runtime` and resolves immediately if found.
- **Events bound in `useEffect`.** Custom event names map to props (`onReady`, `onMessage`). The cleanup function unbinds them, so the wrapper plays nicely with strict mode and unmount.
-- **No camelCase attribute names.** Custom elements use dash-case (`agent-id`, not `agentId`). React passes attributes through as-is — `agent-id` is fine in JSX.
+- **No camelCase attribute names.** Custom elements use dash-case (`agent-id`, not `agentId`). React passes attributes through as-is, `agent-id` is fine in JSX.
- **`useRef` is the API handle.** If you need to call `ref.current.say('hi')` from a parent, expose the ref via `forwardRef` or pass an `apiRef` prop in.
For TypeScript, drop this in a `.d.ts`:
@@ -279,7 +279,7 @@ declare namespace JSX {
---
-## Step 5 — A Vue 3 wrapper
+## Step 5: A Vue 3 wrapper
Vue handles custom elements gracefully provided you flag them as such. Add `agent-3d` to the compiler's custom-element list in your build config:
@@ -405,7 +405,7 @@ The `defineExpose` block matters: without it, the parent's `agent.value.say(...)
---
-## Step 6 — Reactive attribute changes
+## Step 6: Reactive attribute changes
This is the moment when the custom-element approach really pays off. The element observes its key attributes, so changing one re-runs the relevant boot logic.
@@ -432,11 +432,11 @@ The same trick works for `body`, `manifest`, `src`, and the layout attributes (`
There are a few attributes worth treating carefully:
-- `eager` — only matters at first mount; toggling it after boot has no effect since boot already happened.
-- `api-key` — changing this mid-session won't re-issue in-flight LLM calls. Treat it as set-once for any given agent instance.
-- `tracked-mint` — changing this swaps the on-chain trade feed the agent is reacting to. Useful for token-aware widgets.
+- `eager`: only matters at first mount; toggling it after boot has no effect since boot already happened.
+- `api-key`: changing this mid-session won't re-issue in-flight LLM calls. Treat it as set-once for any given agent instance.
+- `tracked-mint`: changing this swaps the on-chain trade feed the agent is reacting to. Useful for token-aware widgets.
-If you need a *full* fresh re-mount (rare — usually the in-place swap is what you want), key the element on the agent ID:
+If you need a *full* fresh re-mount (rare: usually the in-place swap is what you want), key the element on the agent ID:
```jsx
<Agent3D key={activeAgent} agentId={activeAgent} />
@@ -446,9 +446,9 @@ The `key` prop forces React to unmount and remount the wrapper, which fully tear
---
-## Step 7 — Slotting your own UI
+## Step 7: Slotting your own UI
-The element has a built-in chat input at the bottom. That's fine for a drop-in widget. For an integrated product page, you usually want your own input — styled to match your design system, sharing the page layout, with custom send buttons.
+The element has a built-in chat input at the bottom. That's fine for a drop-in widget. For an integrated product page, you usually want your own input, styled to match your design system, sharing the page layout, with custom send buttons.
Two parts to this.
@@ -464,7 +464,7 @@ Two parts to this.
></agent-3d>
```
-The brain still boots, so `say()`, `ask()`, and the whole event stream keep working — only the chrome is gone.
+The brain still boots, so `say()`, `ask()`, and the whole event stream keep working, only the chrome is gone.
**Wire your own UI** that calls the element's API:
@@ -518,14 +518,14 @@ That's the bare minimum. In a real product page you would also add a chat-log el
Two cautions when going custom-UI:
-- **Don't try to inject DOM into the agent's shadow root.** The element uses Shadow DOM (`mode: 'open'`) — you *can* technically reach into it, but anything in there is internal and will change between versions. Build your UI *around* the agent, not *inside* it.
+- **Don't try to inject DOM into the agent's shadow root.** The element uses Shadow DOM (`mode: 'open'`), you *can* technically reach into it, but anything in there is internal and will change between versions. Build your UI *around* the agent, not *inside* it.
- **Style the wrapper, not the internals.** CSS rules on `<agent-3d>` itself (width, height, position) work fine. CSS rules targeting its shadow children won't survive a minor version bump.
---
-## Step 8 — A complete example, top to bottom
+## Step 8: A complete example, top to bottom
-Here's a single-file working example you can drop into any Vite or Next.js app. It's the full pattern from Steps 4 and 6 combined — a wrapper, a reactive agent swap, and event handling.
+Here's a single-file working example you can drop into any Vite or Next.js app. It's the full pattern from Steps 4 and 6 combined, a wrapper, a reactive agent swap, and event handling.
```jsx
// pages/agents.jsx (Next.js) or src/Agents.jsx (Vite)
@@ -581,7 +581,7 @@ Pick an agent from the dropdown, the active one swaps in place, and the event lo
You can now treat `<agent-3d>` as a real component in any framework. The big takeaways:
-- The iframe and custom-element embeds serve different jobs — sandboxed drop-in vs a full-API component; reach for the element whenever your own code needs to drive the agent
+- The iframe and custom-element embeds serve different jobs, sandboxed drop-in vs a full-API component; reach for the element whenever your own code needs to drive the agent
- Attribute changes are reactive; you can swap agents, modes, and layouts at runtime
- React works fine once you bind events in `useEffect`; remember dash-case attribute names
- Vue works fine once you flag the tag as a custom element in the compiler config
@@ -592,6 +592,6 @@ The web component is the most robust integration point the platform offers. Buil
## Next steps
-- [Drive the agent with the JavaScript API](/tutorials/js-api-events) — methods and events covered in depth
-- [Embed a three.ws agent on your website](./embed-on-website.md) — the no-framework paths (Webflow, WordPress, Squarespace) for completeness
-- [Trigger the agent from page events](/tutorials/trigger-from-page-events) — once it's mounted, make it react to the user journey
+- [Drive the agent with the JavaScript API](/tutorials/js-api-events), methods and events covered in depth
+- [Embed a three.ws agent on your website](./embed-on-website.md), the no-framework paths (Webflow, WordPress, Squarespace) for completeness
+- [Trigger the agent from page events](/tutorials/trigger-from-page-events), once it's mounted, make it react to the user journey
diff --git a/packages/alibaba-cloud-mcp/README.md b/packages/alibaba-cloud-mcp/README.md
index 72f4a3904..e29a11beb 100644
--- a/packages/alibaba-cloud-mcp/README.md
+++ b/packages/alibaba-cloud-mcp/README.md
@@ -4,7 +4,7 @@
<h1 align="center">@three-ws/alibaba-cloud-mcp</h1>
-<p align="center"><strong>MCP server for Alibaba Cloud DashScope — Qwen chat, embeddings, and model discovery on your own account.</strong></p>
+<p align="center"><strong>MCP server for Alibaba Cloud DashScope, Qwen chat, embeddings, and model discovery on your own account.</strong></p>
<p align="center">
<a href="https://www.npmjs.com/package/@three-ws/alibaba-cloud-mcp"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/alibaba-cloud-mcp?logo=npm&color=cb3837"></a>
@@ -23,7 +23,7 @@
---
-> A [Model Context Protocol](https://modelcontextprotocol.io) server that exposes Alibaba Cloud's Qwen models — and anything else in your DashScope account — to MCP clients such as Claude Desktop, Claude Code, and Cursor. It talks **directly** to the DashScope OpenAI-compatible REST API with **your own Alibaba Cloud API key**: no intermediary backend, no telemetry, no mock data.
+> A [Model Context Protocol](https://modelcontextprotocol.io) server that exposes Alibaba Cloud's Qwen models, and anything else in your DashScope account, to MCP clients such as Claude Desktop, Claude Code, and Cursor. It talks **directly** to the DashScope OpenAI-compatible REST API with **your own Alibaba Cloud API key**: no intermediary backend, no telemetry, no mock data.
> Community-built and not affiliated with Alibaba Cloud. Registry name: `io.github.nirholas/alibaba-cloud`.
@@ -66,7 +66,7 @@ Or add the server to your MCP client config:
## Requirements
1. An [Alibaba Cloud account](https://www.alibabacloud.com/)
-2. A [DashScope API key](https://bailian.console.alibabacloud.com/) — navigate to **API Keys** and create one
+2. A [DashScope API key](https://bailian.console.alibabacloud.com/), navigate to **API Keys** and create one
3. Node.js ≥ 20
## Tools
@@ -81,9 +81,9 @@ Or add the server to your MCP client config:
| Model ID | Use |
|---|---|
-| `qwen-max` | Highest quality — complex reasoning, long documents |
+| `qwen-max` | Highest quality: complex reasoning, long documents |
| `qwen-plus` | Balanced performance (default) |
-| `qwen-turbo` | Fastest and cheapest — simple tasks |
+| `qwen-turbo` | Fastest and cheapest: simple tasks |
| `qwen-long` | Long context (up to 1M tokens) |
| `text-embedding-v3` | Embeddings, semantic search, RAG (default) |
@@ -91,11 +91,11 @@ Or add the server to your MCP client config:
| Variable | Required | Default | Description |
|---|---|---|---|
-| `DASHSCOPE_API_KEY` | **yes** | — | Your DashScope API key |
+| `DASHSCOPE_API_KEY` | **yes** | - | Your DashScope API key |
| `DASHSCOPE_MODEL_ID` | no | `qwen-plus` | Default chat model |
| `DASHSCOPE_EMBED_MODEL_ID` | no | `text-embedding-v3` | Default embedding model |
| `DASHSCOPE_BASE_URL` | no | International endpoint | Custom DashScope endpoint |
-| `DASHSCOPE_REGION` | no | — | Set to `cn` for the China endpoint |
+| `DASHSCOPE_REGION` | no | - | Set to `cn` for the China endpoint |
| `DASHSCOPE_TIMEOUT_MS` | no | `60000` | Request timeout in ms |
## Inspect
@@ -114,7 +114,7 @@ importable from `@three-ws/alibaba-cloud-mcp/src/dashscope.js` (`loadConfig`,
`DashScopeClient`, `DashScopeError`) when you want the REST wrapper without MCP.
```js
-// example.mjs — run with: DASHSCOPE_API_KEY=sk-... node example.mjs
+// example.mjs: run with: DASHSCOPE_API_KEY=sk-... node example.mjs
import { StdioServerTransport } from '@modelcontextprotocol/sdk/server/stdio.js';
import { buildServer } from '@three-ws/alibaba-cloud-mcp';
diff --git a/packages/irl/README.md b/packages/irl/README.md
index 1bdeb633c..96d699756 100644
--- a/packages/irl/README.md
+++ b/packages/irl/README.md
@@ -4,7 +4,7 @@
<h1 align="center">@three-ws/irl</h1>
-<p align="center"><strong>Geofenced, real-world presence for agents and avatars — check in at a place, prove you were there, discover who and what is nearby.</strong></p>
+<p align="center"><strong>Geofenced, real-world presence for agents and avatars, check in at a place, prove you were there, discover who and what is nearby.</strong></p>
<p align="center">
<a href="https://www.npmjs.com/package/@three-ws/irl"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/irl?logo=npm&color=cb3837"></a>
@@ -25,7 +25,7 @@
---
-> `@three-ws/irl` is the official client for **three.ws IRL** — the layer that
+> `@three-ws/irl` is the official client for **three.ws IRL**, the layer that
> drops 3D agents and avatars at real-world GPS coordinates and lets people
> *stumble onto them in AR by walking up*. You check in at a spot, mint a
> short-lived proof-of-presence token from your live fix, and read back only the
@@ -34,7 +34,7 @@
> nearby feed, the real-world interaction log, **[Money Drops](#money-drops)**
> (real SOL / USDC / $THREE escrowed at a spot, claimable only by walking up)
> and **[World Lines](#world-lines)** (agent-signed proof-of-presence AR
-> quests). Presence is the contract — there is no browseable map, no roster, no
+> quests). Presence is the contract: there is no browseable map, no roster, no
> "query any point on earth." You see what's around you, because you're there.
> It pairs with [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge)
> (make the avatar) and [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar)
@@ -49,18 +49,18 @@ hole structurally, and this SDK gives you the whole flow as plain functions:
- **Presence is proven, not claimed.** Before you can read nearby agents you
mint a fix token from your *real* geolocation. The server only answers for the
- coarse area that token was minted in — "query anywhere" becomes "query where
+ coarse area that token was minted in: "query anywhere" becomes "query where
you are." No token banking, no remote scraping.
- **Tight by default.** The nearby feed is radius-capped at **60 m** (default
- 40 m), returns at most 50 pins, and is IP rate-limited with sweep detection —
+ 40 m), returns at most 50 pins, and is IP rate-limited with sweep detection -
large enough to render an agent as you walk up, small enough that one read only
ever reveals the handful right where you stand.
-- **Anonymous-friendly.** Place and manage pins from a device token — no login.
+- **Anonymous-friendly.** Place and manage pins from a device token, no login.
Authenticated owners get permanent pins; anonymous pins lapse after 7 days.
- **Coordinates are minimized.** The public feed coarsens lat/lng to ~1.1 m,
never returns owner ids, and never logs the caller's position.
-This is the SDK twin of the live [/irl](https://three.ws/irl) surface — the same
+This is the SDK twin of the live [/irl](https://three.ws/irl) surface, the same
endpoints, exposed as plain functions.
## Install
@@ -99,7 +99,7 @@ const { pin } = await placePin({
lng: fix.lng,
avatarName: 'Scout',
avatarUrl: 'https://three.ws/avatars/xbot.glb', // any hosted avatar GLB works
- caption: 'Say hi — I drop $THREE alpha here',
+ caption: 'Say hi: I drop $THREE alpha here',
});
console.log(pin.id, pin.permanent ? 'permanent' : 'expires in 7 days');
@@ -135,7 +135,7 @@ alongside the fix so `nearby()` can prove the read.
| `lat` / `lng` | `number` | The fix used to mint the token. |
| `token` | `string` | HMAC-signed presence token (header `x-irl-fix` on reads). |
| `expiresIn` | `number` | Token lifetime in seconds: **180** (3 min). Re-`checkIn()` when it lapses. |
-| `cell` | `string` | The precision-7 geohash (~153 m) the fix fell in — the client's "re-mint on cell change" trigger. |
+| `cell` | `string` | The precision-7 geohash (~153 m) the fix fell in, the client's "re-mint on cell change" trigger. |
The token anchor is coarsened to ~110 m server-side, so the token itself never
carries a fine coordinate. A read is authorized only when its claimed point is
@@ -149,9 +149,9 @@ header.
| Option | Type | Default | Notes |
|---|---|---|---|
-| `radius` | `number` | `40` | Metres. Clamped server-side to **10–60 m**. |
+| `radius` | `number` | `40` | Metres. Clamped server-side to **10-60 m**. |
-Each returned `Pin` (allow-list projection — never `user_id` or `device_token`).
+Each returned `Pin` (allow-list projection: never `user_id` or `device_token`).
The SDK camelCases the wire row and keeps the untouched original on `raw`:
| Field | Type | Notes |
@@ -159,17 +159,17 @@ The SDK camelCases the wire row and keeps the untouched original on `raw`:
| `id` | `string` | Pin UUID. |
| `agentId` | `string \| null` | Linked agent identity, if any. |
| `lat` / `lng` | `number` | Coarsened to ~1.1 m (5 dp). |
-| `heading` | `number` | Facing, 0–359°. |
+| `heading` | `number` | Facing, 0-359°. |
| `distanceM` | `number` | Great-circle metres from your fix. |
| `avatarUrl` | `string` | GLB to load (relative or first-party https). |
| `avatarName` / `caption` | `string \| null` | Public display text. |
| `x402Endpoint` | `string \| null` | First-party pay target for the agent. |
| `viewCount` | `number` | Deduplicated visitor count. |
-| `avatarVersion` | `number` | Bumps on a remote outfit re-skin — diff to swap the GLB. |
+| `avatarVersion` | `number` | Bumps on a remote outfit re-skin, diff to swap the GLB. |
| `placedAt` | `string \| null` | When the pin was dropped. |
-| `anchorHeightM`, `anchorYawDeg`, `anchorQuat`, `anchorSource` | — | AR replay pose, when the placement carried one. |
+| `anchorHeightM`, `anchorYawDeg`, `anchorQuat`, `anchorSource` | - | AR replay pose, when the placement carried one. |
| `gpsAccuracyM`, `altitudeM` | `number \| null` | Fix quality at placement time. |
-| `roomId`, `relEastM`, `relNorthM`, `originLat`, `originLng`, `originYawDeg` | — | Room frame for shared-anchor clusters (null on standalone pins). |
+| `roomId`, `relEastM`, `relNorthM`, `originLat`, `originLng`, `originYawDeg` | - | Room frame for shared-anchor clusters (null on standalone pins). |
| `isMine` | `boolean` | True for the caller's own pins. |
| `raw` | `unknown` | The untouched wire row (`avatar_name`, `distance_m`, …). |
@@ -183,17 +183,17 @@ Drop a 3D agent at a coordinate. Wraps `POST /api/irl/pins`.
|---|---|---|
| `lat` / `lng` | `number` | **Required.** Range-checked. |
| `heading` | `number` | Initial facing in degrees (default 0). |
-| `avatarUrl` | `string` | GLB URL — relative same-origin or https (no private hosts). |
+| `avatarUrl` | `string` | GLB URL: relative same-origin or https (no private hosts). |
| `avatarName` | `string` | ≤ 40 chars. |
| `caption` | `string` | ≤ 140 chars. Content-gated; may reference only `$THREE`. |
| `agentId` | `string` | Link the pin to a registered agent. |
-| `x402Endpoint` | `string` | Pay target — must be a first-party three.ws host. |
+| `x402Endpoint` | `string` | Pay target: must be a first-party three.ws host. |
| `anchor` | `object` | Optional pose `{ heightM, yawDeg, quat, source }` for AR replay. |
-| `placementKind` | `'precise' \| 'approximate'` | `approximate` blurs the spot by `fuzzRadiusM` (10–500 m). |
+| `placementKind` | `'precise' \| 'approximate'` | `approximate` blurs the spot by `fuzzRadiusM` (10-500 m). |
Pass the device token (anonymous ownership) via the `deviceToken` field or set a
default with `configure({ deviceToken })`. Returns `201` with the created pin and
-a `permanent` flag (`true` for signed-in owners, `false` — 7-day expiry — for
+a `permanent` flag (`true` for signed-in owners, `false`, 7-day expiry, for
anonymous).
### `myPins(options?) → Promise<Pin[]>`
@@ -233,7 +233,7 @@ deviceToken })` sets defaults for the module (base origin defaults to
Real value, escrowed at a real-world spot. A drop holds SOL, USDC, or $THREE in
a fresh per-drop escrow wallet, funded on-chain by its creator; anyone who
-physically walks up — proven by the same fix token every IRL read enforces —
+physically walks up: proven by the same fix token every IRL read enforces -
claims a real on-chain release to their own wallet. Unclaimed funds auto-refund
the creator on expiry. Wraps `/api/irl/drops`.
@@ -275,7 +275,7 @@ const { drop, escrowAddress, fundAmount } = await createDrop({
await fundDrop({ dropId: drop.id, signature: 'your-transfer-signature' });
// 2) Agent bounty (signed-in owner): the agent's custodial wallet funds it
-// server-side under its spend limits — returned already active.
+// server-side under its spend limits: returned already active.
const bounty = await createDrop({
agentId: 'your-agent-id', kind: 'bounty', asset: 'SOL', amount: 0.1,
lat: fix.lat, lng: fix.lng, bountyCondition: 'quiz',
@@ -286,9 +286,9 @@ console.log(bounty.funded, bounty.fundingTx);
| Function | Wraps | Notes |
|---|---|---|
-| `nearbyDrops(presence, { radius? })` | `GET /api/irl/drops?lat=&lng=` | Fix-gated; radius clamped 10–80 m. |
+| `nearbyDrops(presence, { radius? })` | `GET /api/irl/drops?lat=&lng=` | Fix-gated; radius clamped 10-80 m. |
| `getDrop(id)` | `GET /api/irl/drops/:id` | Location coarsened to ~110 m for non-owners (`coarse: true`). |
-| `myDrops()` | `GET /api/irl/drops?mine=1` | `{ drops, claims }` — your creations + claim receipts. |
+| `myDrops()` | `GET /api/irl/drops?mine=1` | `{ drops, claims }`, your creations + claim receipts. |
| `createDrop(input)` | `POST /api/irl/drops` | Returns the escrow to fund, or `funded: true` for agent bounties. |
| `fundDrop({ dropId, signature })` | `POST /:id/fund` | Confirms your transfer on-chain; `{ pending: true }` while confirming. |
| `claimDrop({ dropId, presence, wallet, answer? })` | `POST /:id/claim` | Presence always verified; releases real funds to `wallet`. |
@@ -304,8 +304,8 @@ re-`checkIn()`), `out_of_range` (the drop's radius, with `distance_m` in
Agent-placed proof-of-presence AR quests. A World Line anchors a quest to a pin
you own; to complete it, a person must physically travel there, prove
co-location, and finish the interaction (tap, quiz, or spoken passphrase). On
-success the **agent's own wallet signs an ed25519 proof-of-presence** —
-independently verifiable by anyone, ownable as a collectible — without a
+success the **agent's own wallet signs an ed25519 proof-of-presence** -
+independently verifiable by anyone, ownable as a collectible, without a
precise coordinate ever entering the proof. Wraps `/api/irl/world-lines`.
The walk-up completion loop:
@@ -330,14 +330,14 @@ const { proof, collectible } = await completeWorldLine({
console.log('agent-signed proof:', proof.signature, '→', proof.verifyUrl);
```
-Place a quest on your pin (signed-in — pass `apiKey` to `createIrl`):
+Place a quest on your pin (signed-in: pass `apiKey` to `createIrl`):
```js
import { createIrl } from '@three-ws/irl';
const irl = createIrl({ apiKey: process.env.THREE_WS_SESSION });
const { worldLine } = await irl.createWorldLine({
- pinId: 'your-pin-id', // the anchor — a pin you own
+ pinId: 'your-pin-id', // the anchor, a pin you own
title: 'Meet the courier',
prompt: 'Find me by the fountain and answer one question.',
challenge: { kind: 'quiz', question: 'What coin?', choices: ['$THREE', 'fiat'], answer: 0 },
@@ -359,7 +359,7 @@ const { worldLine } = await irl.createWorldLine({
| `verifyProof(proofId)` | `GET /world-lines/verify/:id` | Public re-check of the agent signature. |
The proof's canonical signed message carries only the quest id, a ~1.1 km
-coarse cell, the nonce, and a salted hash of the completer — never a
+coarse cell, the nonce, and a salted hash of the completer, never a
coordinate, never a raw device token. `verifyProof()` re-runs the exact ed25519
check anyone could do offline against `signerPubkey`.
@@ -393,12 +393,12 @@ Presence is the gate on every read. You can never query a point you aren't at:
- **Proof-of-presence math.** Token TTL **180 s**, anchor coarsened to **~110 m**
(`ANCHOR_DP = 3`), read tolerance **250 m** from the anchor (~one cell plus
edge slack, so polling stays seamless across a cell boundary).
-- **No fan-out.** A placement or edit is never broadcast as a roster — it reaches
+- **No fan-out.** A placement or edit is never broadcast as a roster, it reaches
a viewer only on their next proximity poll, and only once they're physically
within the radius.
- **Dev/preview.** Enforcement turns on only when `IRL_FIX_SECRET` (≥ 16 chars)
is set. Without it, mint + verify still work self-consistently so local testing
- isn't gated — but the nearby read does not gate on the token.
+ isn't gated: but the nearby read does not gate on the token.
## Errors & edge cases
@@ -407,7 +407,7 @@ Presence is the gate on every read. You can never query a point you aren't at:
| `code` | HTTP | Meaning | Recovery |
|---|---|---|---|
-| `fix_required` | 401 | Presence token missing/`expired`/`forged`/`out_of_area`. | Call `checkIn()` again — the fix lapsed or you moved. |
+| `fix_required` | 401 | Presence token missing/`expired`/`forged`/`out_of_area`. | Call `checkIn()` again, the fix lapsed or you moved. |
| `lat_lng_required` | 400 | No coordinates on a read or placement. | Provide `lat`/`lng`. |
| `invalid_coordinates` | 400 | Out-of-range lat/lng. | Send a real fix. |
| `area_full` | 429 | The ~150 m cell already holds 40 agents. | Place in another spot. |
@@ -416,16 +416,16 @@ Presence is the gate on every read. You can never query a point you aren't at:
| `content` | 422 | Caption/name blocked, or names a coin other than `$THREE`. | Reword. |
| `endpoint` | 422 | `x402Endpoint` host isn't first-party. | Use a three.ws pay target. |
| `not_found` | 404 | Pin gone (expired / hidden / not yours). | Refresh your list. |
-| `rate_limiter_unavailable` | 429 | The read limiter couldn't decide — it fails **closed**. | Retry shortly. |
+| `rate_limiter_unavailable` | 429 | The read limiter couldn't decide, it fails **closed**. | Retry shortly. |
Every state is designed. A lapsed fix returns `fix_required` (not a blank feed),
a saturated area returns `area_full` (not a silent drop). Surface them the same
-way in your UI — `fix_required` is the "Getting your location…" state, not an
+way in your UI: `fix_required` is the "Getting your location…" state, not an
error toast.
## Examples
-**Walk-up discovery loop (browser)** — re-check in when the cell changes:
+**Walk-up discovery loop (browser)**: re-check in when the cell changes:
```js
import { checkIn, nearby } from '@three-ws/irl';
@@ -439,7 +439,7 @@ setInterval(async () => {
}, 10_000); // ~6 reads/min, well under the 60/min ceiling
```
-**Place a Forge-made avatar where you stand** — full chain:
+**Place a Forge-made avatar where you stand**: full chain:
```js
import { forge } from '@three-ws/forge';
@@ -455,7 +455,7 @@ const { pin } = await placePin({
});
```
-**Anonymous, no login** — manage pins by device token:
+**Anonymous, no login**: manage pins by device token:
```js
import { configure, placePin, myPins, purgePins } from '@three-ws/irl';
@@ -468,9 +468,9 @@ await purgePins(); // wipe every pin from this device
## Related
-- [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge) — generate the avatar you place.
-- [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar) — render and animate a discovered pin's GLB.
-- [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch) — pay an agent's `x402_endpoint` in USDC.
+- [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge), generate the avatar you place.
+- [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar), render and animate a discovered pin's GLB.
+- [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch), pay an agent's `x402_endpoint` in USDC.
---
diff --git a/packages/mocap/README.md b/packages/mocap/README.md
index bf660892b..02ce053aa 100644
--- a/packages/mocap/README.md
+++ b/packages/mocap/README.md
@@ -4,7 +4,7 @@
<h1 align="center">@three-ws/mocap</h1>
-<p align="center"><strong>Motion capture as an API — turn a webcam or video into face, pose, and hand animation clips you can replay on any avatar.</strong></p>
+<p align="center"><strong>Motion capture as an API, turn a webcam or video into face, pose, and hand animation clips you can replay on any avatar.</strong></p>
<p align="center">
<a href="https://www.npmjs.com/package/@three-ws/mocap"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/mocap?logo=npm&color=cb3837"></a>
@@ -23,30 +23,30 @@
---
-> `@three-ws/mocap` is the official client for the three.ws **mocap clip** store —
+> `@three-ws/mocap` is the official client for the three.ws **mocap clip** store -
> the library behind the in-browser mocap studio. Recording happens in the
> browser: MediaPipe Face Landmarker reads a webcam frame and emits 52 ARKit
> blendshapes plus a head-pose matrix per frame; the runtime smooths and packs
-> them into a portable clip. This package is the durable half — it saves that
+> them into a portable clip. This package is the durable half, it saves that
> clip, lists your library, makes clips public or for-sale, and hands any clip
> back so you can replay it on a different avatar. It wraps the auth'd
> `/api/mocap/clips` endpoints. It pairs with
> [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar) and
-> [`@three-ws/walk`](https://www.npmjs.com/package/@three-ws/walk) — those *render*
+> [`@three-ws/walk`](https://www.npmjs.com/package/@three-ws/walk), those *render*
> the avatar, `@three-ws/mocap` *drives its face*.
## Why
-Facial mocap in the browser is solved math, but the boring half — persisting a
+Facial mocap in the browser is solved math, but the boring half, persisting a
recording, versioning the wire format, sharing it, replaying it on a *different*
-rig — is where projects stall. A blendshape buffer in memory is gone the moment
+rig: is where projects stall. A blendshape buffer in memory is gone the moment
the tab closes. This package is that half, done once:
- **Capture once, replay anywhere.** A clip is rig-agnostic ARKit blendshapes,
not baked keyframes, so a face you recorded on one avatar plays on any avatar
that exposes ARKit morph targets.
- **Versioned wire format.** Every clip carries a format string
- (`three.ws.face-mocap.v1`). The runtime asserts on it before replay — a future
+ (`three.ws.face-mocap.v1`). The runtime asserts on it before replay, a future
v2 clip can't silently load on a v1 player and mangle the animation.
- **Library, sharing, marketplace.** Clips are private by default; flip one to
`public`, attach a `$THREE` price, and it's listed. One field, no new plumbing.
@@ -102,28 +102,28 @@ cookie or a bearer token with the right scope; reads of public clips are open.
Persist a browser recording. Wraps `POST /api/mocap/clips`. The `recording` is
passed through as the `clip` field; `meta` supplies the library metadata.
-**`recording`** — the object the capture runtime returns:
+**`recording`**: the object the capture runtime returns:
| Field | Type | Notes |
|---|---|---|
| `format` | `string` | One of the [supported formats](#how-it-works). Asserted server-side. |
-| `duration` | `number` | Seconds, `0`–`3600`. Stored as `duration_ms`. |
+| `duration` | `number` | Seconds, `0`-`3600`. Stored as `duration_ms`. |
| `frames` | `Frame[]` | `{ t, shapes, mat? }` per frame. Max **18,000** frames, **2 MB** inline. |
A `Frame` is `{ t: number, shapes: Record<string, number>, mat?: number[16] | null }`
-— `t` is seconds from clip start, `shapes` maps ARKit blendshape names to scores,
+- `t` is seconds from clip start, `shapes` maps ARKit blendshape names to scores,
`mat` is the optional 4×4 head-pose matrix.
**`meta`**
| Field | Type | Default | Notes |
|---|---|---|---|
-| `name` | `string` | — | **Required.** 1–120 chars. |
+| `name` | `string` | - | **Required.** 1-120 chars. |
| `slug` | `string` | auto from `name` | `^[a-z0-9][a-z0-9-]{0,79}$`, unique per owner. |
-| `description` | `string` | — | Up to 2000 chars. |
+| `description` | `string` | - | Up to 2000 chars. |
| `tags` | `string[]` | `[]` | Up to 20 tags, ≤40 chars each. |
| `visibility` | `'private' \| 'unlisted' \| 'public'` | `'private'` | |
-| `avatarId` | `uuid` | — | Bind the clip to one of your avatars. Must be owned by you. (`avatar_id` is accepted too.) |
+| `avatarId` | `uuid` | - | Bind the clip to one of your avatars. Must be owned by you. (`avatar_id` is accepted too.) |
Returns the created `Clip` (`201`). `kind` (`face` / `pose` / `hand` / `vmc`) is
derived from `format` server-side.
@@ -141,14 +141,14 @@ it. Pass the `id` when you need to name one exact clip.
### `listClips(auth, opts?) → Promise<{ items, nextCursor }>`
-List clips **without frames** (metadata only — cheap). Wraps
+List clips **without frames** (metadata only: cheap). Wraps
`GET /api/mocap/clips`. Cursor-paginated, newest first.
| Option | Type | Default | Notes |
|---|---|---|---|
-| `limit` | `number` | `50` | Clamped to `1`–`100`. |
-| `cursor` | `string` | — | `nextCursor` from the previous page. |
-| `kind` | `'face' \| 'pose' \| 'hand' \| 'vmc'` | — | Filter by clip kind. |
+| `limit` | `number` | `50` | Clamped to `1`-`100`. |
+| `cursor` | `string` | - | `nextCursor` from the previous page. |
+| `kind` | `'face' \| 'pose' \| 'hand' \| 'vmc'` | - | Filter by clip kind. |
| `includePublic` | `boolean` | `false` | Authed: union your clips with the public pool. |
With no `auth`, you get the public pool only. With `auth`, you get your own
@@ -189,7 +189,7 @@ camelCases the wire row and keeps the untouched original on `raw`:
## How it works
Capture is client-side and free; persistence is this API. The clip is the
-contract between them — a portable, versioned blendshape buffer:
+contract between them: a portable, versioned blendshape buffer:
```
webcam / video frame
@@ -213,7 +213,7 @@ contract between them — a portable, versioned blendshape buffer:
FaceMocap.play(clip) on ANY ARKit avatar ← @three-ws/avatar / @three-ws/walk
```
-Because a clip is rig-agnostic ARKit blendshapes — not baked bone keyframes —
+Because a clip is rig-agnostic ARKit blendshapes: not baked bone keyframes -
the same recording replays on any avatar that exposes ARKit morph targets. The
`format` string carries the version; the runtime refuses a clip whose format it
doesn't speak rather than mangling the animation.
@@ -249,7 +249,7 @@ SDK surfaces them as a typed `ThreeWsError` carrying the `code`:
| `db_error` | 500 | List query failed. | Retry. |
Every state is designed: a `private` clip you don't own returns `404`, not its
-contents — non-owners can't even confirm it exists. Mirror that in your UI.
+contents: non-owners can't even confirm it exists. Mirror that in your UI.
## Examples
@@ -294,10 +294,10 @@ do {
## Related
-- [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar) — render the avatar a mocap clip drives.
-- [`@three-ws/walk`](https://www.npmjs.com/package/@three-ws/walk) — a rigged avatar as a page companion you can face-animate.
-- [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge) — generate the ARKit avatar to replay clips on.
-- [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch) — settle payments for priced clips.
+- [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar), render the avatar a mocap clip drives.
+- [`@three-ws/walk`](https://www.npmjs.com/package/@three-ws/walk), a rigged avatar as a page companion you can face-animate.
+- [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge), generate the ARKit avatar to replay clips on.
+- [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch), settle payments for priced clips.
---
diff --git a/packages/names/README.md b/packages/names/README.md
index f02d33267..b289eee20 100644
--- a/packages/names/README.md
+++ b/packages/names/README.md
@@ -4,7 +4,7 @@
<h1 align="center">@three-ws/names</h1>
-<p align="center"><strong>ENS + SNS resolution, <code>*.threews.sol</code> subdomain minting, and pay-by-name — agent identity in one import.</strong></p>
+<p align="center"><strong>ENS + SNS resolution, <code>*.threews.sol</code> subdomain minting, and pay-by-name, agent identity in one import.</strong></p>
<p align="center">
<a href="https://www.npmjs.com/package/@three-ws/names"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/names?logo=npm&color=cb3837"></a>
@@ -23,7 +23,7 @@
---
-> `@three-ws/names` is the official client for the three.ws **naming layer** —
+> `@three-ws/names` is the official client for the three.ws **naming layer** -
> the identity plumbing behind every agent on the platform. It resolves
> human-readable names to on-chain addresses across **ENS** (Ethereum) and
> **SNS** (Solana), mints `<label>.threews.sol` subdomains under the
@@ -40,14 +40,14 @@ A wallet address is unusable as an identity. Nobody types
have to. The naming layer turns identity into a string:
- **Resolve in one call.** `resolve('vitalik.eth')` and `resolve('bonfida.sol')`
- hit the right registry automatically — ENS via an Ethereum RPC with failover,
- SNS via Bonfida — and a bare label is tried against both.
+ hit the right registry automatically: ENS via an Ethereum RPC with failover,
+ SNS via Bonfida: and a bare label is tried against both.
- **Mint a name your agent owns.** `mintSubdomain('alice')` registers
`alice.threews.sol` on-chain, writes a Brave-resolvable URL record, and
- transfers ownership to the agent's wallet — all in one signed transaction.
+ transfers ownership to the agent's wallet: all in one signed transaction.
The platform absorbs the gas; the agent's wallet never signs.
- **Pay by name.** `payByName('alice.threews.sol', '5')` resolves the recipient
- and builds (or sends) a USDC transfer — handles, `.sol` domains, and raw
+ and builds (or sends) a USDC transfer: handles, `.sol` domains, and raw
addresses all route through the same call, with a recipient-poisoning guard.
Hand-rolling this means three different on-chain SDKs (Bonfida SNS, ethers, SPL
@@ -55,7 +55,7 @@ token), RPC failover, label validation, an availability denylist, and a
preview-then-send flow that survives a name being re-pointed mid-flight. This
package is that, done once.
-This is the SDK twin of the [`ens_sns_resolve` MCP tool](https://three.ws/mcp) —
+This is the SDK twin of the [`ens_sns_resolve` MCP tool](https://three.ws/mcp) -
the same resolution engine, exposed as plain functions instead of an MCP tool.
## Install
@@ -66,7 +66,7 @@ npm install @three-ws/names
Zero runtime dependencies. Works in Node 18+ and the browser (uses `fetch`).
Minting and `mode: 'send'` payments require a signed-in three.ws session or a
-bearer token. The browser `prep` lane needs no auth — it returns an unsigned
+bearer token. The browser `prep` lane needs no auth, it returns an unsigned
transaction for a wallet to sign.
## Quick start
@@ -96,7 +96,7 @@ import { mintSubdomain, payByName } from '@three-ws/names';
// Registers alice.threews.sol on-chain, transfers it to the agent's wallet.
const { fullName, signature } = await mintSubdomain({
agentId: 'agt_7Yq…',
- label: 'alice', // optional — defaults to the agent's slugified name
+ label: 'alice', // optional: defaults to the agent's slugified name
token: process.env.THREEWS_TOKEN,
});
console.log(fullName); // → alice.threews.sol
@@ -121,7 +121,7 @@ label (`vitalik`) is tried against the `.sol` registry. Wraps
| Option | Type | Default | Notes |
|---|---|---|---|
| `domains` | `boolean` | `false` | (SNS) also return every `.sol` the owner holds and their favorite domain. Off by default: it adds two SNS-index lookups the address resolution itself does not need. |
-| `signal` | `AbortSignal` | — | Cancel the request. |
+| `signal` | `AbortSignal` | - | Cancel the request. |
**Returns** `ResolveResult`
@@ -136,7 +136,7 @@ label (`vitalik`) is tried against the `.sol` registry. Wraps
| `domainsTruncated` | `boolean` | `true` when the owner holds more than the 100 names returned. |
| `raw` | `unknown` | The untouched wire envelope. |
-A `.sol` miss returns `200` with `resolved: false` — the reverse-lookup that
+A `.sol` miss returns `200` with `resolved: false`, the reverse-lookup that
runs on every page load makes "no domain" an expected answer, so it is never a
`404`. Malformed input is a `400`.
@@ -165,7 +165,7 @@ Check whether `<label>.threews.sol` is free. Wraps
### `mintSubdomain(input) → Promise<MintResult>`
Mint `<label>.threews.sol`, write its Brave URL record, and transfer ownership
-to a wallet — atomically, in one platform-signed transaction. Wraps
+to a wallet: atomically, in one platform-signed transaction. Wraps
`POST /api/sns-subdomain`. Requires auth.
**Input**
@@ -173,9 +173,9 @@ to a wallet — atomically, in one platform-signed transaction. Wraps
| Field | Type | Notes |
|---|---|---|
| `agentId` | `string` | **Required.** The agent the subdomain attaches to. |
-| `label` | `string` | Optional. Defaults to the agent's slugified name. 1–63 chars `[a-z0-9-]`. |
+| `label` | `string` | Optional. Defaults to the agent's slugified name. 1-63 chars `[a-z0-9-]`. |
| `ownerAddress` | `string` | Optional base58 wallet to receive ownership. Must be **linked to your account**. Defaults to the agent's own Solana wallet. |
-| `space` | `number` | Optional, 1000–10000. Registry bytes reserved. Default `2000`. |
+| `space` | `number` | Optional, 1000-10000. Registry bytes reserved. Default `2000`. |
| `token` | `string` | Bearer token (or rely on a session cookie). |
**Returns** `MintResult`: `{ ok, agentId, fullName, parent, owner, signature, explorer, urlRecord, agentUrl }` (the untouched wire body stays on `raw`). The new subdomain's URL record points at
@@ -189,7 +189,7 @@ manifests can show `recipient_name` without an extra round-trip.
Claim `<username>.threews.sol` for the signed-in user, with its URL record set
to `https://three.ws/u/<username>`. Wraps `POST /api/threews/subdomain`. The
-`label` **must equal your account username** — divergent labels would let users
+`label` **must equal your account username**: divergent labels would let users
impersonate other handles. Pass `ownerWallet` (linked to your account) or fall
back to your default agent's Solana wallet. `releaseSubdomain(label)` wraps the
`DELETE` route to drop the local claim (on-chain ownership is unchanged).
@@ -206,13 +206,13 @@ agent wallet; **`.sol` domain** (including `foo.threews.sol`) → on-chain owner
| Option | Type | Default | Notes |
|---|---|---|---|
| `mode` | `'prep' \| 'send'` | `'prep'` | `prep` returns an unsigned tx; `send` has the agent sign and broadcast. |
-| `payerWallet` | `string` | — | **Required for `prep`.** Base58 fee-payer + source. |
-| `agentId` | `string` | — | **Required for `send`.** The agent that signs (must be yours). |
-| `expectedAddress` | `string` | — | (`send`) the address you previewed. If the name now resolves elsewhere, the call rejects with `recipient_changed` before signing. |
-| `message` | `string` | — | Optional memo. |
-| `token` | `string` | — | Bearer token for `send`. |
+| `payerWallet` | `string` | - | **Required for `prep`.** Base58 fee-payer + source. |
+| `agentId` | `string` | - | **Required for `send`.** The agent that signs (must be yours). |
+| `expectedAddress` | `string` | - | (`send`) the address you previewed. If the name now resolves elsewhere, the call rejects with `recipient_changed` before signing. |
+| `message` | `string` | - | Optional memo. |
+| `token` | `string` | - | Bearer token for `send`. |
-**Returns (`prep`)** `{ mode: 'prep', recipient, amountUsdc, txBase64, blockhash, lastValidBlockHeight, mint }` — decode `txBase64` into a `VersionedTransaction`, sign with the payer wallet, and submit. **Returns (`send`)** `{ mode: 'send', recipient, payer, amountUsdc, signature }`. The `amountUsdc` argument accepts a string or number, must be `> 0` and `≤ 10000`.
+**Returns (`prep`)** `{ mode: 'prep', recipient, amountUsdc, txBase64, blockhash, lastValidBlockHeight, mint }`, decode `txBase64` into a `VersionedTransaction`, sign with the payer wallet, and submit. **Returns (`send`)** `{ mode: 'send', recipient, payer, amountUsdc, signature }`. The `amountUsdc` argument accepts a string or number, must be `> 0` and `≤ 10000`.
### `resolvePayee(name) → Promise<Payee>`
@@ -255,7 +255,7 @@ string you pass:
record while the platform still owns it (so `<label>.threews.sol` resolves in
Brave) → `transferSubdomain` hands it to the agent's wallet. The platform's
parent-owner keypair (`THREEWS_SOL_PARENT_SECRET_BASE58`) is the only signer
- and fee payer — gas is under 0.01 SOL and absorbed, so the agent's wallet
+ and fee payer: gas is under 0.01 SOL and absorbed, so the agent's wallet
never has to sign.
- **Pay-by-name** uses the USDC mint (`EPjFWdd5AufqSSqeM2qN1xzybapC8G4wEGGkZwyTDt1v`,
6 decimals), creating the recipient's associated token account idempotently.
@@ -264,11 +264,11 @@ string you pass:
### Environment
-`THREEWS_SOL_PARENT_SECRET_BASE58` — the base58-encoded 64-byte ed25519 secret
+`THREEWS_SOL_PARENT_SECRET_BASE58`: the base58-encoded 64-byte ed25519 secret
for the wallet that owns the parent `.sol` (default `threews.sol`, overridable
with `THREEWS_SOL_PARENT_DOMAIN`). This is **server-side only**; it gates all
subdomain minting. When it is absent the mint endpoints answer `503`
-`config_missing` rather than failing mid-transaction — the SDK surfaces that as
+`config_missing` rather than failing mid-transaction, the SDK surfaces that as
a clean error, never a fake success.
## Pricing / payment
@@ -276,9 +276,9 @@ a clean error, never a fake success.
| Action | Cost |
|---|---|
| `resolve`, `reverseLookup`, `checkSubdomain`, `resolvePayee` | **Free.** Public, rate-limited per IP. |
-| `mintSubdomain`, `claimSubdomain` | **Free** to the caller — the platform absorbs the sub-0.01-SOL gas. Requires auth. |
+| `mintSubdomain`, `claimSubdomain` | **Free** to the caller, the platform absorbs the sub-0.01-SOL gas. Requires auth. |
| `payByName` | The transferred USDC amount, plus Solana network fees. |
-| [`ens_sns_resolve` MCP tool](https://three.ws/mcp) | **$0.0005 USDC** over x402 — the metered equivalent of `resolve`. |
+| [`ens_sns_resolve` MCP tool](https://three.ws/mcp) | **$0.0005 USDC** over x402, the metered equivalent of `resolve`. |
`.sol` reads are cached server-side (5 min positive, 60 s negative), and ENS
resolutions are cached 5 min in-memory, so repeated UX previews don't hammer the
@@ -292,7 +292,7 @@ real faults reject.
| State | HTTP | Meaning | Recovery |
|---|---|---|---|
| `resolved: false` | 200 | Name has no owner. **Not an error.** | Show "unclaimed"; offer to mint. |
-| `validation_error` | 400 | Malformed name, label, or amount. | Fix the input. Labels are 1–63 chars `[a-z0-9-]`. |
+| `validation_error` | 400 | Malformed name, label, or amount. | Fix the input. Labels are 1-63 chars `[a-z0-9-]`. |
| `unauthorized` | 401 | Mint or `mode: 'send'` without auth. | Sign in or pass a bearer `token`. |
| `forbidden` | 403 | `ownerAddress` not linked to your account. | Link the wallet, or omit it. |
| `per_tx_exceeded` | 403 | Send over the agent's per-transaction limit. | Lower the amount or raise the agent's limit. |
@@ -306,7 +306,7 @@ real faults reject.
## Examples
-**Under the hood — resolve `.sol` with raw `fetch`** (what `resolve` wraps):
+**Under the hood: resolve `.sol` with raw `fetch`** (what `resolve` wraps):
```js
const r = await fetch('https://three.ws/api/sns?name=bonfida.sol');
@@ -314,7 +314,7 @@ const { data } = await r.json();
// → { name: 'bonfida.sol', address: '…', network: 'solana', resolved: true }
```
-**Agent identity, end to end** — give an agent a name, then receive a payment:
+**Agent identity, end to end**: give an agent a name, then receive a payment:
```js
import { mintSubdomain, resolvePayee } from '@three-ws/names';
@@ -326,7 +326,7 @@ const payee = await resolvePayee(fullName);
// → { name: 'oracle.threews.sol', address: '…', source: 'sns', claim: … }
```
-**Browser pay-by-name** — build, sign in the wallet, submit:
+**Browser pay-by-name**: build, sign in the wallet, submit:
```js
import { payByName } from '@three-ws/names';
@@ -340,7 +340,7 @@ const signed = await wallet.signTransaction(tx);
const sig = await connection.sendRawTransaction(signed.serialize());
```
-**Agent-signed send** — the agent's custodial wallet pays, with a poisoning guard:
+**Agent-signed send**: the agent's custodial wallet pays, with a poisoning guard:
```js
const preview = await resolvePayee('alice.threews.sol');
@@ -354,9 +354,9 @@ const { signature } = await payByName('alice.threews.sol', '5', {
## Related
-- [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch) — auto-pay the `$0.0005` `ens_sns_resolve` MCP tool and other x402 lanes.
-- [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge) — generate the agent's 3D avatar to pair with its name.
-- [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar) — render the named agent's avatar in the browser.
+- [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch), auto-pay the `$0.0005` `ens_sns_resolve` MCP tool and other x402 lanes.
+- [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge), generate the agent's 3D avatar to pair with its name.
+- [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar), render the named agent's avatar in the browser.
---
diff --git a/packages/pumpfun-mcp/test/entrypoint.test.mjs b/packages/pumpfun-mcp/test/entrypoint.test.mjs
index d4ea5aaa0..694c33494 100644
--- a/packages/pumpfun-mcp/test/entrypoint.test.mjs
+++ b/packages/pumpfun-mcp/test/entrypoint.test.mjs
@@ -30,7 +30,7 @@ test('importing the entry point never connects a transport', async () => {
// loop alive forever. Asserted in a CHILD process: this test file has already
// imported the module, and the test runner touches stdin itself, so only a
// clean process can answer the question honestly. A regression here does not
- // fail an assertion, it hangs — hence the timeout.
+ // fail an assertion, it hangs: hence the timeout.
const { stdout, stderr } = await run(
process.execPath,
['-e', `import(${JSON.stringify(ENTRY)}).then(() => { console.log(process.stdin.listenerCount('data')); });`],
diff --git a/packages/vanity/README.md b/packages/vanity/README.md
index a4ccb2701..abafa9d06 100644
--- a/packages/vanity/README.md
+++ b/packages/vanity/README.md
@@ -94,7 +94,7 @@ import { Keypair } from '@solana/web3.js';
const wallet = Keypair.fromSecretKey(secretKey);
```
-A fuller run — suffix, case-insensitive, live progress + ETA, cancellable:
+A fuller run: suffix, case-insensitive, live progress + ETA, cancellable:
```js
import { grind, expectedAttempts } from '@three-ws/vanity';
@@ -138,7 +138,7 @@ wall-clock cadence. Rejects with `AbortError` if `signal` aborts.
At least one of `prefix` / `suffix` is required. Both are validated against the
Base58 alphabet (`0 O I l` excluded) and a 6-char-per-pattern ceiling before any
-work starts — an invalid pattern rejects immediately with a specific message.
+work starts: an invalid pattern rejects immediately with a specific message.
**Returns** `GrindResult`
@@ -160,7 +160,7 @@ work starts — an invalid pattern rejects immediately with a specific message.
### `expectedAttempts({ prefix?, suffix?, ignoreCase? }) → number`
-The mean of the geometric distribution — `58^n` adjusted for case-insensitivity
+The mean of the geometric distribution: `58^n` adjusted for case-insensitivity
per character. Use it to gate a pattern before grinding (e.g. warn past a
threshold).
@@ -168,9 +168,9 @@ threshold).
Validate a single prefix or suffix against the Base58 alphabet and length ceiling.
Returns specific, user-facing error strings (e.g. `invalid character 'O'
-(uppercase o) — use other uppercase letters`).
+(uppercase o): use other uppercase letters`).
-### `grindViaApi(options) → Promise<ApiResult>` — the paid lane
+### `grindViaApi(options) → Promise<ApiResult>`: the paid lane
For environments that can't grind locally, grind a short pattern over the hosted
[x402](https://x402.org) endpoint instead of locally. Wraps
@@ -183,7 +183,7 @@ x402-capable `fetch` to settle the 402 automatically.
| `ignoreCase` | `boolean` | Case-insensitive match. |
| `format` | `'keypair' \| 'mnemonic'` | `mnemonic` returns an importable BIP-39 phrase (≤ 2 chars, ~100× slower). |
| `strength` | `128 \| 256` | Mnemonic only: 12 or 24 words. |
-| `sealTo` | `string` | Optional X25519 public key — the secret is ECIES-sealed to you and the plaintext is omitted from the response. |
+| `sealTo` | `string` | Optional X25519 public key: the secret is ECIES-sealed to you and the plaintext is omitted from the response. |
| `fetch` | `typeof fetch` | An x402-wrapped fetch (see [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch)). Without one you get a `PaymentRequiredError` carrying the x402 challenge to settle yourself. |
| `baseUrl` | `string` | API origin. Defaults to `THREE_WS_BASE_URL` or `https://three.ws`. |
| `apiKey` | `string` | Sent as `Authorization: Bearer …`. Not required for the x402 lane. |
@@ -191,8 +191,8 @@ x402-capable `fetch` to settle the 402 automatically.
| `signal` | `AbortSignal` | Cancel the request. |
Response fields: `address`, `secretKeyBase58`, `secretKey` (64-int array),
-`attempts`, `durationMs`, `expectedAttempts`, `network`, `explorerUrl`, and —
-for `format=mnemonic` — `mnemonic`, `wordCount`, `derivationPath`.
+`attempts`, `durationMs`, `expectedAttempts`, `network`, `explorerUrl`, and -
+for `format=mnemonic`: `mnemonic`, `wordCount`, `derivationPath`.
### `createVanity(options?) → VanityClient`
@@ -215,7 +215,7 @@ const { address } = await vanity.grindViaApi({ prefix: 'ag' });
| `base58Encode(bytes)` | Base58 (Solana address) encoder for a `Uint8Array` / number array. Zero deps. |
| `BASE58_ALPHABET` | The 58-character alphabet (excludes the confusable `0 O I l`). |
| `MAX_PATTERN_LENGTH` | The per-pattern ceiling `validatePattern` and `grind` enforce (`6`). |
-| `DEFAULT_BASE_URL` | `https://three.ws` — the origin the hosted lane uses unless overridden. |
+| `DEFAULT_BASE_URL` | `https://three.ws`: the origin the hosted lane uses unless overridden. |
| `ThreeWsError` / `PaymentRequiredError` | Typed errors (`code`, `status`, and `accepts` for the x402 challenge). |
## How it works
@@ -269,7 +269,7 @@ This is the part that matters for a secret-key tool.
grinds a brand-new keypair per call and returns it once over TLS; it is never
written to disk and is stripped from the idempotency cache. Because that
secret transits the network, prefer `sealTo` (ECIES-seal it to your X25519
- key so the plaintext never appears in the response or any proxy log) — or just
+ key so the plaintext never appears in the response or any proxy log), or just
grind locally.
- **MCP responses can be logged.** The `vanity_grinder` MCP tool returns a real,
spendable secret in plaintext over the MCP channel, which the host (Claude
@@ -279,7 +279,7 @@ This is the part that matters for a secret-key tool.
## Pricing
-The local `grind()` path is free and unlimited — it's your CPU. Pricing only
+The local `grind()` path is free and unlimited: it's your CPU. Pricing only
applies to the paid `grindViaApi()` HTTP lane, which is difficulty-tiered
(each Base58 character multiplies expected work by ~58):
@@ -287,13 +287,13 @@ applies to the paid `grindViaApi()` HTTP lane, which is difficulty-tiered
|---|---|---|
| 1 | **$0.01** | **$0.05** |
| 2 | **$0.05** | **$0.50** |
-| 3 | **$0.25** | — (capped at 2) |
+| 3 | **$0.25** |: (capped at 2) |
A [provably-fair lane](https://three.ws/vanity/verify) (`GET
-/api/x402/vanity-verifiable`, $0.02–$0.40) grinds under a commit–reveal protocol
+/api/x402/vanity-verifiable`, $0.02-$0.40) grinds under a commit-reveal protocol
and returns a signed receipt you can verify entirely client-side. Settlement
runs only **after** a successful grind, so an exhausted budget costs nothing and
-can be retried. Pay per call in USDC on Base or Solana mainnet — no API keys, no
+can be retried. Pay per call in USDC on Base or Solana mainnet, no API keys, no
accounts. Pair with [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch)
to automate the 402.
@@ -315,7 +315,7 @@ The paid `grindViaApi()` path surfaces the endpoint's HTTP errors:
|---|---|---|---|
| `validation_error` | 400 | Bad pattern, format, or strength. | Fix the input. |
| `pattern_too_long` | 400 | Combined pattern over the mnemonic cap of 2. (A combined pattern over 3 never leaves the process: the SDK rejects it locally as `invalid_input`.) | Grind locally with `grind()`. |
-| `grind_exhausted` | 504 | Time budget elapsed without a hit (rare, <1% at 3 chars). | Retry — you weren't charged. |
+| `grind_exhausted` | 504 | Time budget elapsed without a hit (rare, <1% at 3 chars). | Retry, you weren't charged. |
| `rate_limited` | 429 | Pre-payment probe rate limit. | Honour `retry-after`. |
Long patterns are designed, not crashed: the server tells you to grind them
@@ -323,7 +323,7 @@ locally with `grind()`, where the only cap is the 6-char-per-pattern ceiling.
## Examples
-**Node — grind, then write a Solana CLI keypair file:**
+**Node: grind, then write a Solana CLI keypair file:**
```js
import { grind } from '@three-ws/vanity';
@@ -334,7 +334,7 @@ writeFileSync(`${publicKey}.json`, JSON.stringify(Array.from(secretKey)));
// → solana config set --keypair ./<address>.json
```
-**Browser — cancel a long grind from the UI:**
+**Browser: cancel a long grind from the UI:**
```js
import { grind } from '@three-ws/vanity';
@@ -347,7 +347,7 @@ document.querySelector('#stop').onclick = () => controller.abort();
const { publicKey, secretKey } = await job; // rejects with AbortError on stop
```
-**Agent — the free MCP tool, no toolchain:**
+**Agent: the free MCP tool, no toolchain:**
```js
// The same capability ships as the `vanity_grinder` MCP tool on the
@@ -363,9 +363,9 @@ const { address, secretKeyBase58 } = await grindViaApi({
## Related
-- [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch) — auto-pay the 402 on the hosted grinder.
-- [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge) — text/image → rig-ready 3D GLB, the same SDK pattern.
-- [`@three-ws/pumpfun-mcp`](https://www.npmjs.com/package/@three-ws/pumpfun-mcp) — launch a token to a vanity mint you ground here.
+- [`@three-ws/x402-fetch`](https://www.npmjs.com/package/@three-ws/x402-fetch), auto-pay the 402 on the hosted grinder.
+- [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge), text/image → rig-ready 3D GLB, the same SDK pattern.
+- [`@three-ws/pumpfun-mcp`](https://www.npmjs.com/package/@three-ws/pumpfun-mcp), launch a token to a vanity mint you ground here.
---
diff --git a/packages/vanity/test/vanity.test.js b/packages/vanity/test/vanity.test.js
index 4993b101a..c0d3ce37e 100644
--- a/packages/vanity/test/vanity.test.js
+++ b/packages/vanity/test/vanity.test.js
@@ -12,7 +12,7 @@ import {
} from '../src/index.js';
// A scripted fetch double: each call shifts the next queued response and records
-// the request. No network, no real endpoints — we assert on request shaping and
+// the request. No network, no real endpoints: we assert on request shaping and
// response parsing, which is all the SDK is responsible for.
function stubFetch(responses) {
const calls = [];
@@ -186,7 +186,7 @@ test('the default grindViaApi export is wired to a shared client', () => {
test('the standalone grindViaApi honours a per-call fetch and baseUrl', async () => {
// The paid lane needs an x402-wrapped fetch, so a `fetch` passed straight to
- // the standalone export must actually be used — falling back to the global
+ // the standalone export must actually be used: falling back to the global
// one would send the call out unpaid and 402.
const { fetch, calls } = stubFetch([{ body: { address: 'THREEsynthetic1111', network: 'solana' } }]);
const res = await grindViaApi({ prefix: 'a', fetch, baseUrl: 'https://preview.three.ws' });
diff --git a/packages/voice/README.md b/packages/voice/README.md
index a0687eec4..2b5d54143 100644
--- a/packages/voice/README.md
+++ b/packages/voice/README.md
@@ -4,7 +4,7 @@
<h1 align="center">@three-ws/voice</h1>
-<p align="center"><strong>Give your avatar a voice — speech in, speech out, and lips that move. ASR, TTS, and Audio2Face lipsync in one import.</strong></p>
+<p align="center"><strong>Give your avatar a voice, speech in, speech out, and lips that move. ASR, TTS, and Audio2Face lipsync in one import.</strong></p>
<p align="center">
<a href="https://www.npmjs.com/package/@three-ws/voice"><img alt="npm" src="https://img.shields.io/npm/v/@three-ws/voice?logo=npm&color=cb3837"></a>
@@ -23,7 +23,7 @@
---
-> `@three-ws/voice` is the official client for the three.ws **voice loop** — the
+> `@three-ws/voice` is the official client for the three.ws **voice loop**, the
> three endpoints that let an avatar hear, speak, and move its face in sync.
> `transcribe()` turns spoken audio into text (NVIDIA Riva ASR), `speak()` turns
> text into a voiced clip (NVIDIA Magpie TTS, ElevenLabs for cloned voices), and
@@ -31,7 +31,7 @@
> Audio2Face-3D) that drives the avatar's mouth and face. It wraps the live,
> auth-free `/api/asr`, `/api/tts/speak`, and `/api/a2f` endpoints. The visemes
> it produces are exactly what [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar)
-> plays back on a loaded GLB — this is the voice half of a talking avatar.
+> plays back on a loaded GLB: this is the voice half of a talking avatar.
## Why
@@ -45,14 +45,14 @@ ordering, and three sets of rate limits.
`@three-ws/voice` is that loop, done once:
- **One import, the whole loop.** `transcribe(audio)`, `speak(text)`,
- `lipsync(audio)` — hear, speak, and animate the face from three plain calls.
+ `lipsync(audio)`: hear, speak, and animate the face from three plain calls.
- **Free first.** All three lanes lead with NVIDIA NIM (Riva, Magpie,
- Audio2Face-3D) — no key, no wallet, no card on the free path.
+ Audio2Face-3D): no key, no wallet, no card on the free path.
- **Cross-browser by default.** Server-side Riva recognition replaces the
Chrome/Edge-only `window.webkitSpeechRecognition`, so voice input works in
Firefox and inside embeds too.
- **Lips that match the exact bytes.** `lipsync()` returns time-coded ARKit
- weights for the precise clip you'll play — drop them straight into
+ weights for the precise clip you'll play: drop them straight into
[`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar).
Every lane is purely additive on the platform: when a provider isn't configured,
@@ -79,7 +79,7 @@ const clip = await speak('Hi, I am your three.ws avatar.', { voice: 'nova' });
new Audio(clip.url).play(); // clip.url is an object URL for the synthesized audio
```
-The full loop — hear the user, answer, animate the face:
+The full loop: hear the user, answer, animate the face:
```js
import { transcribe, speak, lipsync } from '@three-ws/voice';
@@ -120,15 +120,15 @@ blob's MIME type (or `options.format`).
| `language` | `string` | `'en-US'` | BCP-47 language code. |
| `sampleRate` | `number` | `16000` | Required for raw `pcm`; WAV carries its own rate in the header. |
| `words` | `boolean` | `false` | Return word-level timestamps. |
-| `model` | `string` | — | Override the Riva model name. |
-| `signal` | `AbortSignal` | — | Cancel an in-flight request. |
+| `model` | `string` | - | Override the Riva model name. |
+| `signal` | `AbortSignal` | - | Cancel an in-flight request. |
**Returns** `Transcript`
| Field | Type | Notes |
|---|---|---|
| `text` | `string` | The recognized utterance. |
-| `confidence` | `number` | Mean confidence across results (0–1). |
+| `confidence` | `number` | Mean confidence across results (0-1). |
| `language` | `string` | Detected language code. |
| `model` | `string` | Model that produced the transcript. |
| `durationSec` | `number` | Seconds of audio processed. |
@@ -147,9 +147,9 @@ a ready-to-play object `url`.
| `voice` | `string` | `'nova'` | One of the [voice catalog](#voices) ids. |
| `format` | `'mp3' \| 'wav' \| 'opus' \| 'aac' \| 'flac' \| 'pcm'` | `'mp3'` | Output container. Magpie emits PCM, so non-`pcm` requests are served as WAV. |
| `language` | `string` | `'en-US'` | BCP-47 language code. |
-| `speed` | `number` | `1.0` | Clamped to 0.5–2.0 (paid backstop only). |
-| `model` | `string` | — | `tts-1`, `tts-1-hd`, or `gpt-4o-mini-tts` (backstop). |
-| `signal` | `AbortSignal` | — | Cancel an in-flight request. |
+| `speed` | `number` | `1.0` | Clamped to 0.5-2.0 (paid backstop only). |
+| `model` | `string` | - | `tts-1`, `tts-1-hd`, or `gpt-4o-mini-tts` (backstop). |
+| `signal` | `AbortSignal` | - | Cancel an in-flight request. |
**Returns** `Clip`: `{ blob, url, contentType, voice, format, model }`. The
`x-tts-voice` / `x-tts-model` / `x-tts-format` response headers always describe
@@ -170,7 +170,7 @@ audio and sample the track by the audio element's `currentTime`.
|---|---|---|
| `fps` | `number` | Frame cadence (30 fps native). |
| `blendShapeNames` | `string[]` | ARKit-52 names, the order `frames[i].w` follows. |
-| `frames` | `{ t, w }[]` | `t` = seconds from start, `w` = weights (0–1) in `blendShapeNames` order. |
+| `frames` | `{ t, w }[]` | `t` = seconds from start, `w` = weights (0-1) in `blendShapeNames` order. |
| `frameCount` | `number` | Number of frames. |
| `durationSec` | `number` | Clip length in seconds. |
@@ -180,11 +180,11 @@ One-shot text → speech → face. Wraps `POST /api/a2f` with `{ text, voice,
language }`: the server synthesizes with Magpie, animates that exact clip, and
returns both. `audio` is `{ url, blob, contentType, format, voiceName }`;
`animation` is the same shape as `FaceTrack`. Use this when latency matters more
-than picking your own TTS — one round trip instead of two.
+than picking your own TTS: one round trip instead of two.
### `voices() → Promise<VoiceCatalog>`
-Fetch the live voice catalog (`GET /api/tts/voices`) — ids, names, descriptions,
+Fetch the live voice catalog (`GET /api/tts/voices`), ids, names, descriptions,
which synthesis lanes are configured. Render a picker before the user commits.
### Capability probes: `asrInfo()` / `lipsyncInfo()`
@@ -203,7 +203,7 @@ const face = await lipsyncInfo(); // GET /api/a2f
```
`configured: false` means that lane's provider key isn't set on the deployment,
-so the call would raise `not_configured` — render the in-browser fallback
+so the call would raise `not_configured`: render the in-browser fallback
instead. `raw` carries the untouched endpoint response for anything not shaped
above.
@@ -257,13 +257,13 @@ Three NVIDIA NIM models on one face, closing the loop user → avatar → user:
{ fps, blendShapeNames, frames:[{t,w}] } (lips move)
```
-- **ASR** — Riva offline `Recognize` over NVCF gRPC. Browsers can't all produce
+- **ASR**: Riva offline `Recognize` over NVCF gRPC. Browsers can't all produce
the same codec, so the cross-browser default is raw 16-bit PCM (or WAV, whose
header is parsed to LINEAR_PCM). Needs `NVIDIA_API_KEY` + `NVIDIA_ASR_FUNCTION_ID`.
-- **TTS** — Magpie leads (free, gRPC); OpenAI `/v1/audio/speech` is the paid
+- **TTS**: Magpie leads (free, gRPC); OpenAI `/v1/audio/speech` is the paid
last-resort backstop. The clip is fully buffered before a byte ships, so a
Magpie failure fails over cleanly.
-- **Lipsync** — Audio2Face-3D bidirectional streaming. Audio is downmixed to
+- **Lipsync**: Audio2Face-3D bidirectional streaming. Audio is downmixed to
mono and resampled to 16 kHz, then streamed; the server streams back the
ordered ARKit names followed by per-frame weights at 30 fps. Works out of the
box with just `NVIDIA_API_KEY` (a stable published model id; override with
@@ -277,7 +277,7 @@ Oculus), so the same track drives any avatar.
The three NVIDIA NIM lanes are **free** (credit-metered, no payment). The lanes
are metered to bound abuse: signed-in callers get a per-user budget, anonymous
-callers a tighter per-IP one — exceeding it returns `429`. The OpenAI TTS
+callers a tighter per-IP one: exceeding it returns `429`. The OpenAI TTS
backstop and ElevenLabs cloned voices are paid provider lanes used only when
configured; the free Magpie lane covers the default voices end to end.
@@ -299,7 +299,7 @@ endpoint's response:
Every state is designed: an unconfigured lane returns `not_configured` (not a
crash), so the client keeps its existing browser path. A2F's text path
-additionally needs Magpie TTS — without it, `say()` returns `not_configured` and
+additionally needs Magpie TTS: without it, `say()` returns `not_configured` and
you pass pre-synthesized audio to `lipsync()` instead.
## Examples
@@ -324,10 +324,10 @@ const el = document.createElement('audio');
el.src = audio.url;
el.play();
// sample `animation.frames` by el.currentTime and apply to the avatar's
-// morph targets — @three-ws/avatar does this mapping for you.
+// morph targets: @three-ws/avatar does this mapping for you.
```
-**Node — synthesize a narration clip to a file:**
+**Node: synthesize a narration clip to a file:**
```js
import { writeFile } from 'node:fs/promises';
@@ -337,7 +337,7 @@ const clip = await speak('The only coin is $THREE.', { voice: 'onyx', format: 'w
await writeFile('line.wav', Buffer.from(await clip.blob.arrayBuffer()));
```
-**Agent — caption an audio clip (word-level timestamps):**
+**Agent: caption an audio clip (word-level timestamps):**
```js
const { text, words } = await transcribe(clip, { words: true });
@@ -346,9 +346,9 @@ for (const w of words) console.log(`${(w.startMs / 1000).toFixed(2)}s ${w.word}
## Related
-- [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar) — render a GLB and play these visemes as real lipsync.
-- [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge) — generate and auto-rig the GLB this voice loop speaks through.
-- [`@three-ws/react`](https://www.npmjs.com/package/@three-ws/react) — React bindings for the three.ws avatar runtime.
+- [`@three-ws/avatar`](https://www.npmjs.com/package/@three-ws/avatar), render a GLB and play these visemes as real lipsync.
+- [`@three-ws/forge`](https://www.npmjs.com/package/@three-ws/forge), generate and auto-rig the GLB this voice loop speaks through.
+- [`@three-ws/react`](https://www.npmjs.com/package/@three-ws/react), React bindings for the three.ws avatar runtime.
---
diff --git a/packages/voice/examples/voice-loop.mjs b/packages/voice/examples/voice-loop.mjs
index 330260508..23999fd3a 100644
--- a/packages/voice/examples/voice-loop.mjs
+++ b/packages/voice/examples/voice-loop.mjs
@@ -1,9 +1,9 @@
// The whole voice loop against the live three.ws endpoints, in one run:
//
-// speak() text → a voiced clip (NVIDIA Magpie TTS)
-// lipsync() that clip → ARKit visemes (NVIDIA Audio2Face-3D)
-// transcribe() that clip → text again (NVIDIA Riva ASR)
-// say() text → voice + face in one round trip
+// speak turns text into a voiced clip (NVIDIA Magpie TTS)
+// lipsync turns that clip into ARKit visemes (NVIDIA Audio2Face-3D)
+// transcribe turns that clip back into text (NVIDIA Riva ASR)
+// say returns voice + face in one round trip
//
// Run: node examples/voice-loop.mjs
// TEXT="say this instead" node examples/voice-loop.mjs
diff --git a/packages/vscode-x402/src/scaffold-template.js b/packages/vscode-x402/src/scaffold-template.js
index 9e1dda1c7..91555a1ff 100644
--- a/packages/vscode-x402/src/scaffold-template.js
+++ b/packages/vscode-x402/src/scaffold-template.js
@@ -15,7 +15,7 @@
*/
export function renderEndpoint({ slug, priceUsd, description }) {
const priceAtomics = Math.round(Number(priceUsd) * 1e6);
- return `// ${slug} — paid x402 endpoint. Buyers pay USDC (Solana or Base); the call runs
+ return `// ${slug}: paid x402 endpoint. Buyers pay USDC (Solana or Base); the call runs
// only after settlement. Wired to the shared paidEndpoint() x402 dance.
//
// POST /api/x402/${slug}
diff --git a/tests/solana-rpc-rotating-fetch.test.js b/tests/solana-rpc-rotating-fetch.test.js
index 9dc32a31e..a21c3cb96 100644
--- a/tests/solana-rpc-rotating-fetch.test.js
+++ b/tests/solana-rpc-rotating-fetch.test.js
@@ -21,7 +21,7 @@ const VALID = { jsonrpc: '2.0', id: 1, result: { ok: true } };
// guards: every endpoint cooling from a prior request used to fall back to a raw,
// unvalidated `fetch(soonest)` whose `[]` / HTML / truncated body went straight to
// the browser, where web3.js choked with a StructError (or silently mis-read `[]`).
-describe('makeRotatingFetch — never leaks an unvalidated upstream body', () => {
+describe('makeRotatingFetch: never leaks an unvalidated upstream body', () => {
let origFetch;
beforeEach(() => {
origFetch = global.fetch;
@@ -37,7 +37,7 @@ describe('makeRotatingFetch — never leaks an unvalidated upstream body', () =>
expect((await out.json()).result).toEqual({ ok: true });
});
- it('throws instead of returning `[]` when every endpoint yields garbage — even once all are cooling', async () => {
+ it('throws instead of returning `[]` when every endpoint yields garbage, even once all are cooling', async () => {
const eps = ['https://leak-b1.test/', 'https://leak-b2.test/'];
global.fetch = vi.fn(async () => resp('[]'));
const rf = makeRotatingFetch(eps);
@@ -45,7 +45,7 @@ describe('makeRotatingFetch — never leaks an unvalidated upstream body', () =>
await expect(rf(null, { method: 'POST', body: '{}' })).rejects.toThrow();
// Second request: both already cooling. The old code did a raw fetch(soonest)
// and returned the `[]`; the fixed code validates the all-cooling pass and
- // still throws — the caller never sees an empty array.
+ // still throws: the caller never sees an empty array.
await expect(rf(null, { method: 'POST', body: '{}' })).rejects.toThrow();
});
@@ -68,13 +68,13 @@ describe('makeRotatingFetch — never leaks an unvalidated upstream body', () =>
global.fetch = fetchSpy;
const out = await makeRotatingFetch(eps)(null, { method: 'POST', body: '{}' });
expect((await out.json()).result).toEqual({ ok: true });
- // First healthy endpoint answers — no failover round-trips.
+ // First healthy endpoint answers: no failover round-trips.
expect(fetchSpy).toHaveBeenCalledTimes(1);
});
// A keyless lane that gates a method behind its paid/registered tier answers 200
- // with a method-shaped JSON-RPC error. It is provider-specific — the next lane
- // serves the call — so it must rotate rather than surface. Production symptom:
+ // with a method-shaped JSON-RPC error. It is provider-specific (the next lane
+ // serves the call), so it must rotate rather than surface. Production symptom:
// the ring leak scanner's getSignaturesForAddress and the balance reader's
// getBalance both hard-failed whenever rotation cascaded onto Tatum.
// -16401 is the code Tatum actually returns (verified live against
@@ -181,7 +181,7 @@ describe('provider daily-limit (-32003 / "request limit reached")', () => {
// web3.js sends getTransactions/getParsedTransactions as ONE JSON-RPC array of N
// getTransaction calls. PublicNode caps that at 1 per batch and rejects the whole
// array with HTTP 400 + -32600 "Maximum number of 'getTransaction' calls in a
-// batch request is 1" — a plain 4xx, which shouldRotate deliberately treats as a
+// batch request is 1": a plain 4xx, which shouldRotate deliberately treats as a
// caller error and surfaces as-is. Left unclassified it hard-failed every batched
// read on that lane while single calls to the same lane worked: the pump.fun MCP
// `get_token_trades` tool returned nothing but that 400 (measured 2026-08-15).