Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.
JavaScript 3d-generationai-agentsanimationavatardigital-humangenerative-aiglbgltfimage-to-3dllmmcpmcp-servermodel-context-protocolsolanatext-to-3dthreejsweb-componentswebglwebxrx402
fix(sdk): give pose a local preset path and make clash tool failures use one error channel
nirholas530d062e58f3
diff --git a/packages/clash-mcp/README.md b/packages/clash-mcp/README.mdindex 458c73d4b..0830fd23c 100644--- a/packages/clash-mcp/README.md+++ b/packages/clash-mcp/README.md@@ -98,13 +98,16 @@ The reads return live data — power and standings move between calls, so neithe{"ok": true,"epoch": 486231,+ "epochMs": 3600000,+ "endsAt": 1750000000000,"msLeft": 1843000,"factionCount": 16,"arena": [{"id": "486231:…",- "a": { "token": "…", "symbol": "ALPHA", "members": 8200, "momentum": 1.31, "power": 940, "record": { "w": 12, "l": 4, "d": 1 } },- "b": { "token": "…", "symbol": "BETA", "members": 5100, "momentum": 1.12, "power": 610, "record": { "w": 7, "l": 9, "d": 0 } },+ // each side also carries image, posts, and priceUsd (elided here)+ "a": { "token": "…", "symbol": "ALPHA", "members": 8200, "momentum": 1.31, "power": 940, "record": { "w": 12, "l": 4, "d": 1, "battles": 17, "power": 8100 } },+ "b": { "token": "…", "symbol": "BETA", "members": 5100, "momentum": 1.12, "power": 610, "record": { "w": 7, "l": 9, "d": 0, "battles": 16, "power": 5400 } },"aShare": 0.61,"leader": "…ALPHA mint…"}@@ -121,9 +124,9 @@ The reads return live data — power and standings move between calls, so neithe"enlisted": { "wallet": "…", "amount": 1250000, "usd": 84.20 },"epoch": 486231,"mint": "…faction mint…",- "added": 65,+ "added": 66,"momentum": 1.31,- "walletPower": 65,+ "walletPower": 66,"walletCap": 5000,"capped": false,"factionPower": 1005,@@ -144,15 +147,30 @@ The reads return live data — power and standings move between calls, so neithe| `THREE_WS_BASE` | no | `https://three.ws` | API deployment to talk to. || `THREE_WS_TIMEOUT_MS` | no | `20000` | Per-request timeout. || `SOLANA_SECRET_KEY` | writes only | — | Base58 secret of the enlisting wallet. Per-call `secret` overrides it. **Treat like cash.** |+| `CLASH_SOLANA_SECRET` | no | — | Fallback signer read when `SOLANA_SECRET_KEY` is unset, for hosts that scope env vars per server. Same format and the same care. |> The `secret` is only ever used to sign the enlist challenge locally — a detached ed25519 signature over the challenge text. It never signs a transaction and no funds move. Still, it controls a wallet: prefer a per-call `secret` or a dedicated env on a machine you trust.+## Errors++A failed tool call returns an MCP error result (`isError: true`) whose text is a single JSON object: `{ "ok": false, "error": "<code>", "message": "…" }`, plus `status` on upstream rejections and `detail` where the failure carries context (e.g. which wallet was not a holder):++| `error` | Meaning | Recovery |+| ------- | ------- | -------- |+| `validation_error` | Bad arguments: a missing faction `token`, or `rally_faction` called with neither a `pass` nor a `token`. | Fix the call. |+| `no_signer` / `invalid_secret` | A write tool had no Solana key, or the key was not a base58 64-byte secret. | Pass `secret` or set `SOLANA_SECRET_KEY`. |+| `not_eligible` | The auto-enlisting wallet does not hold the faction coin, so no pass was issued. `detail` carries `wallet`, `faction`, and `reason`. | Hold the coin, then retry. |+| `upstream_error` | The API rejected the request. `status` carries the HTTP code; notable bodies include `bad_challenge`, `bad_signature`, `pass_invalid` (expired or foreign war pass), `balance_unavailable` (RPC could not read the holding), and `cc_unconfigured` (the deployment has no CoinCommunities config). | Act on the code; re-enlist on `pass_invalid`. |+| `timeout` | No response within `THREE_WS_TIMEOUT_MS`. | Retry or raise the timeout. |+| `network_error` | The request never reached the API (DNS, offline, TLS). | Check connectivity / `THREE_WS_BASE`. |+| `bad_config` | `THREE_WS_TIMEOUT_MS` is not a positive number (thrown at startup). | Fix the env var. |+## Links- Homepage: https://three.ws- Changelog: https://three.ws/changelog- Issues: https://github.com/nirholas/three.ws/issues-- License: Apache-2.0 — see [LICENSE](./LICENSE)+- License: proprietary, see [LICENSE](./LICENSE)---diff --git a/packages/clash-mcp/src/lib/api.js b/packages/clash-mcp/src/lib/api.jsindex 4b01992d6..fd1908b61 100644--- a/packages/clash-mcp/src/lib/api.js+++ b/packages/clash-mcp/src/lib/api.js@@ -59,7 +59,8 @@ export async function apiRequest(path, { method = 'GET', query, body } = {}) {}if (!res.ok) {- const message = data?.message || data?.error || `three.ws ${path} returned HTTP ${res.status}`;+ const message =+ data?.error_description || data?.message || data?.error || `three.ws ${path} returned HTTP ${res.status}`;throw Object.assign(new Error(message), { code: 'upstream_error', status: res.status, body: data });}return data;diff --git a/packages/clash-mcp/src/tools/enlist-faction.js b/packages/clash-mcp/src/tools/enlist-faction.jsindex 6b0bb24c3..90f83cb2f 100644--- a/packages/clash-mcp/src/tools/enlist-faction.js+++ b/packages/clash-mcp/src/tools/enlist-faction.js@@ -30,17 +30,12 @@ export const def = {.optional().describe('Base58 Solana secret of the enlisting wallet. Falls back to SOLANA_SECRET_KEY env. The wallet must hold the faction coin.'),},+ // Failures (no signer, bad secret, upstream rejection) propagate to the+ // server wrapper, which formats them and marks the result isError - the same+ // error channel the read tools use. An ineligible wallet is NOT an error:+ // the proof ran and answered, so it returns ok:true with eligible:false.async handler(args) {- try {- const result = await enlist({ token: args?.token, secret: args?.secret });- return { ok: true, ...result };- } catch (err) {- return {- ok: false,- error: err?.code || 'enlist_failed',- message: err?.message || String(err),- ...(err?.status ? { status: err.status } : {}),- };- }+ const result = await enlist({ token: args?.token, secret: args?.secret });+ return { ok: true, ...result };},};diff --git a/packages/pose/src/index.js b/packages/pose/src/index.jsindex 6f6eb41ad..7dbc4ae16 100644--- a/packages/pose/src/index.js+++ b/packages/pose/src/index.js@@ -1,15 +1,19 @@-// @three-ws/pose — a phrase → a deterministic seed + the full Euler-// joint-rotation map for a rigged 3D avatar. Thin client over the public,-// auth-free `pose_model` tool on the Streamable-HTTP MCP server at-// POST /api/mcp-3d (the SDK twin of the 3D Studio MCP server).+// @three-ws/pose: a phrase in, a deterministic seed + the full Euler+// joint-rotation map for a rigged 3D avatar out.//-// The wire call is a standard JSON-RPC `tools/call`. The tool is pure local-// computation — it scores the prompt against an in-repo preset library, picks-// one, derives a seed, and returns the preset's pre-authored rotation map. No-// model inference, no GPU, nothing persisted; the same prompt always resolves-// to the same pose. See README.md for the full reference.+// The zero-config path computes the pose LOCALLY: the pose_model algorithm is+// pure deterministic computation (token scoring + sha256) over the preset+// library this package bundles, so `poseSeed('wave hello')` needs no network,+// no key, and no payment, and returns the same result as the hosted tool.+//+// The hosted lane on the Streamable-HTTP MCP server at POST /api/mcp-3d stays+// available as an opt-in: pass `baseUrl`, `apiKey`, or `fetch` to createPose()+// and calls go over the wire as standard JSON-RPC `tools/call` requests.+// Keyless wire calls are x402-priced per call; OAuth principals (apiKey) run+// operator-funded. See README.md for the full reference.import { createHttp, ThreeWsError } from './http.js';+import { resolvePoseLocal } from './local.js';import { PRESETS, PRESET_GROUPS, getPresetById } from './pose-presets.js';export { ThreeWsError, PaymentRequiredError, DEFAULT_BASE_URL } from './http.js';@@ -33,20 +37,22 @@ export class PoseError extends ThreeWsError {}/**- * Create a Pose client bound to a base URL, fetch, and optional auth.- * For most callers the default export `poseSeed()` is enough; use this when- * you want to reuse configuration (a payment-aware fetch for the paid MCP- * lane, a custom origin) across many calls.+ * Create a Pose client. With no transport options this resolves poses locally+ * (no network, no key, no payment). Passing `baseUrl`, `apiKey`, or `fetch`+ * switches the client to the hosted pose_model tool on /api/mcp-3d: use that+ * to reuse configuration (a payment-aware fetch for the x402 lane, an OAuth+ * key for operator-funded calls, a custom origin) across many calls.** @param {object} [options]- * @param {string} [options.baseUrl] API origin (default https://three.ws).- * @param {typeof fetch} [options.fetch] fetch implementation.- * @param {string} [options.apiKey] OAuth bearer — runs the call operator-funded (free).- * @param {string} [options.previewBase] base URL for the returned previewUrl.+ * @param {string} [options.baseUrl] API origin (default https://three.ws). Selects the hosted lane.+ * @param {typeof fetch} [options.fetch] fetch implementation. Selects the hosted lane.+ * @param {string} [options.apiKey] OAuth bearer, runs hosted calls operator-funded. Selects the hosted lane.+ * @param {string} [options.previewBase] base URL for the returned previewUrl (local or hosted).* @param {Record<string,string>} [options.headers]*/export function createPose(options = {}) {- const request = createHttp(options);+ const remote = Boolean(options.baseUrl || options.apiKey || options.fetch);+ const request = remote ? createHttp(options) : null;const previewBase = stripTrailingSlash(options.previewBase || PREVIEW_BASE);let nextId = 1;@@ -63,7 +69,7 @@ export function createPose(options = {}) {{ code: 'invalid_prompt' },);}- return callPoseModel(text, opts);+ return remote ? callPoseModel(text, opts) : resolveLocally(text, opts);}/**@@ -78,7 +84,20 @@ export function createPose(options = {}) {{ code: 'invalid_prompt' },);}- return callPoseModel(presetId, opts);+ return remote ? callPoseModel(presetId, opts) : resolveLocally(presetId, opts);+ }++ // The zero-config lane: run the pose_model algorithm in-process over the+ // bundled preset library, then normalize through the same shape() step the+ // wire response goes through, so both lanes return identical PoseResults.+ async function resolveLocally(prompt, opts) {+ if (opts?.signal?.aborted) {+ const e = new Error('The operation was aborted.');+ e.name = 'AbortError';+ throw e;+ }+ const sc = await resolvePoseLocal(prompt);+ return shape(sc, previewBase);}// One JSON-RPC tools/call to pose_model, shaped into a PoseResult.diff --git a/packages/pose/src/local.js b/packages/pose/src/local.jsnew file mode 100644index 000000000..9a3704751--- /dev/null+++ b/packages/pose/src/local.js@@ -0,0 +1,102 @@+// Local pose resolution: the same deterministic algorithm the hosted+// pose_model tool runs behind POST /api/mcp-3d, executed in-process over the+// bundled preset library. Ported verbatim from the server implementation+// (api/_mcp3d/tools/studio.js in the three.ws repo) so a zero-config+// poseSeed() needs no network, no key, and no payment, and resolves+// byte-identically to the hosted tool: same token scoring, same sha256+// fallback pick, same seed derivation.+//+// Hashing uses WebCrypto (crypto.subtle), available in Node 18+ and every+// modern browser, so the package stays dependency-free on both runtimes.++import { PRESETS, PRESET_GROUPS } from './pose-presets.js';++function tokensOf(str) {+ return String(str || '')+ .toLowerCase()+ .split(/[^a-z0-9]+/g)+ .filter(Boolean);+}++const INDEX = PRESETS.map((preset) => {+ const idTokens = tokensOf(preset.id);+ const labelTokens = tokensOf(preset.label);+ const groupTokens = tokensOf(preset.group);+ return {+ preset,+ all: new Set([...idTokens, ...labelTokens, ...groupTokens]),+ idTokens,+ labelTokens,+ };+});++function scorePreset(promptTokens, entry) {+ let score = 0;+ for (const t of promptTokens) {+ if (entry.all.has(t)) score += 3;+ else {+ for (const tok of [...entry.idTokens, ...entry.labelTokens]) {+ if (tok.includes(t) || t.includes(tok)) {+ score += 1;+ break;+ }+ }+ }+ }+ return score;+}++async function sha256Bytes(text) {+ const digest = await crypto.subtle.digest('SHA-256', new TextEncoder().encode(text));+ return new Uint8Array(digest);+}++function toHex(bytes) {+ let out = '';+ for (const b of bytes) out += b.toString(16).padStart(2, '0');+ return out;+}++async function pickPreset(prompt) {+ const tokens = tokensOf(prompt);+ const deterministic = async () => {+ const hash = await sha256Bytes(String(prompt));+ // Same pick as the server's hash.readUInt32BE(0): big-endian first word.+ const idx = new DataView(hash.buffer, hash.byteOffset, hash.byteLength).getUint32(0) % INDEX.length;+ return { entry: INDEX[idx], score: 0, reason: 'no-match-deterministic-pick' };+ };+ if (tokens.length === 0) return deterministic();+ let best = null;+ let bestScore = -1;+ for (const entry of INDEX) {+ const sc = scorePreset(tokens, entry);+ if (sc > bestScore) {+ best = entry;+ bestScore = sc;+ }+ }+ if (bestScore <= 0) return deterministic();+ return { entry: best, score: bestScore, reason: 'token-match' };+}++/**+ * Resolve a prompt to the tool's snake_case structuredContent shape, so the+ * local and remote lanes normalize through the exact same `shape()` step.+ * @param {string} prompt+ * @returns {Promise<object>} structuredContent (snake_case, as on the wire)+ */+export async function resolvePoseLocal(prompt) {+ const picked = await pickPreset(prompt);+ const preset = picked.entry.preset;+ const seed = toHex(await sha256Bytes(`${prompt}|${preset.id}`)).slice(0, 16);+ return {+ seed,+ preset_id: preset.id,+ preset_label: preset.label,+ group: preset.group,+ parameters: preset.pose,+ preview_url: null,+ match: { score: picked.score, reason: picked.reason },+ groups: PRESET_GROUPS,+ };+}diff --git a/packages/pose/src/pose-presets.js b/packages/pose/src/pose-presets.jsindex 53ca680fc..1c9bc739d 100644--- a/packages/pose/src/pose-presets.js+++ b/packages/pose/src/pose-presets.js@@ -103,6 +103,20 @@ export const PRESETS = [chest: { x: -0.05, y: 0, z: 0 },},},+ {+ id: 'salute',+ label: 'Salute',+ group: 'Standing',+ pose: {+ chest: { x: -0.04, y: 0, z: 0 },+ head: { x: 0.05, y: 0, z: 0 },+ shoulderL: { x: -0.04, y: 0, z: 0.09 },+ elbowL: { x: -0.12, y: 0, z: 0 },+ shoulderR: { x: -0.78, y: 0.35, z: -0.60 },+ elbowR: { x: -2.35, y: 0, z: 0 },+ wristR: { x: 0, y: 0, z: -0.20 },+ },+ },// ─── ACTION ───{@@ -212,6 +226,25 @@ export const PRESETS = [rootPosition: { x: 0, y: -0.42, z: 0 },},},+ {+ id: 'fighting-stance',+ label: 'Fighting stance',+ group: 'Action',+ pose: {+ spine: { x: 0.05, y: 0.10, z: 0 },+ chest: { x: 0.05, y: 0.22, z: 0 },+ head: { x: 0.08, y: 0.12, z: 0 },+ shoulderL: { x: -0.85, y: 0.30, z: -0.30 },+ shoulderR: { x: -0.85, y: -0.25, z: -0.20 },+ elbowL: { x: -2.10, y: 0, z: 0 },+ elbowR: { x: -2.20, y: 0, z: 0 },+ hipL: { x: -0.25, y: 0.10, z: 0.05 },+ hipR: { x: -0.20, y: -0.10, z: -0.05 },+ kneeL: { x: 0.45, y: 0, z: 0 },+ kneeR: { x: 0.55, y: 0, z: 0 },+ rootPosition: { x: 0, y: -0.12, z: 0 },+ },+ },// ─── SITTING & FLOOR ───{@@ -399,6 +432,37 @@ export const PRESETS = [head: { x: 0, y: -0.30, z: 0 },},},+ {+ id: 'facepalm',+ label: 'Facepalm',+ group: 'Expressive',+ pose: {+ spine: { x: 0.10, y: 0, z: 0 },+ chest: { x: 0.18, y: 0, z: 0 },+ neck: { x: 0.25, y: 0, z: 0 },+ head: { x: 0.50, y: 0, z: 0 },+ shoulderR: { x: -0.90, y: 0.50, z: -0.45 },+ elbowR: { x: -2.40, y: 0, z: 0 },+ wristR: { x: 0.10, y: 0, z: 0 },+ shoulderL: { x: -0.15, y: 0, z: 0.12 },+ elbowL: { x: -0.30, y: 0, z: 0 },+ },+ },+ {+ id: 'bow',+ label: 'Take a bow',+ group: 'Expressive',+ pose: {+ spine: { x: 0.40, y: 0, z: 0 },+ chest: { x: 0.55, y: 0, z: 0 },+ neck: { x: 0.18, y: 0, z: 0 },+ head: { x: 0.22, y: 0, z: 0 },+ shoulderL: { x: -0.12, y: 0, z: 0.14 },+ shoulderR: { x: -0.12, y: 0, z: -0.14 },+ elbowL: { x: -0.28, y: 0, z: 0 },+ elbowR: { x: -0.28, y: 0, z: 0 },+ },+ },];export function getPresetById(id) {