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
feat: ElevenLabs TTS lib, chat-plugin protocol/tool, IBM partner pages, lobehub plugin updates
nirholas17185aa15864
diff --git a/api/_lib/elevenlabs.js b/api/_lib/elevenlabs.jsnew file mode 100644index 000000000..50f1a0e9c--- /dev/null+++ b/api/_lib/elevenlabs.js@@ -0,0 +1,129 @@+// Shared ElevenLabs client + helpers.+//+// Centralizes the base URL, the API-key gate, the cached voice catalog, voice+// cloning (via the official SDK), and best-effort voice deletion so the TTS+// proxy (api/tts/*) and the agent-voice endpoints (api/agents/:id/voice) don't+// each reimplement them. Lazy: nothing here touches the network at import time.++import { ElevenLabsClient } from '@elevenlabs/elevenlabs-js';+import { env } from './env.js';++export const ELEVEN_BASE = 'https://api.elevenlabs.io/v1';++// Default real-time synthesis model. Flash v2.5 has roughly half the latency+// (and cost) of Turbo v2.5, which matters for a talking avatar; callers can+// still override per request with `modelId`.+export const DEFAULT_TTS_MODEL = 'eleven_flash_v2_5';++export function elevenApiKey() {+ return env.ELEVENLABS_API_KEY || null;+}++export function isConfigured() {+ return !!env.ELEVENLABS_API_KEY;+}++/** Build an Error tagged with an HTTP status (and optional upstream detail). */+function upstreamError(message, status, extra = {}) {+ return Object.assign(new Error(message), { status, ...extra });+}++// ── Voice catalog ────────────────────────────────────────────────────────────+// The catalog changes only when an account adds/clones/removes a voice, but the+// agent editor and the PUT validator both read it. Cache the filtered list per+// warm serverless instance; a short TTL keeps freshly cloned voices visible.++const VOICE_TTL_MS = 5 * 60 * 1000;+let voiceCache = null; // { at: epochMs, voices: [...] }++export function invalidateVoiceCache() {+ voiceCache = null;+}++/**+ * Fetch the account's voices, filtered to safe public fields.+ * @returns {Promise<{ voices: Array, cached: boolean }>}+ * @throws {Error & { status:number }} 503 when unconfigured, 502 on upstream failure.+ */+export async function listVoices({ force = false } = {}) {+ const apiKey = elevenApiKey();+ if (!apiKey) throw upstreamError('ElevenLabs is not configured', 503);++ if (!force && voiceCache && Date.now() - voiceCache.at < VOICE_TTL_MS) {+ return { voices: voiceCache.voices, cached: true };+ }++ let resp;+ try {+ resp = await fetch(`${ELEVEN_BASE}/voices`, { headers: { 'xi-api-key': apiKey } });+ } catch (e) {+ throw upstreamError('Could not reach ElevenLabs', 502, { cause: e });+ }+ if (!resp.ok) {+ console.error('[elevenlabs] listVoices error', resp.status);+ throw upstreamError(`ElevenLabs returned ${resp.status}`, 502);+ }++ const data = await resp.json();+ const voices = (data.voices || []).map((v) => ({+ voice_id: v.voice_id,+ name: v.name,+ category: v.category,+ labels: v.labels || {},+ preview_url: v.preview_url || null,+ }));++ voiceCache = { at: Date.now(), voices };+ return { voices, cached: false };+}++// ── Cloning ──────────────────────────────────────────────────────────────────++/**+ * Instant Voice Cloning via the official SDK.+ * @param {{ name:string, description?:string, files:File[] }} input+ * @returns {Promise<{ voiceId:string, requiresVerification:boolean }>}+ * @throws {Error & { status:number, upstreamBody?:string }} on failure. IVC is+ * a paid-tier feature; the free tier surfaces `can_not_use_instant_+ * voice_cloning` here, which callers can pass through verbatim.+ */+export async function createClonedVoice({ name, description, files }) {+ const apiKey = elevenApiKey();+ if (!apiKey) throw upstreamError('ElevenLabs is not configured', 503);++ const client = new ElevenLabsClient({ apiKey });+ let result;+ try {+ result = await client.voices.ivc.create({ name, description, files });+ } catch (err) {+ const status = err?.statusCode || err?.status || 502;+ const upstreamBody =+ (err?.body && typeof err.body === 'object' ? JSON.stringify(err.body) : err?.body) ||+ err?.message ||+ 'upstream error';+ throw upstreamError(`ElevenLabs returned ${status}`, status, { upstreamBody });+ }++ if (!result?.voice_id) throw upstreamError('ElevenLabs response missing voice_id', 502);++ invalidateVoiceCache();+ return { voiceId: result.voice_id, requiresVerification: !!result.requires_verification };+}++/**+ * Best-effort deletion to free a quota slot. Never throws — a failed cleanup is+ * logged and swallowed so it can't break the caller's primary flow.+ */+export async function deleteVoice(voiceId) {+ const apiKey = elevenApiKey();+ if (!apiKey || !voiceId) return;+ try {+ await fetch(`${ELEVEN_BASE}/voices/${encodeURIComponent(voiceId)}`, {+ method: 'DELETE',+ headers: { 'xi-api-key': apiKey },+ });+ invalidateVoiceCache();+ } catch (e) {+ console.warn('[elevenlabs] deleteVoice failed', voiceId, e?.message);+ }+}diff --git a/api/_lib/migrations/20260603000000_agent_voice_settings.sql b/api/_lib/migrations/20260603000000_agent_voice_settings.sqlnew file mode 100644index 000000000..d5ba6540f--- /dev/null+++ b/api/_lib/migrations/20260603000000_agent_voice_settings.sql@@ -0,0 +1,10 @@+-- Per-agent ElevenLabs voice tuning.+--+-- voice_model: synthesis model id (e.g. eleven_flash_v2_5). NULL = platform default.+-- voice_settings: canonical ElevenLabs voice_settings object+-- { stability, similarity_boost, style, use_speaker_boost }. NULL = recommended defaults.+--+-- Both are read by the agent runtime (src/agent-resolver.js) and written by+-- PUT /api/agents/:id/voice. NULL keeps existing agents on the defaults.+alter table agent_identities add column if not exists voice_model text;+alter table agent_identities add column if not exists voice_settings jsonb;diff --git a/api/agents/_id/voice.js b/api/agents/_id/voice.jsindex c9b28fa1d..b21792597 100644--- a/api/agents/_id/voice.js+++ b/api/agents/_id/voice.js@@ -9,12 +9,11 @@import { sql } from '../../_lib/db.js';import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';import { cors, json, method, wrap, error, readJson } from '../../_lib/http.js';-import { limits, clientIp } from '../../_lib/rate-limit.js';-import { env } from '../../_lib/env.js';+import { limits } from '../../_lib/rate-limit.js';+import { isConfigured, listVoices, createClonedVoice, deleteVoice } from '../../_lib/elevenlabs.js';const MAX_AUDIO_BYTES = 10 * 1024 * 1024; // 10 MBconst MIN_DURATION_SEC = 30;-const ELEVEN_BASE = 'https://api.elevenlabs.io/v1';async function resolveAuth(req) {const session = await getSessionUser(req);@@ -78,13 +77,20 @@ export const handleVoice = wrap(async (req, res, id, action) => {// not a clone owned by this user).if (req.method === 'PUT') {- const apiKey = env.ELEVENLABS_API_KEY;- if (!apiKey)- return error(res, 503, 'not_configured', 'voice library is not configured on this server');+ if (!isConfigured())+ return error(+ res,+ 503,+ 'not_configured',+ 'voice library is not configured on this server',+ );let body;- try { body = await readJson(req); }- catch { return error(res, 400, 'validation_error', 'invalid JSON body'); }+ try {+ body = await readJson(req);+ } catch {+ return error(res, 400, 'validation_error', 'invalid JSON body');+ }const nextVoiceId = body?.voice_id == null ? null : String(body.voice_id).trim() || null;@@ -97,31 +103,25 @@ export const handleVoice = wrap(async (req, res, id, action) => {if (nextVoiceId) {let voices;try {- const resp = await fetch(`${ELEVEN_BASE}/voices`, {- headers: { 'xi-api-key': apiKey },- });- if (!resp.ok) {- console.error('[voice/put] elevenlabs voices fetch failed', resp.status);- return error(res, 502, 'upstream_error', 'voice library is unavailable');- }- const data = await resp.json();- voices = data?.voices || [];+ ({ voices } = await listVoices());} catch (err) {- console.error('[voice/put] elevenlabs fetch threw', err);+ console.error('[voice/put] listVoices failed', err);return error(res, 502, 'upstream_error', 'voice library is unavailable');}if (!voices.some((v) => v.voice_id === nextVoiceId)) {- return error(res, 400, 'validation_error', 'voice_id is not in the available library');+ return error(+ res,+ 400,+ 'validation_error',+ 'voice_id is not in the available library',+ );}}// Free the prior cloned voice on ElevenLabs (best-effort) only when// we're actually replacing a clone with something else.if (wasCloned && oldVoiceId && oldVoiceId !== nextVoiceId) {- fetch(`${ELEVEN_BASE}/voices/${encodeURIComponent(oldVoiceId)}`, {- method: 'DELETE',- headers: { 'xi-api-key': apiKey },- }).catch(() => {});+ deleteVoice(oldVoiceId);}if (nextVoiceId) {@@ -130,7 +130,11 @@ export const handleVoice = wrap(async (req, res, id, action) => {SET voice_provider = 'elevenlabs', voice_id = ${nextVoiceId}, voice_cloned_at = NULLWHERE id = ${id}`;- return json(res, 200, { voice_provider: 'elevenlabs', voice_id: nextVoiceId, voice_cloned_at: null });+ return json(res, 200, {+ voice_provider: 'elevenlabs',+ voice_id: nextVoiceId,+ voice_cloned_at: null,+ });}await sql`@@ -144,17 +148,11 @@ export const handleVoice = wrap(async (req, res, id, action) => {// ── DELETE — remove cloned voice ─────────────────────────────────────────if (req.method === 'DELETE') {- const [row] = await sql`SELECT voice_id FROM agent_identities WHERE id = ${id}`;- if (row?.voice_id) {- // Best-effort: free the quota slot on ElevenLabs.- const apiKey = env.ELEVENLABS_API_KEY;- if (apiKey) {- fetch(`${ELEVEN_BASE}/voices/${encodeURIComponent(row.voice_id)}`, {- method: 'DELETE',- headers: { 'xi-api-key': apiKey },- }).catch(() => {});- }- }+ const [row] =+ await sql`SELECT voice_id, voice_cloned_at FROM agent_identities WHERE id = ${id}`;+ // Only free *cloned* voices on ElevenLabs — library voices are shared+ // across the account and must never be deleted here.+ if (row?.voice_id && row?.voice_cloned_at) deleteVoice(row.voice_id);await sql`UPDATE agent_identitiesSET voice_provider = 'browser', voice_id = NULL, voice_cloned_at = NULL@@ -166,9 +164,13 @@ export const handleVoice = wrap(async (req, res, id, action) => {// ── POST /clone ──────────────────────────────────────────────────────────if (req.method === 'POST' && action === 'clone') {- const apiKey = env.ELEVENLABS_API_KEY;- if (!apiKey)- return error(res, 503, 'not_configured', 'voice cloning is not configured on this server');+ if (!isConfigured())+ return error(+ res,+ 503,+ 'not_configured',+ 'voice cloning is not configured on this server',+ );// Rate limit: 3 clones per user per day.const rl = await limits.voiceClone(auth.userId);@@ -201,7 +203,8 @@ export const handleVoice = wrap(async (req, res, id, action) => {throw err;}- if (audioBuf.length === 0) return error(res, 400, 'validation_error', 'audio body is empty');+ if (audioBuf.length === 0)+ return error(res, 400, 'validation_error', 'audio body is empty');// Fallback size check when no duration header. WebM/Opus at 64 kbps:// 3 s ≈ 24 KB, 30 s ≈ 240 KB. 50 KB catches sub-6-second clips.@@ -224,41 +227,47 @@ export const handleVoice = wrap(async (req, res, id, action) => {? 'audio.m4a': 'audio.webm';- const form = new FormData();- form.append('name', voiceName);- if (voiceDescription) form.append('description', voiceDescription);- form.append('files', new Blob([audioBuf], { type: ct }), ext);+ const audioFile = new File([audioBuf], ext, { type: ct });- let elevenResp;+ let voiceId;try {- elevenResp = await fetch(`${ELEVEN_BASE}/voices/add`, {- method: 'POST',- headers: { 'xi-api-key': apiKey },- body: form,- });+ ({ voiceId } = await createClonedVoice({+ name: voiceName,+ description: voiceDescription || undefined,+ files: [audioFile],+ }));} catch (err) {- console.error('[voice/clone] elevenlabs fetch failed', err);- return error(res, 502, 'upstream_error', 'voice cloning service unavailable');- }-- if (!elevenResp.ok) {- const body = await elevenResp.text().catch(() => '');- console.error('[voice/clone] elevenlabs error', elevenResp.status, body);- if (elevenResp.status === 422)- return error(res, 400, 'audio_too_short', 'audio is too short or low quality for cloning');+ console.error(+ '[voice/clone] createClonedVoice failed',+ err.status,+ err.upstreamBody || err.message,+ );+ if (err.status === 422)+ return error(+ res,+ 400,+ 'audio_too_short',+ 'audio is too short or low quality for cloning',+ );return error(res, 502, 'upstream_error', 'voice cloning failed');}- const { voice_id } = await elevenResp.json();- if (!voice_id) return error(res, 502, 'upstream_error', 'unexpected response from voice service');-- await sql`- UPDATE agent_identities- SET voice_provider = 'elevenlabs', voice_id = ${voice_id}, voice_cloned_at = now()- WHERE id = ${id}- `;+ // Persist the clone. If the DB write fails the voice we just created would+ // leak in ElevenLabs (counting against the account quota with no DB+ // reference), so delete it before surfacing the error.+ try {+ await sql`+ UPDATE agent_identities+ SET voice_provider = 'elevenlabs', voice_id = ${voiceId}, voice_cloned_at = now()+ WHERE id = ${id}+ `;+ } catch (dbErr) {+ console.error('[voice/clone] DB persist failed, rolling back clone', dbErr);+ await deleteVoice(voiceId);+ return error(res, 500, 'internal_error', 'failed to save cloned voice');+ }- return json(res, 201, { voice_id, name: voiceName });+ return json(res, 201, { voice_id: voiceId, name: voiceName });}return error(res, 404, 'not_found', 'unknown voice action');diff --git a/api/chat-plugin/[tool].js b/api/chat-plugin/[tool].jsnew file mode 100644index 000000000..6a9cb3ba2--- /dev/null+++ b/api/chat-plugin/[tool].js@@ -0,0 +1,135 @@+// Gateway-facing tool endpoint for the three.ws chat plugin (LobeChat / SperaxOS).+//+// When the LLM calls one of the plugin's functions, the host's plugin gateway+// POSTs the function arguments here as the JSON body and forwards the user's+// plugin settings in a header. The standalone iframe animates the avatar over+// postMessage; this endpoint returns the concise tool result the model reads+// back. Both halves run for every call — this is the model-facing half.+//+// Function → URL mapping is declared in /sperax/manifest.json:+// render_agent → /api/chat-plugin/render-agent+// speak → /api/chat-plugin/speak+// gesture → /api/chat-plugin/gesture+// emote → /api/chat-plugin/emote+import { cors, error, json, method, readJson, wrap } from '../_lib/http.js';+import { clientIp, limits } from '../_lib/rate-limit.js';++const GESTURES = ['wave', 'nod', 'point', 'shrug'];+const EMOTIONS = ['concern', 'celebration', 'patience', 'curiosity', 'empathy'];++// LobeChat forwards settings in `lobe-chat-plugin-settings`; SperaxOS renames it+// to `Sperax-Plugin-Settings`. Header names are lower-cased by Node.+function readSettings(req) {+ const raw = req.headers['sperax-plugin-settings'] || req.headers['lobe-chat-plugin-settings'];+ if (!raw || typeof raw !== 'string') return {};+ try {+ const parsed = JSON.parse(raw);+ return parsed && typeof parsed === 'object' ? parsed : {};+ } catch {+ return {};+ }+}++// The gateway posts the arguments object as the body. Be defensive about a+// `{ arguments: "<json-string>" }` envelope in case a host wraps it.+function readArgs(body) {+ if (!body || typeof body !== 'object') return {};+ if (typeof body.arguments === 'string') {+ try {+ return JSON.parse(body.arguments) || {};+ } catch {+ return {};+ }+ }+ return body;+}++export default wrap(async (req, res) => {+ // Server-to-server from the gateway, but also reachable by browser-based+ // marketplace validators — keep it openly readable.+ if (cors(req, res, { methods: 'POST,OPTIONS', origins: '*' })) return;+ if (!method(req, res, ['POST'])) return;++ const rl = await limits.widgetRead(clientIp(req));+ if (!rl.success) return error(res, 429, 'rate_limited', 'too many requests');++ const tool = String(req.query?.tool || '').toLowerCase();+ const args = readArgs(await readJson(req, 64_000));+ const settings = readSettings(req);+ const agentId =+ typeof args.agentId === 'string'+ ? args.agentId+ : typeof settings.agentId === 'string'+ ? settings.agentId+ : null;++ switch (tool) {+ case 'render-agent': {+ if (!agentId) {+ return error(res, 400, 'validation_error', 'agentId is required');+ }+ return json(res, 200, {+ ok: true,+ action: 'render_agent',+ agentId,+ message: `The embodied avatar panel is now bound to agent ${agentId}.`,+ });+ }++ case 'speak': {+ const text = typeof args.text === 'string' ? args.text.trim() : '';+ if (!text) return error(res, 400, 'validation_error', 'text is required');+ const sentiment =+ typeof args.sentiment === 'number' ? Math.max(-1, Math.min(1, args.sentiment)) : 0;+ return json(res, 200, {+ ok: true,+ action: 'speak',+ spoken: text,+ sentiment,+ message: 'The avatar spoke this line aloud in the panel.',+ });+ }++ case 'gesture': {+ const name = typeof args.name === 'string' ? args.name.toLowerCase() : '';+ if (!GESTURES.includes(name)) {+ return error(+ res,+ 400,+ 'validation_error',+ `name must be one of: ${GESTURES.join(', ')}`,+ );+ }+ return json(res, 200, {+ ok: true,+ action: 'gesture',+ gesture: name,+ message: `The avatar played the "${name}" gesture.`,+ });+ }++ case 'emote': {+ const trigger = typeof args.trigger === 'string' ? args.trigger.toLowerCase() : '';+ if (!EMOTIONS.includes(trigger)) {+ return error(+ res,+ 400,+ 'validation_error',+ `trigger must be one of: ${EMOTIONS.join(', ')}`,+ );+ }+ const weight =+ typeof args.weight === 'number' ? Math.max(0, Math.min(1, args.weight)) : 1;+ return json(res, 200, {+ ok: true,+ action: 'emote',+ emotion: trigger,+ weight,+ message: `The avatar's body language shifted toward "${trigger}".`,+ });+ }++ default:+ return error(res, 404, 'not_found', `unknown plugin tool: ${tool || '(none)'}`);+ }+});diff --git a/api/lobehub/[action].js b/api/lobehub/[action].jsindex dc0373af8..b6c09f75a 100644--- a/api/lobehub/[action].js+++ b/api/lobehub/[action].js@@ -67,7 +67,14 @@ export default wrap(async (req, res) => {if (!agent) return error(res, 404, 'not_found', 'agent not found');- const allowedHosts = ['chat.lobehub.com', 'lobechat.ai'];+ const allowedHosts = [+ 'chat.lobehub.com',+ 'lobechat.ai',+ 'chat.sperax.io',+ 'sperax.io',+ 'sperax-iota.vercel.app',+ 'sperax-jam2emun9-moomsi.vercel.app',+ ];if (hostOrigin) {try {allowedHosts.push(new URL(hostOrigin).hostname);diff --git a/api/tts/eleven-clone.js b/api/tts/eleven-clone.jsindex bc77739ad..7f1cdc6d7 100644--- a/api/tts/eleven-clone.js+++ b/api/tts/eleven-clone.js@@ -17,10 +17,9 @@* with the upstream body included so the demo log surfaces it verbatim.*/-import { ElevenLabsClient } from '@elevenlabs/elevenlabs-js';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { cors, method, wrap, error, json } from '../_lib/http.js';-import { env } from '../_lib/env.js';+import { createClonedVoice, isConfigured } from '../_lib/elevenlabs.js';export const config = {api: { bodyParser: false },@@ -34,8 +33,7 @@ export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;- const apiKey = env.ELEVENLABS_API_KEY;- if (!apiKey)+ if (!isConfigured())return error(res, 503, 'not_configured', 'ElevenLabs is not configured on this server');const session = await getSessionUser(req);@@ -44,7 +42,12 @@ export default wrap(async (req, res) => {const ct = req.headers['content-type'] || '';if (!ct.toLowerCase().startsWith('multipart/form-data'))- return error(res, 415, 'unsupported_media_type', 'content-type must be multipart/form-data');+ return error(+ res,+ 415,+ 'unsupported_media_type',+ 'content-type must be multipart/form-data',+ );const boundaryMatch = ct.match(/boundary=(?:"([^"]+)"|([^;]+))/i);const boundary = boundaryMatch ? (boundaryMatch[1] || boundaryMatch[2]).trim() : null;@@ -55,7 +58,12 @@ export default wrap(async (req, res) => {raw = await readBody(req, MAX_REQUEST_BYTES);} catch (err) {const status = err.status || 400;- return error(res, status, status === 413 ? 'payload_too_large' : 'bad_request', err.message);+ return error(+ res,+ status,+ status === 413 ? 'payload_too_large' : 'bad_request',+ err.message,+ );}let parts;@@ -84,53 +92,47 @@ export default wrap(async (req, res) => {if (!name) return error(res, 400, 'validation_error', 'name field is required');if (name.length > 64) return error(res, 400, 'validation_error', 'name exceeds 64 chars');- const description = String(fields.description || '').trim().slice(0, 500) || undefined;+ const description =+ String(fields.description || '')+ .trim()+ .slice(0, 500) || undefined;const filename = audio.filename || 'sample.webm';const fileType = audio.contentType || guessAudioMime(filename);const audioFile = new File([audio.data], filename, { type: fileType });- const client = new ElevenLabsClient({ apiKey });-let result;try {- result = await client.voices.ivc.create({- name,- description,- files: [audioFile],- });+ result = await createClonedVoice({ name, description, files: [audioFile] });} catch (err) {- const status = err?.statusCode || err?.status || 502;- const body =- (err?.body && typeof err.body === 'object' ? JSON.stringify(err.body) : err?.body) ||- err?.message ||- 'upstream error';- console.error('[tts/eleven-clone] ElevenLabs voices.ivc.create failed', status, body);+ const status = err.status || 502;+ console.error(+ '[tts/eleven-clone] createClonedVoice failed',+ status,+ err.upstreamBody || err.message,+ );// Pass the upstream body through so the demo surface can show the exact// quota / verification message — IVC is a paid-tier feature.return json(res, 502, {error: 'upstream_error',error_description: `ElevenLabs returned ${status}`,upstream_status: status,- upstream_body: body,+ upstream_body: err.upstreamBody || err.message || 'upstream error',});}- if (!result?.voice_id)- return error(res, 502, 'upstream_error', 'ElevenLabs response missing voice_id');-const userId = session?.id ?? bearer.userId;if (process.env.TTS_DEBUG === '1') {console.log(- `[tts/eleven-clone] user=${userId} cloned voice "${name}" -> ${result.voice_id} (audio=${audio.data.length}B)`,+ `[tts/eleven-clone] user=${userId} cloned voice "${name}" -> ${result.voiceId} (audio=${audio.data.length}B)`,);}return json(res, 200, {- voice_id: result.voice_id,+ voice_id: result.voiceId,name,- status: result.requires_verification ? 'pending_verification' : 'ready',- requires_verification: !!result.requires_verification,+ status: result.requiresVerification ? 'pending_verification' : 'ready',+ requires_verification: result.requiresVerification,});});@@ -179,7 +181,10 @@ function parseMultipart(buf, boundary) {const headerStr = buf.slice(pos, headersEnd).toString('utf8');const dataStart = headersEnd + 4;- const nextBoundary = buf.indexOf(crlf.length ? Buffer.concat([crlf, delim]) : delim, dataStart);+ const nextBoundary = buf.indexOf(+ crlf.length ? Buffer.concat([crlf, delim]) : delim,+ dataStart,+ );if (nextBoundary < 0) throw new Error('no closing boundary for part');const data = buf.slice(dataStart, nextBoundary);diff --git a/api/tts/eleven.js b/api/tts/eleven.jsindex 1dec9c26b..0ccc0d339 100644--- a/api/tts/eleven.js+++ b/api/tts/eleven.js@@ -1,23 +1,42 @@/*** POST /api/tts/eleven*- * Server proxy for ElevenLabs TTS. Keeps the API key server-side.- * Caches synthesized clips in R2 by sha256(voiceId + text) for 30 days.+ * Server proxy for ElevenLabs TTS. Keeps the API key server-side. The clip is+ * streamed straight to the client (low TTFB) and, on a clean finish, cached in+ * R2 for 30 days keyed by sha256(voiceId + text + modelId + voice_settings).* Rate-limits per user: 1000 chars / hour tracked via Redis INCRBY.*- * Body: { voiceId: string, text: string, modelId?: string }- * Response: audio/mpeg+ * Body: {+ * voiceId: string,+ * text: string,+ * modelId?: string, // default eleven_flash_v2_5+ * voice_settings?: { // canonical ElevenLabs shape, honored verbatim+ * stability?, similarity_boost?, style?, // clamped to 0..1+ * use_speaker_boost? // boolean+ * }+ * }+ * Response: audio/mpeg (chunked)*/import { Redis } from '@upstash/redis';import { getSessionUser, authenticateBearer, extractBearer } from '../_lib/auth.js';import { cors, method, wrap, error, readJson } from '../_lib/http.js';import { sha256 } from '../_lib/crypto.js';-import { env } from '../_lib/env.js';import { headObject, getObjectBuffer, putObject } from '../_lib/r2.js';+import { ELEVEN_BASE, DEFAULT_TTS_MODEL, elevenApiKey } from '../_lib/elevenlabs.js';const CHARS_PER_HOUR = 1000;-const ELEVEN_BASE = 'https://api.elevenlabs.io/v1';++// Fire-and-forget R2 cache write — a miss on failure is acceptable.+function cacheAudio(key, buffer) {+ if (!buffer.length) return;+ putObject({+ key,+ body: buffer,+ contentType: 'audio/mpeg',+ metadata: { 'created-at': new Date().toISOString() },+ }).catch((e) => console.warn('[tts/eleven] R2 cache write failed:', e.message));+}// Only instantiate if Upstash is configured (mirrors the pattern in rate-limit.js).let redis = null;@@ -32,7 +51,7 @@ export default wrap(async (req, res) => {if (cors(req, res, { methods: 'POST,OPTIONS', credentials: true })) return;if (!method(req, res, ['POST'])) return;- const apiKey = env.ELEVENLABS_API_KEY;+ const apiKey = elevenApiKey();if (!apiKey)return error(res, 503, 'not_configured', 'ElevenLabs is not configured on this server');@@ -44,17 +63,35 @@ export default wrap(async (req, res) => {const body = await readJson(req);const voiceId = String(body.voiceId || '').trim();const text = String(body.text || '').trim();- const modelId = String(body.modelId || 'eleven_turbo_v2_5').trim();+ const modelId = String(body.modelId || DEFAULT_TTS_MODEL).trim();if (!voiceId) return error(res, 400, 'validation_error', 'voiceId is required');if (!text) return error(res, 400, 'validation_error', 'text is required');if (text.length > 500)return error(res, 400, 'validation_error', 'text exceeds 500 chars per request');+ // Honor the canonical ElevenLabs `voice_settings` object the client sends+ // (the ElevenLabsTTS client maps `rate` → `style` and forwards it here);+ // fall back to ElevenLabs' recommended defaults. Clamped to 0..1 and folded+ // into the cache key so distinct settings never collide on a shared clip.+ const clamp01 = (v, fallback) => {+ const n = Number(v);+ return Number.isFinite(n) ? Math.min(1, Math.max(0, n)) : fallback;+ };+ const vs =+ body.voice_settings && typeof body.voice_settings === 'object' ? body.voice_settings : {};+ const stability = clamp01(vs.stability, 0.5);+ const similarityBoost = clamp01(vs.similarity_boost, 0.75);+ const style = clamp01(vs.style, 0.5);+ const useSpeakerBoost = vs.use_speaker_boost !== undefined ? !!vs.use_speaker_boost : true;+// ── Char-based rate limit ─────────────────────────────────────────────────+ // rKey is lifted to function scope so a failed synthesis can refund the+ // characters it optimistically reserves below.+ let rKey = null;if (redis) {const hourBucket = Math.floor(Date.now() / 3_600_000);- const rKey = `tts:chars:${userId}:${hourBucket}`;+ rKey = `tts:chars:${userId}:${hourBucket}`;const used = Number((await redis.get(rKey)) || 0);if (used + text.length > CHARS_PER_HOUR) {return error(@@ -78,8 +115,16 @@ export default wrap(async (req, res) => {}}+ // Refund reserved characters when synthesis ultimately fails, so a user is+ // not billed against the hourly budget for a clip they never received.+ const refundChars = async () => {+ if (rKey) await redis.decrby(rKey, text.length).catch(() => {});+ };+// ── R2 cache lookup ───────────────────────────────────────────────────────- const cacheHash = await sha256(`${voiceId}\x00${text}\x00${modelId}`);+ const cacheHash = await sha256(+ `${voiceId}\x00${text}\x00${modelId}\x00${stability}\x00${similarityBoost}\x00${style}\x00${useSpeakerBoost}`,+ );const cacheKey = `tts/cache/${cacheHash}.mp3`;const cached = await headObject(cacheKey).catch(() => null);@@ -97,9 +142,6 @@ export default wrap(async (req, res) => {}// ── Synthesize via ElevenLabs ─────────────────────────────────────────────- // Map rate (0.5..1.5) → ElevenLabs style (0..1). Default rate=1 → style=0.5.- const styleVal = 0.5;-let elResp;try {elResp = await fetch(@@ -115,39 +157,77 @@ export default wrap(async (req, res) => {text,model_id: modelId,voice_settings: {- stability: 0.5,- similarity_boost: 0.75,- style: styleVal,- use_speaker_boost: true,+ stability,+ similarity_boost: similarityBoost,+ style,+ use_speaker_boost: useSpeakerBoost,},}),},);} catch (fetchErr) {console.error('[tts/eleven] ElevenLabs fetch failed', fetchErr);+ await refundChars();return error(res, 502, 'upstream_error', 'Could not reach ElevenLabs');}if (!elResp.ok) {const msg = await elResp.text().catch(() => '');console.error('[tts/eleven] ElevenLabs error', elResp.status, msg);+ await refundChars();return error(res, 502, 'upstream_error', `ElevenLabs returned ${elResp.status}`);}- // Buffer the audio so we can cache and serve in one pass.- const audioBuffer = Buffer.from(await elResp.arrayBuffer());-- // Store in R2 (fire-and-forget — cache miss on failure is acceptable).- putObject({- key: cacheKey,- body: audioBuffer,- contentType: 'audio/mpeg',- metadata: { 'created-at': new Date().toISOString() },- }).catch((e) => console.warn('[tts/eleven] R2 cache write failed:', e.message));-+ // Stream the clip to the client for low TTFB while teeing the chunks into a+ // buffer, so the complete audio can be cached once it has fully arrived.res.setHeader('content-type', 'audio/mpeg');- res.setHeader('content-length', String(audioBuffer.length));res.setHeader('x-tts-cache', 'miss');res.setHeader('cache-control', 'private, max-age=86400');- return res.end(audioBuffer);++ if (!elResp.body) {+ // No readable stream (unexpected) — fall back to a single buffered write.+ const audioBuffer = Buffer.from(await elResp.arrayBuffer());+ res.setHeader('content-length', String(audioBuffer.length));+ res.end(audioBuffer);+ cacheAudio(cacheKey, audioBuffer);+ return;+ }++ const chunks = [];+ let completed = false;+ try {+ for await (const chunk of elResp.body) {+ if (res.destroyed) break; // client hung up — stop pulling from upstream+ const buf = Buffer.isBuffer(chunk) ? chunk : Buffer.from(chunk);+ chunks.push(buf);+ // Respect write backpressure so a slow client can't pile unbounded data+ // into the socket buffer. Resolve on 'close' too, so a mid-clip+ // disconnect can't hang this await forever.+ if (!res.write(buf)) {+ await new Promise((resolve) => {+ const done = () => {+ res.off('drain', done);+ res.off('close', done);+ resolve();+ };+ res.once('drain', done);+ res.once('close', done);+ });+ }+ }+ // Only a naturally-exhausted iterator (no break/destroy) means every+ // upstream byte arrived — required before we may cache the clip.+ completed = !res.destroyed;+ } catch (streamErr) {+ // Upstream aborted or the client disconnected mid-clip. Don't cache a+ // partial, possibly-corrupt file — just close the response.+ console.error('[tts/eleven] stream interrupted', streamErr);+ if (!res.writableEnded && !res.destroyed) res.end();+ return;+ }++ if (!res.writableEnded && !res.destroyed) res.end();+ // Cache only a complete clip — a truncated one would poison the deterministic+ // cache key and be served as a permanent "hit" for this utterance.+ if (completed) cacheAudio(cacheKey, Buffer.concat(chunks));});diff --git a/api/tts/eleven/voices.js b/api/tts/eleven/voices.jsindex af9750479..e330fb06d 100644--- a/api/tts/eleven/voices.js+++ b/api/tts/eleven/voices.js@@ -1,14 +1,15 @@/*** GET /api/tts/eleven/voices*- * Returns the ElevenLabs voice list (filtered to safe public fields).- * Returns { enabled: false, voices: [] } when ELEVENLABS_API_KEY is not set- * so the client can gate the UI without a separate config check.+ * Returns the ElevenLabs voice list (filtered to safe public fields), served+ * from the shared per-instance cache in _lib/elevenlabs.js. Returns+ * { enabled: false, voices: [] } when ELEVENLABS_API_KEY is not set so the+ * client can gate the UI without a separate config check.*/import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';import { cors, json, method, wrap, error } from '../../_lib/http.js';-import { env } from '../../_lib/env.js';+import { isConfigured, listVoices } from '../../_lib/elevenlabs.js';export default wrap(async (req, res) => {if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;@@ -18,31 +19,28 @@ export default wrap(async (req, res) => {const bearer = session ? null : await authenticateBearer(extractBearer(req));if (!session && !bearer) return error(res, 401, 'unauthorized', 'sign in required');- const apiKey = env.ELEVENLABS_API_KEY;- if (!apiKey) return json(res, 200, { enabled: false, voices: [] });+ if (!isConfigured()) return json(res, 200, { enabled: false, voices: [] });- let data;+ let result;try {- const resp = await fetch('https://api.elevenlabs.io/v1/voices', {- headers: { 'xi-api-key': apiKey },- });- if (!resp.ok) {- console.error('[tts/eleven/voices] ElevenLabs error', resp.status);- return error(res, 502, 'upstream_error', `ElevenLabs returned ${resp.status}`);- }- data = await resp.json();+ result = await listVoices();} catch (e) {- console.error('[tts/eleven/voices] fetch failed', e);- return error(res, 502, 'upstream_error', 'Could not reach ElevenLabs');+ console.error('[tts/eleven/voices] listVoices failed', e);+ return error(+ res,+ e.status || 502,+ 'upstream_error',+ e.message || 'Could not reach ElevenLabs',+ );}- const voices = (data.voices || []).map((v) => ({- voice_id: v.voice_id,- name: v.name,- category: v.category,- labels: v.labels || {},- preview_url: v.preview_url || null,- }));-- return json(res, 200, { enabled: true, voices });+ return json(+ res,+ 200,+ { enabled: true, voices: result.voices },+ {+ 'cache-control': 'private, max-age=300',+ 'x-voices-cache': result.cached ? 'hit' : 'miss',+ },+ );});diff --git a/api/wk.js b/api/wk.jsindex bbbb155a8..c9139bd64 100644--- a/api/wk.js+++ b/api/wk.js@@ -1,6 +1,8 @@// Consolidated /.well-known/* handler.// Dispatches on ?name= query param set by vercel.json rewrites.+import { readFileSync } from 'node:fs';+import { join } from 'node:path';import { cors, json, method, wrap, error } from './_lib/http.js';import { env } from './_lib/env.js';import {@@ -1241,9 +1243,28 @@ function handleChatPlugin(req, res) {);}+// SperaxOS / plugin.delivery manifest. Single source of truth is the static+// file at public/sperax/manifest.json (also served verbatim at /sperax/manifest.json);+// this alias adds cross-origin headers so the marketplace + browser validators+// can fetch it from /.well-known/sperax-plugin.json.+let speraxManifest;+try {+ speraxManifest = JSON.parse(+ readFileSync(join(process.cwd(), 'public/sperax/manifest.json'), 'utf8'),+ );+} catch (err) {+ console.error('[wk/sperax-plugin] failed to load manifest', err);+}++function handleSperaxPlugin(req, res) {+ if (!speraxManifest) return error(res, 500, 'internal_error', 'manifest unavailable');+ return json(res, 200, speraxManifest, { 'cache-control': 'public, max-age=3600' });+}+const DISPATCH = {'agent-attestation-schemas': handleAttestationSchemas,'chat-plugin': handleChatPlugin,+ 'sperax-plugin': handleSperaxPlugin,'oauth-authorization-server': handleOauthAuthServer,'oauth-protected-resource': handleOauthProtectedResource,x402: handleX402,@@ -1257,6 +1278,7 @@ const PUBLIC_DISCOVERY = new Set(['x402','x402-discovery','chat-plugin',+ 'sperax-plugin','agent-attestation-schemas',]);diff --git a/blog/index.html b/blog/index.htmlindex 0dbe199f9..31220bd51 100644--- a/blog/index.html+++ b/blog/index.html@@ -58,6 +58,19 @@<ul class="bl-list">+ <li class="bl-item">+ <a href="/blog/three-ws-ibm-collaboration">+ <div class="bl-meta">+ <span class="bl-date">2026-06-02</span>+ <span class="bl-tag">Partnership</span>+ <span class="bl-tag">IBM</span>+ <span class="bl-tag">watsonx</span>+ </div>+ <h2 class="bl-title">Showcasing the three.ws × IBM Partnership</h2>+ <p class="bl-summary">three.ws and IBM showcased their formal partnership: a persistent, on-chain 3D agent embedded into any page as easily as a YouTube video — with the agent brain thinking on IBM watsonx.ai and Granite. IBM's official account replied, "We're super excited about this."</p>+ </a>+ </li>+<li class="bl-item"><a href="/blog/three-ws-aws-partner"><div class="bl-meta">diff --git a/blog/three-ws-ibm-business-partner.html b/blog/three-ws-ibm-business-partner.htmlindex dfe7cb68d..2387d4162 100644--- a/blog/three-ws-ibm-business-partner.html+++ b/blog/three-ws-ibm-business-partner.html@@ -71,6 +71,7 @@<h2>Links</h2><ul>+ <li>IBM partner page: <a href="/ibm">three.ws/ibm</a></li><li>Project site: <a href="https://three.ws" rel="noopener">three.ws</a></li><li>Open source: <a href="https://github.com/nirholas/three.ws" rel="noopener">github.com/nirholas/three.ws</a></li></ul>diff --git a/blog/three-ws-ibm-collaboration.html b/blog/three-ws-ibm-collaboration.htmlnew file mode 100644index 000000000..008bdb51c--- /dev/null+++ b/blog/three-ws-ibm-collaboration.html@@ -0,0 +1,156 @@+<!DOCTYPE html>+<html lang="en">+<head>+ <meta charset="UTF-8">+ <meta name="viewport" content="width=device-width, initial-scale=1.0">+ <title>Showcasing the three.ws × IBM Partnership</title>+ <meta name="description" content="three.ws and IBM showcased their partnership: embedding a persistent, on-chain 3D agent into any platform as easily as a YouTube video, with the agent brain running on IBM watsonx.ai and Granite.">+ <meta name="keywords" content="three.ws, IBM, watsonx, watsonx.ai, Granite, business partner, 3D agents, on-chain agents, agent-3d, ERC-8004, x402, enterprise AI, MCP">+ <link rel="canonical" href="https://three.ws/blog/three-ws-ibm-collaboration">++ <meta property="og:site_name" content="three.ws">+ <meta property="og:title" content="Showcasing the three.ws × IBM Partnership">+ <meta property="og:description" content="A persistent, on-chain 3D agent embedded as easily as a YouTube video — thinking on IBM watsonx.ai and Granite. three.ws and IBM showcase the partnership.">+ <meta property="og:url" content="https://three.ws/blog/three-ws-ibm-collaboration">+ <meta property="og:type" content="article">+ <meta property="article:published_time" content="2026-06-02T15:00:00.000Z">+ <meta property="article:author" content="three.ws">+ <meta property="article:section" content="Partnerships">+ <meta property="article:tag" content="IBM">+ <meta property="article:tag" content="watsonx">+ <meta property="og:image" content="https://three.ws/ibm-og.png">+ <meta property="og:image:width" content="1200">+ <meta property="og:image:height" content="630">+ <meta property="og:image:type" content="image/png">+ <meta property="og:image:alt" content="three.ws × IBM — showcasing the partnership. A persistent, on-chain 3D agent thinking on IBM watsonx.ai and Granite.">++ <meta name="twitter:card" content="summary_large_image">+ <meta name="twitter:site" content="@trythreews">+ <meta name="twitter:title" content="Showcasing the three.ws × IBM Partnership">+ <meta name="twitter:description" content="On-chain 3D agents embedded as easily as a YouTube video, thinking on IBM watsonx.ai. three.ws × IBM.">+ <meta name="twitter:image" content="https://three.ws/ibm-og.png">+ <meta name="twitter:image:alt" content="three.ws × IBM — showcasing the partnership.">++ <link rel="shortcut icon" href="/favicon.ico">+ <link rel="stylesheet" href="/nav.css">+ <link rel="stylesheet" href="/footer.css">+ <style>+ :root { color-scheme: dark; }+ body { margin: 0; background: #060611; color: #e7e7f5; font-family: ui-sans-serif, system-ui, -apple-system, "Segoe UI", Roboto, sans-serif; -webkit-font-smoothing: antialiased; }+ .post-wrap { max-width: 720px; margin: 0 auto; padding: 96px 24px 80px; }+ .post-meta { display: flex; flex-wrap: wrap; gap: 10px; align-items: center; color: #7a85a8; font-size: 13px; margin-bottom: 28px; }+ .post-date { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; }+ .post-tag { padding: 2px 8px; border-radius: 999px; background: rgba(154,212,255,.08); color: #9ad4ff; font-size: 11px; font-weight: 500; letter-spacing: 0.02em; text-transform: uppercase; }+ h1 { font-size: clamp(26px, 4vw, 40px); font-weight: 700; letter-spacing: -0.02em; line-height: 1.2; margin: 0 0 20px; }+ h2 { font-size: 20px; font-weight: 600; margin: 40px 0 12px; letter-spacing: -0.01em; }+ p { color: #c8c8e0; line-height: 1.7; margin: 0 0 18px; font-size: 16px; }+ ul, ol { color: #c8c8e0; line-height: 1.7; margin: 0 0 18px; padding-left: 24px; font-size: 16px; }+ li { margin-bottom: 6px; }+ a { color: #9ad4ff; text-decoration: none; }+ a:hover { text-decoration: underline; }+ code { font-family: ui-monospace, SFMono-Regular, Menlo, monospace; font-size: 13px; background: rgba(154,212,255,.07); color: #9ad4ff; padding: 2px 6px; border-radius: 4px; }+ pre { background: rgba(255,255,255,.04); border: 1px solid rgba(255,255,255,.08); border-radius: 8px; padding: 16px 20px; overflow-x: auto; margin: 0 0 20px; }+ pre code { background: none; padding: 0; font-size: 14px; }+ strong { color: #e7e7f5; }+ blockquote { margin: 0 0 18px; padding: 4px 0 4px 18px; border-left: 2px solid rgba(154,212,255,.4); color: #d8d8ee; font-style: italic; }+ .post-back { display: inline-flex; align-items: center; gap: 6px; color: #7a85a8; font-size: 14px; margin-bottom: 40px; text-decoration: none; }+ .post-back:hover { color: #9ad4ff; }+ hr { border: none; border-top: 1px solid rgba(255,255,255,.08); margin: 40px 0; }+ </style>+ <script type="application/ld+json">+ {+ "@context": "https://schema.org",+ "@type": "BlogPosting",+ "headline": "Showcasing the three.ws × IBM Partnership",+ "description": "three.ws and IBM showcased their partnership: a persistent, on-chain 3D agent embedded into any page as easily as a YouTube video, with the agent brain thinking on IBM watsonx.ai and Granite.",+ "image": "https://three.ws/ibm-og.png",+ "datePublished": "2026-06-02T15:00:00.000Z",+ "dateModified": "2026-06-02T15:00:00.000Z",+ "author": { "@type": "Organization", "name": "three.ws", "url": "https://three.ws" },+ "publisher": {+ "@type": "Organization",+ "name": "three.ws",+ "url": "https://three.ws",+ "logo": { "@type": "ImageObject", "url": "https://three.ws/og-image.png" }+ },+ "mainEntityOfPage": { "@type": "WebPage", "@id": "https://three.ws/blog/three-ws-ibm-collaboration" },+ "keywords": "three.ws, IBM, watsonx, watsonx.ai, Granite, partnership, 3D agents, on-chain agents, agent-3d, enterprise AI, MCP",+ "about": [+ { "@type": "Organization", "name": "IBM", "url": "https://www.ibm.com" },+ { "@type": "SoftwareApplication", "name": "IBM watsonx.ai", "applicationCategory": "AIApplication" }+ ]+ }+ </script>+</head>+<body>+ <div id="nav-container"></div>+ <main class="post-wrap">+ <a class="post-back" href="/blog">← Blog</a>+ <div class="post-meta">+ <span class="post-date">2026-06-02</span>+ <span class="post-tag">Partnership</span>+ <span class="post-tag">IBM</span>+ <span class="post-tag">watsonx</span>+ </div>+ <h1>Showcasing the three.ws × IBM Partnership</h1>++ <p><strong>three.ws and IBM showcased their partnership publicly.</strong> We shared a live demo of what the partnership makes possible — a persistent, on-chain 3D agent embedded into a page as easily as a YouTube video — and IBM's official account replied in the open:</p>++ <blockquote>"We're super excited about this."</blockquote>++ <p>This post is the longer version of that demo: what we showed, how the agent thinks on IBM watsonx.ai, and what the partnership unlocks for enterprise AI.</p>++ <h2>What we showed</h2>+ <p>The demo made one thing concrete: embedding a persistent, on-chain 3D agent into any platform should be as easy as embedding a YouTube video. One <code><agent-3d></code> tag, dropped into a page, deploys a full agent — no install, no plugin, no native app. It renders in any modern browser over WebGL.</p>+ <p>What lands on the page is not a chat box. It's a character with a face, a voice, memory, emotion, and an on-chain identity that persists across platforms. The goal of that frictionless deployment is simple: onboard the next millions of people to embodied AI without asking any of them to download anything.</p>++ <h2>Powered by IBM watsonx.ai</h2>+ <p>Behind the 3D body is a brain — and that brain can run on IBM watsonx.ai. The integration is real, in production, and open source. There is no mock path.</p>+ <p>Two layers connect three.ws to watsonx:</p>+ <ul>+ <li><strong>An open-source MCP server for watsonx.ai.</strong> three.ws ships <code>@three-ws/ibm-watsonx-mcp</code>, a <a href="https://modelcontextprotocol.io" rel="noopener">Model Context Protocol</a> server that exposes watsonx.ai — IBM Granite and any model in your account — to any MCP client (Claude Desktop, Claude Code, Cursor) as five tools: chat, text generation, embeddings, tokenization, and model discovery.</li>+ <li><strong>watsonx as a first-class agent-brain provider.</strong> watsonx is wired directly into the three.ws agent runtime. The streaming chat brain calls watsonx.ai's <code>/ml/v1/text/chat_stream</code> endpoint, authenticated with IBM Cloud IAM, scoped to your project, defaulting to <code>ibm/granite-3-8b-instruct</code>. When credentials are present, the agent thinks on Granite; when they're absent, the provider simply reports unavailable.</li>+ </ul>+ <p>Both layers run on <strong>your own IBM Cloud credentials</strong>. An API key is exchanged for a short-lived IAM bearer token, cached until just before expiry, and every inference call is scoped to your watsonx.ai project — no three.ws intermediary sits between your agent and IBM. The result: a 3D agent embedded on any page can reason on IBM Granite, running inside your own watsonx.ai project, governed by your IBM Cloud account.</p>++ <h2>A formal IBM partnership</h2>+ <p>This is a formal partnership: three.ws is a partner in IBM's Business Partner program. As <a href="/blog/three-ws-ibm-business-partner">we shared earlier</a>, that partnership brings together the open-source, browser-native, decentralized on-chain identity of three.ws with IBM's leadership in enterprise AI — and gives three.ws an integration path into IBM's AI and cloud portfolio, plus a route toward enterprise deployments in regulated industries.</p>++ <h2>Why enterprise AI needs a body</h2>+ <p>Enterprise AI deployments today are mostly headless — text in, text out, embedded in dashboards and chat windows that feel like forms. three.ws is the layer that gives those agents a persistent presence: a face that reacts to data, a voice, a body, and an identity that survives across surfaces. Concretely, it brings enterprise AI:</p>+ <ul>+ <li><strong>A 3D customer interface.</strong> Agents that look and move in response to the conversation, instead of a blinking cursor.</li>+ <li><strong>Browser-native delivery.</strong> No client install, no plugin — WebGL renders in every modern browser.</li>+ <li><strong>Decentralized identity.</strong> ERC-8004 on-chain identity means an agent persona persists and is verifiable without any single server being the point of trust.</li>+ <li><strong>High-security architecture.</strong> No private keys in client code; no centralized credential store for agent wallets.</li>+ <li><strong>Native x402 payments.</strong> Machine-to-machine micropayment settlement in USDC, without bespoke billing integrations.</li>+ </ul>++ <h2>Try it</h2>+ <p>The watsonx integration is open source and runnable today. Point it at your own IBM Cloud account:</p>+ <pre><code>WATSONX_API_KEY=... WATSONX_PROJECT_ID=... npx @three-ws/ibm-watsonx-mcp</code></pre>+ <p>You'll need an IBM Cloud account with watsonx.ai provisioned (<a href="https://dataplatform.cloud.ibm.com/registration/stepone?context=wx" rel="noopener">free tier available</a>), an <a href="https://cloud.ibm.com/iam/apikeys" rel="noopener">IBM Cloud API key</a>, and your watsonx.ai project id.</p>++ <h2>Links</h2>+ <ul>+ <li>IBM partner page: <a href="/ibm">three.ws/ibm</a></li>+ <li>watsonx.ai MCP server: <a href="https://www.npmjs.com/package/@three-ws/ibm-watsonx-mcp" rel="noopener">@three-ws/ibm-watsonx-mcp</a></li>+ <li>Open source: <a href="https://github.com/nirholas/three.ws" rel="noopener">github.com/nirholas/three.ws</a></li>+ <li>Project site: <a href="https://three.ws" rel="noopener">three.ws</a></li>+ </ul>++ <h2>Related</h2>+ <ul>+ <li><a href="/blog/three-ws-ibm-business-partner">three.ws Is Now an Official IBM Business Partner</a></li>+ <li><a href="/blog/agent-3d-web-component">We Just Shipped the 3D Layer for the Internet — <agent-3d></a></li>+ <li><a href="/blog/three-ws-on-anthropic-mcp-registry">three.ws Listed on Anthropic's Official MCP Registry</a></li>+ </ul>++ <hr>+ <p><a href="/blog">← All posts</a></p>+ </main>+ <div id="footer-container"></div>+ <script src="/nav.js"></script>+ <script src="/footer.js"></script>+</body>+</html>diff --git a/chat-plugin/README.md b/chat-plugin/README.mdindex 49ff64ff1..83f84f9c3 100644--- a/chat-plugin/README.md+++ b/chat-plugin/README.md@@ -1,12 +1,30 @@# @3dagent/chat-plugin-Render an embodied 3D avatar in the LobeChat sidebar. The avatar reacts to the LLM's tool calls — speaking, gesturing, and emoting — in real time.+Render an embodied 3D avatar in the **LobeChat** or **SperaxOS** sidebar. The avatar reacts to the LLM's tool calls — speaking, gesturing, and emoting — in real time.-> **Icon/screenshot note:** `assets/icon-256.svg` is a placeholder. Replace with a designed 256×256 PNG before submitting to the LobeHub plugin registry.+SperaxOS is a LobeChat-lineage host: both platforms speak an identical plugin+protocol, differing only in the channel prefix (`lobe-chat:` vs `speraxos:`). This+package targets both. The primary, no-bundle integration is the **standalone+manifest** (a hosted iframe the host frames directly); this React component is for+hosts that mount a plugin via a bundled SDK component.++> **Designed icon:** [`/sperax/icon-256.svg`](../public/sperax/icon-256.svg) is the production avatar referenced by the manifests. `assets/icon-256.svg` remains as a local fallback.----## One-click install (LobeChat ≥ 1.x)+## One-click install++### SperaxOS++1. Open **Plugins → Add Plugin → Custom Plugin** (or submit to the marketplace at `plugin.delivery`).+2. Paste the manifest URL:+ ```+ https://three.ws/.well-known/sperax-plugin.json+ ```+3. Click **Install**, then set your **Agent ID** (from `https://three.ws/dashboard`).+4. The avatar appears in the chat panel and reacts to the agent's tool calls.++### LobeChat (≥ 1.x)1. In LobeChat, open **Plugins → Plugin Store → Custom plugins**.2. Paste the manifest URL:@@ -21,9 +39,9 @@ Render an embodied 3D avatar in the LobeChat sidebar. The avatar reacts to the L## Configuration-| Setting | Type | Required | Default | Description |-| ----------- | -------- | -------- | ---------------------------- | -------------------------------------- |-| `agentId` | `string` | Yes | — | Agent UUID from the three.ws dashboard |+| Setting | Type | Required | Default | Description |+| ----------- | -------- | -------- | ------------------- | -------------------------------------- |+| `agentId` | `string` | Yes | — | Agent UUID from the three.ws dashboard || `apiOrigin` | `string` | No | `https://three.ws/` | Override for self-hosted instances |---@@ -31,36 +49,47 @@ Render an embodied 3D avatar in the LobeChat sidebar. The avatar reacts to the L## How it works```-LobeChat host- │ postMessage({ type: 'LobePlugin.renderPlugin', payload: { apiName, arguments } })- ▼-AgentPane (React sidebar component)- │ v1 bridge request: { v:1, source:'agent-host', kind:'request', op:'speak', payload }+Host (LobeChat / SperaxOS)+ │ postMessage({ type: '<ns>:init-standalone-plugin',+ │ payload: { apiName, arguments }, settings })▼-/lobehub/iframe/ (boot.js)- │ el.say(text, { sentiment })+Standalone iframe — /sperax/iframe/ (boot.js) ← primary path (no bundle)+ │ parses apiName + JSON.parse(arguments)▼-<agent-3d> web component — avatar speaks+<agent-3d> web component — avatar speaks / gestures / emotes```-When the LLM calls one of the plugin's tools (`speak`, `gesture`, `emote`, `render_agent`), LobeChat sends the tool args as a postMessage to the plugin iframe. `AgentPane` receives it, translates it into a bridge request, and the iframe's `boot.js` dispatches it to the `<agent-3d>` element.+`<ns>` is `lobe-chat` or `speraxos`. When the LLM calls one of the plugin's tools+(`speak`, `gesture`, `emote`, `render_agent`), the host renders the manifest's+`ui.url` iframe and delivers the triggering function call to it by postMessage. The+iframe's `boot.js` parses the call and drives the `<agent-3d>` element. The host's+plugin gateway also POSTs the arguments to the function's `api[].url`+(`/api/chat-plugin/<tool>`) to obtain the concise tool result the model reads back.++The React `AgentPane` component (this package) follows the same contract for hosts+that mount a bundled sidebar component instead of framing the manifest iframe.-### LobeChat message format+### Message format (verified)-LobeChat (and `@lobehub/chat-plugin-sdk` internally) sends:+Channel names are verified against `@lobehub/[email protected]` and the Sperax+`AI-Plugin-Marketplace-SDK`. The host posts:```json{- "type": "LobePlugin.renderPlugin",+ "type": "speraxos:init-standalone-plugin","payload": {+ "identifier": "three-ws","apiName": "speak",- "arguments": "{\"text\":\"Hello!\",\"sentiment\":0.5}",- "identifier": "3d-agent"- }+ "arguments": "{\"text\":\"Hello!\",\"sentiment\":0.5}"+ },+ "settings": { "agentId": "<uuid>" }}```-`AgentPane` listens for this on `window.addEventListener('message', ...)`. When `@lobehub/chat-plugin-sdk` ships a stable `usePluginStore` / `useWatchPluginMessage` hook that is directly callable for sidebar plugins, replace the listener with that hook so the React render cycle drives the effect.+`arguments` is a JSON **string**; `settings.agentId` binds the avatar. The same+shape applies with the `lobe-chat:` prefix on LobeChat. The iframe announces+readiness with `{ type: '<ns>:plugin-ready-for-render' }` so the host knows to+deliver the payload.### Wire protocol (v1)@@ -95,22 +124,25 @@ Full spec: [`01-embed-bridges.md`](../prompts/final-integration/01-embed-bridges## Dev harness-To test the plugin without running LobeChat:+Two harnesses live in `chat-plugin/dev/`:-```bash-# From repo root:-npm run build:lib # produces dist-lib/agent-3d.js (the <agent-3d> web component)-npm --prefix chat-plugin install-npm --prefix chat-plugin run build+- **`sperax.html`** — drives `boot.js` with the **exact** standalone-plugin wire+ protocol (`<ns>:plugin-ready-for-render` → `<ns>:init-standalone-plugin` tool+ calls). Toggle the namespace between `speraxos:` and `lobe-chat:`. This is the+ one to use when verifying the SperaxOS / LobeChat integration.+- **`index.html`** — drives the lower-level v1 bridge directly.-# Serve the repo root:-python3 -m http.server 8080+```bash+# From repo root, run the dev server (serves /lobehub/iframe/ + /api proxy):+npm run dev # http://localhost:3000-# Open in browser:-open http://localhost:8080/chat-plugin/dev/?agent=<your-agent-id>+# Open the protocol harness against it:+open http://localhost:3000/chat-plugin/dev/sperax.html?origin=http://localhost:3000&agent=<your-agent-id>```-The harness shows the agent iframe on the left and a control panel on the right. Click **Inject speak** to fire a fake assistant message and verify the avatar reacts.+Click **Load iframe**, wait for the green **plugin-ready ✓** dot, then **Inject+speak / gesture / emote** and watch the avatar react. Every postMessage is logged+in both directions.---diff --git a/chat-plugin/dev/sperax.html b/chat-plugin/dev/sperax.htmlnew file mode 100644index 000000000..968e73b7c--- /dev/null+++ b/chat-plugin/dev/sperax.html@@ -0,0 +1,345 @@+<!doctype html>+<html lang="en">+ <head>+ <meta charset="utf-8" />+ <title>three.ws — SperaxOS / LobeChat plugin protocol harness</title>+ <meta name="viewport" content="width=device-width, initial-scale=1" />+ <style>+ *,+ *::before,+ *::after {+ box-sizing: border-box;+ }+ body {+ margin: 0;+ font:+ 14px/1.5 system-ui,+ sans-serif;+ background: #0f0f10;+ color: #e0e0e0;+ display: flex;+ height: 100vh;+ overflow: hidden;+ }+ #sidebar {+ width: 420px;+ flex-shrink: 0;+ background: #151618;+ border-right: 1px solid #2a2a2e;+ display: flex;+ flex-direction: column;+ }+ #sidebar-header {+ padding: 12px 16px;+ border-bottom: 1px solid #2a2a2e;+ font-size: 12px;+ color: #888;+ letter-spacing: 0.05em;+ text-transform: uppercase;+ display: flex;+ align-items: center;+ gap: 8px;+ }+ #agent-frame {+ flex: 1;+ border: none;+ width: 100%;+ background: transparent;+ }+ #controls {+ flex: 1;+ padding: 24px;+ overflow-y: auto;+ display: flex;+ flex-direction: column;+ gap: 20px;+ }+ h1 {+ margin: 0 0 4px;+ font-size: 18px;+ font-weight: 600;+ }+ .subtitle {+ color: #888;+ font-size: 13px;+ margin: 0 0 8px;+ }+ .section {+ background: #151618;+ border: 1px solid #2a2a2e;+ border-radius: 8px;+ padding: 16px;+ }+ .section h2 {+ margin: 0 0 12px;+ font-size: 13px;+ font-weight: 600;+ color: #aaa;+ text-transform: uppercase;+ letter-spacing: 0.05em;+ }+ .row {+ display: flex;+ gap: 8px;+ align-items: center;+ margin-bottom: 8px;+ }+ label {+ font-size: 12px;+ color: #888;+ }+ input[type='text'],+ select {+ flex: 1;+ background: #0f0f10;+ border: 1px solid #333;+ border-radius: 6px;+ color: #e0e0e0;+ padding: 6px 10px;+ font: inherit;+ }+ input[type='range'] {+ flex: 1;+ }+ button {+ background: #6366f1;+ border: none;+ border-radius: 6px;+ color: #fff;+ cursor: pointer;+ font: inherit;+ font-size: 13px;+ padding: 6px 14px;+ white-space: nowrap;+ transition: background 0.15s;+ }+ button:hover {+ background: #4f46e5;+ }+ button.secondary {+ background: #2a2a2e;+ color: #ccc;+ }+ button.secondary:hover {+ background: #333;+ }+ #log {+ font: 12px/1.6 monospace;+ color: #93c5fd;+ background: #0a0a0c;+ border: 1px solid #1e2a3a;+ border-radius: 6px;+ padding: 10px;+ max-height: 240px;+ overflow-y: auto;+ white-space: pre-wrap;+ word-break: break-all;+ }+ .dot {+ display: inline-block;+ width: 8px;+ height: 8px;+ border-radius: 50%;+ background: #ef4444;+ }+ .dot.ready {+ background: #22c55e;+ }+ </style>+ </head>+ <body>+ <div id="sidebar">+ <div id="sidebar-header">+ <span id="dot" class="dot"></span>+ <span id="dot-label">waiting for plugin-ready…</span>+ </div>+ <iframe id="agent-frame" title="Agent embed" allow="microphone; camera"></iframe>+ </div>++ <div id="controls">+ <div>+ <h1>SperaxOS / LobeChat protocol harness</h1>+ <p class="subtitle">+ Drives <code>boot.js</code> with the exact standalone-plugin wire protocol —+ <code><ns>:plugin-ready-for-render</code> in, then+ <code><ns>:init-standalone-plugin</code> tool calls out. Verifies the+ avatar reacts without running a full host.+ </p>+ </div>++ <div class="section">+ <h2>Config</h2>+ <div class="row">+ <label style="width: 80px">Namespace</label>+ <select id="ns">+ <option value="speraxos">speraxos:</option>+ <option value="lobe-chat">lobe-chat:</option>+ </select>+ </div>+ <div class="row">+ <label style="width: 80px">Agent ID</label>+ <input type="text" id="agent-id" placeholder="agent UUID (sent via settings)" />+ </div>+ <div class="row">+ <label style="width: 80px">GLB URL</label>+ <input type="text" id="src" placeholder="optional — bypasses agent API" />+ </div>+ <div class="row">+ <label style="width: 80px">Origin</label>+ <input type="text" id="origin" value="http://localhost:3000" />+ </div>+ <div class="row">+ <button id="load">Load iframe</button>+ <button class="secondary" id="send-settings">Send settings.agentId</button>+ </div>+ </div>++ <div class="section">+ <h2>Inject tool call (host → plugin)</h2>+ <div class="row">+ <label style="width: 60px">Text</label>+ <input type="text" id="speak-text" value="Hello! I am your three.ws avatar." />+ </div>+ <div class="row">+ <label style="width: 60px">Sentiment</label>+ <input type="range" id="sentiment" min="-1" max="1" step="0.1" value="0.4" />+ <span id="sentiment-label">0.4</span>+ </div>+ <div class="row"><button id="speak">Inject speak</button></div>+ <div class="row" style="margin-top: 8px">+ <label style="width: 60px">Gesture</label>+ <select id="gesture-name">+ <option>wave</option>+ <option>nod</option>+ <option>point</option>+ <option>shrug</option>+ </select>+ <button id="gesture">Inject gesture</button>+ </div>+ <div class="row" style="margin-top: 8px">+ <label style="width: 60px">Emote</label>+ <select id="emote-trigger">+ <option>celebration</option>+ <option>curiosity</option>+ <option>concern</option>+ <option>patience</option>+ <option>empathy</option>+ </select>+ <button id="emote">Inject emote</button>+ </div>+ <div class="row" style="margin-top: 8px">+ <label style="width: 60px">Render</label>+ <input type="text" id="render-id" placeholder="agentId to render_agent" />+ <button id="render">Inject render_agent</button>+ </div>+ </div>++ <div class="section">+ <h2>postMessage log</h2>+ <div id="log">Waiting…</div>+ </div>+ </div>++ <script>+ const frame = document.getElementById('agent-frame');+ const logEl = document.getElementById('log');+ const dot = document.getElementById('dot');+ const dotLabel = document.getElementById('dot-label');+ const $ = (id) => document.getElementById(id);++ const log = (msg) => {+ logEl.textContent += '\n' + new Date().toISOString().slice(11, 23) + ' ' + msg;+ logEl.scrollTop = logEl.scrollHeight;+ };++ const ns = () => $('ns').value;+ const targetOrigin = () => $('origin').value.trim() || '*';++ // Post a message to the iframe exactly as a LobeChat/SperaxOS host would.+ function post(type, body) {+ const msg = { type: `${ns()}:${type}`, ...body };+ log('→ ' + JSON.stringify(msg));+ frame.contentWindow?.postMessage(msg, targetOrigin());+ }++ // A standalone tool call: payload.apiName + JSON-string arguments.+ function toolCall(apiName, args) {+ post('init-standalone-plugin', {+ payload: {+ identifier: 'three-ws',+ apiName,+ arguments: JSON.stringify(args),+ },+ settings: $('agent-id').value.trim()+ ? { agentId: $('agent-id').value.trim() }+ : undefined,+ });+ }++ function loadIframe() {+ const base = targetOrigin().replace(/\/$/, '');+ const params = new URLSearchParams({ host: location.origin, bg: 'transparent' });+ const src = $('src').value.trim();+ const agent = $('agent-id').value.trim();+ // In production, the neutral /sperax/iframe/ path is a Vercel rewrite to+ // the iframe. The Vite dev server applies no rewrites, so point straight+ // at the real file (/lobehub/iframe/index.html) when testing locally.+ const path = base.includes('localhost')+ ? '/lobehub/iframe/index.html'+ : '/sperax/iframe/';+ if (src) params.set('src', src);+ else if (agent) params.set('agent', agent);+ const url = `${base}${path}?${params}`;+ dot.className = 'dot';+ dotLabel.textContent = 'loading…';+ frame.src = url;+ log('→ load ' + url);+ }++ $('load').addEventListener('click', loadIframe);+ $('send-settings').addEventListener('click', () =>+ post('init-standalone-plugin', {+ settings: { agentId: $('agent-id').value.trim() },+ }),+ );+ $('speak').addEventListener('click', () =>+ toolCall('speak', {+ text: $('speak-text').value.trim(),+ sentiment: parseFloat($('sentiment').value),+ }),+ );+ $('gesture').addEventListener('click', () =>+ toolCall('gesture', { name: $('gesture-name').value }),+ );+ $('emote').addEventListener('click', () =>+ toolCall('emote', { trigger: $('emote-trigger').value, weight: 1 }),+ );+ $('render').addEventListener('click', () =>+ toolCall('render_agent', { agentId: $('render-id').value.trim() }),+ );+ $('sentiment').addEventListener('input', (e) => {+ $('sentiment-label').textContent = parseFloat(e.target.value).toFixed(1);+ });++ // Receive the plugin-ready signal and the v1 ready event from the iframe.+ window.addEventListener('message', (ev) => {+ const d = ev.data;+ if (!d || typeof d !== 'object') return;+ log('← ' + JSON.stringify(d));+ if (+ d.type === `${ns()}:plugin-ready-for-render` ||+ (typeof d.type === 'string' && d.type.endsWith(':plugin-ready-for-render'))+ ) {+ dot.className = 'dot ready';+ dotLabel.textContent = 'plugin-ready ✓';+ }+ });++ // Auto-load from query (?agent= / ?origin=).+ const qp = new URLSearchParams(location.search);+ if (qp.get('origin')) $('origin').value = qp.get('origin');+ if (qp.get('agent')) $('agent-id').value = qp.get('agent');+ if (qp.get('agent') || qp.get('src')) loadIframe();+ </script>+ </body>+</html>diff --git a/chat-plugin/src/AgentPane.tsx b/chat-plugin/src/AgentPane.tsxindex 5d31e88e1..ab04e7bcd 100644--- a/chat-plugin/src/AgentPane.tsx+++ b/chat-plugin/src/AgentPane.tsx@@ -7,15 +7,15 @@ export interface AgentPaneProps {}/**- * Sidebar plugin component that renders a three.ws avatar and- * forwards LobeChat tool-call payloads to the agent via the bridge.+ * Sidebar plugin component that renders a three.ws avatar and forwards+ * host tool-call payloads to the agent via the bridge.*- * LobeChat delivers tool calls by postMessage into the plugin iframe:- * { type: 'LobePlugin.renderPlugin', payload: { apiName, arguments } }- *- * When @lobehub/chat-plugin-sdk ships a stable usePluginStore hook,- * replace the window message listener below with that hook so the- * React render cycle drives the effect instead of a raw event.+ * The host (LobeChat or SperaxOS — a LobeChat-lineage platform) delivers a+ * standalone plugin's triggering function call by postMessage:+ * { type: '<ns>:init-standalone-plugin', payload: { apiName, arguments }, settings }+ * where `<ns>` is 'lobe-chat' or 'speraxos' and `arguments` is a JSON string.+ * Channel names are verified against @lobehub/chat-plugin-sdk and the Sperax+ * AI-Plugin-Marketplace-SDK.*/export const AgentPane: React.FC<AgentPaneProps> = ({ settings }) => {const iframeRef = useRef<HTMLIFrameElement>(null);@@ -44,34 +44,48 @@ export const AgentPane: React.FC<AgentPaneProps> = ({ settings }) => {};}, [settings.agentId]);- // Observe LobeChat tool calls delivered as postMessage to this plugin iframe.- //- // LobeChat sends: { type: 'LobePlugin.renderPlugin', payload: { apiName, arguments } }- // where `arguments` is a JSON string of the tool's input object.+ // Observe tool calls the host (LobeChat / SperaxOS) delivers by postMessage.//- // Fallback path: if LobeChat changes its message contract or a host-level fork- // dispatches { type: 'lobe:assistantMessage', detail: { content } } as a custom- // event, the second listener below handles that case.+ // Both platforms share an identical contract, differing only in the channel+ // prefix: 'lobe-chat:' vs 'speraxos:'. A standalone plugin receives its+ // triggering function call on the init-standalone-plugin (or render-plugin)+ // channel: { type, payload: { apiName, arguments }, settings }. `arguments` is+ // a JSON string; older builds nest the payload under `props`. We accept both.useEffect(() => {+ const isPluginCall = (type?: string) =>+ !!type &&+ (type.startsWith('lobe-chat:') || type.startsWith('speraxos:')) &&+ (type.endsWith('init-standalone-plugin') || type.endsWith('render-plugin'));+const handleMessage = (ev: MessageEvent) => {- if (!ev.data || typeof ev.data !== 'object') return;- const { type, payload } = ev.data as {- type?: string;- payload?: Record<string, unknown>;- };- if (type !== 'LobePlugin.renderPlugin' || !payload) return;+ const data = ev.data as Record<string, unknown> | null;+ if (!data || typeof data !== 'object') return;+ if (!isPluginCall(data['type'] as string)) return;++ const payload = (data['payload'] || data['props'] || {}) as Record<string, unknown>;+ const apiName = (payload['apiName'] || payload['name']) as string | undefined;- const apiName = payload['apiName'] as string | undefined;let args: Record<string, unknown> = {};- try {- args = JSON.parse((payload['arguments'] as string) || '{}');- } catch {- return;+ const raw = payload['arguments'];+ if (typeof raw === 'string') {+ try {+ args = JSON.parse(raw || '{}');+ } catch {+ args = {};+ }+ } else if (raw && typeof raw === 'object') {+ args = raw as Record<string, unknown>;}const bridge = bridgeRef.current;if (!bridge) return;+ // Re-bind if the host pushed an updated agentId in settings.+ const settings = data['settings'] as Record<string, unknown> | undefined;+ if (settings && typeof settings['agentId'] === 'string') {+ bridge.setAgent(settings['agentId']).catch(() => undefined);+ }+switch (apiName) {case 'speak':if (typeof args['text'] === 'string') {@@ -99,6 +113,7 @@ export const AgentPane: React.FC<AgentPaneProps> = ({ settings }) => {}break;case 'render_agent':+ case 'render-agent':if (typeof args['agentId'] === 'string') {bridge.setAgent(args['agentId']).catch(() => undefined);}diff --git a/data/rss/items.json b/data/rss/items.jsonindex 9a5a7c603..3f88ca3ef 100644--- a/data/rss/items.json+++ b/data/rss/items.json@@ -1,6 +1,24 @@{"_readme": "Curated RSS items for https://three.ws/rss/announcements.xml. Edit this file to control exactly what HackerNoon (and any RSS reader) sees. Each entry needs: id (stable slug), title, date (ISO 8601), body_html. Optional: link, author, summary, tags. Items are served newest-first by date; cap is 50. Seeded from data/archives/trythreews_tweets_2026-05-16.json on 2026-05-16 (35 entries). Re-run scripts/seed-rss-from-archive.mjs to refresh from a newer scrape.","items": [+ {+ "id": "ibm-collaboration-showcase",+ "title": "Showcasing the three.ws × IBM Partnership",+ "date": "2026-06-02T15:00:00.000Z",+ "link": "https://three.ws/blog/three-ws-ibm-collaboration",+ "author": "three.ws",+ "summary": "three.ws and IBM showcased their formal partnership: a persistent, on-chain 3D agent embedded into any page as easily as a YouTube video — with the agent brain thinking on IBM watsonx.ai and Granite. The integration ships as an open-source MCP server and a first-class watsonx provider in the three.ws agent runtime, running on your own IBM Cloud credentials.",+ "body_html": "<p><strong>three.ws and IBM showcased their partnership publicly.</strong> We shared a live demo of what the partnership makes possible — a persistent, on-chain 3D agent embedded into a page as easily as a YouTube video — and IBM's official account replied in the open: <em>\"We're super excited about this.\"</em></p>\n<h2>What we showed</h2>\n<p>Embedding a persistent, on-chain 3D agent into any platform should be as easy as embedding a YouTube video. One <code><agent-3d></code> tag deploys a full agent — no install, no plugin, no native app — rendered in any modern browser over WebGL. What lands on the page is a character with a face, a voice, memory, emotion, and an on-chain identity that persists across platforms. The goal of that frictionless deployment: onboard the next millions of people to embodied AI without asking any of them to download anything.</p>\n<h2>Powered by IBM watsonx.ai</h2>\n<p>Behind the 3D body is a brain — and that brain can run on IBM watsonx.ai. The integration is real, in production, and open source, with no mock path. Two layers connect three.ws to watsonx:</p>\n<ul>\n<li><strong>An open-source MCP server for watsonx.ai.</strong> <code>@three-ws/ibm-watsonx-mcp</code> exposes watsonx.ai — IBM Granite and any model in your account — to any MCP client (Claude Desktop, Claude Code, Cursor) as five tools: chat, text generation, embeddings, tokenization, and model discovery.</li>\n<li><strong>watsonx as a first-class agent-brain provider.</strong> watsonx is wired directly into the three.ws agent runtime. The streaming chat brain calls watsonx.ai's <code>/ml/v1/text/chat_stream</code> endpoint, authenticated with IBM Cloud IAM, scoped to your project, defaulting to <code>ibm/granite-3-8b-instruct</code>.</li>\n</ul>\n<p>Both layers run on your own IBM Cloud credentials — an API key is exchanged for a short-lived IAM token and every inference call is scoped to your watsonx.ai project, with no three.ws intermediary between your agent and IBM. A 3D agent embedded on any page can reason on IBM Granite, running inside your own watsonx.ai project, governed by your IBM Cloud account.</p>\n<h2>A formal IBM partnership</h2>\n<p>This is a formal partnership: three.ws is a partner in IBM's Business Partner program, bringing together the open-source, browser-native, decentralized on-chain identity of three.ws with IBM's leadership in enterprise AI — and an integration path into IBM's AI and cloud portfolio.</p>\n<h2>Try it</h2>\n<p>The watsonx integration is open source and runnable today against your own IBM Cloud account: <code>WATSONX_API_KEY=... WATSONX_PROJECT_ID=... npx @three-ws/ibm-watsonx-mcp</code></p>\n<h2>Related</h2>\n<ul>\n<li><a href=\"https://three.ws/blog/three-ws-ibm-collaboration\">Full announcement on the three.ws blog</a></li>\n<li><a href=\"https://three.ws/blog/three-ws-ibm-business-partner\">three.ws Is Now an Official IBM Business Partner</a></li>\n<li><a href=\"https://three.ws/blog/agent-3d-web-component\">We Just Shipped the 3D Layer for the Internet — <agent-3d></a></li>\n</ul>",+ "tags": [+ "partnership",+ "ibm",+ "watsonx",+ "granite",+ "enterprise",+ "mcp",+ "agent-3d"+ ]+ },{"id": "joined-aws-partner-network","title": "three.ws Joins the AWS Partner Network",diff --git a/docs/embedding.md b/docs/embedding.mdindex 9174f36a2..aa7aa57f5 100644--- a/docs/embedding.md+++ b/docs/embedding.md@@ -12,6 +12,7 @@| [iframe embed](#iframe-embed) | Very low | Limited (postMessage) | Third-party pages, CMS platforms, sandboxed contexts || [oEmbed (paste URL)](#oembed) | None | None | Notion, Ghost, Substack, WordPress || [Claude Artifact](#claude-artifact) | None | None | AI-generated interactive demos in Claude.ai |+| [Chat plugin](#chat-plugins-speraxos--lobechat) | None | Tool-driven | SperaxOS / LobeChat — the agent gets a body in the chat |If you control the page, use the web component. If you're pasting into a CMS or embedding in a third-party context, use the iframe. If you just want to share a link and let the platform render it, paste the widget URL and let oEmbed do the rest.@@ -396,6 +397,48 @@ You can also configure embed policy via Dashboard → Agent Settings → Embed P---+## Chat plugins (SperaxOS / LobeChat)++Give an agent a body inside an AI chat host. SperaxOS and LobeChat are the same plugin lineage, so three.ws ships one **standalone plugin** that targets both — a hosted iframe the platform frames in its chat panel, plus four LLM-callable tools. When the model calls a tool, the avatar speaks, gestures, or shifts its body language in real time.++### Install++Paste the manifest URL into the host's custom-plugin dialog:++| Host | Manifest URL |+|------|--------------|+| SperaxOS | `https://three.ws/.well-known/sperax-plugin.json` |+| LobeChat | `https://three.ws/.well-known/chat-plugin.json` |++Then set the one setting — your **Agent ID** (a UUID or `@handle` from the dashboard). No API key, no bundle to install.++### Tools the model can call++| Tool | Arguments | Effect |+|------|-----------|--------|+| `render_agent` | `{ agentId }` | Bind / swap the avatar to an agent |+| `speak` | `{ text, sentiment? }` | Speak aloud with emotional valence (`-1`…`1`) |+| `gesture` | `{ name: wave\|nod\|point\|shrug }` | Play a physical gesture |+| `emote` | `{ trigger, weight? }` | Blend an emotion into the Empathy Layer |++### Protocol++The host renders the manifest's `ui.url` iframe and delivers the triggering call over postMessage. Channel names differ only by prefix — `speraxos:` on SperaxOS, `lobe-chat:` on LobeChat — and are otherwise identical:++```json+{+ "type": "speraxos:init-standalone-plugin",+ "payload": { "apiName": "speak", "arguments": "{\"text\":\"Hi\",\"sentiment\":0.4}" },+ "settings": { "agentId": "<uuid>" }+}+```++The iframe announces itself with `{ type: '<ns>:plugin-ready-for-render' }`, then parses `payload.apiName` + the JSON-string `payload.arguments` and drives the `<agent-3d>` element. In parallel, the host's gateway POSTs the arguments to the tool's endpoint (`/api/chat-plugin/{tool}`, with the user's settings in the `Sperax-Plugin-Settings` header) to get the concise result the model reads back.++Full setup, submission, and chain notes: [`/sperax/README.md`](https://three.ws/sperax/README.md).++---+## oEmbedMany platforms support oEmbed — paste a URL and the platform auto-fetches a rich preview. No code required.diff --git a/pages/ibm/index.html b/pages/ibm/index.htmlnew file mode 100644index 000000000..02244b1e1--- /dev/null+++ b/pages/ibm/index.html@@ -0,0 +1,282 @@+<!doctype html>+<html lang="en">+<head>+ <meta charset="utf-8" />+ <meta name="viewport" content="width=device-width,initial-scale=1" />+ <title>three.ws on IBM watsonx — 3D AI Agent Platform · IBM Business Partner</title>+ <meta name="description" content="three.ws is an IBM Business Partner. Open-source 3D AI agents that think on IBM Granite via watsonx.ai and give watsonx Orchestrate agents a face, voice, and on-chain identity — embed anywhere with one tag." />+ <link rel="canonical" href="https://three.ws/ibm" />++ <meta property="og:type" content="website" />+ <meta property="og:title" content="three.ws on IBM watsonx — 3D AI Agent Platform" />+ <meta property="og:description" content="Open-source 3D AI agents on IBM watsonx.ai and Granite. IBM Business Partner. Give watsonx Orchestrate a 3D body, voice, and on-chain identity." />+ <meta property="og:url" content="https://three.ws/ibm" />+ <meta property="og:image" content="https://three.ws/og-image.png" />++ <meta name="twitter:card" content="summary_large_image" />+ <meta name="twitter:title" content="three.ws on IBM watsonx" />+ <meta name="twitter:description" content="Open-source 3D AI agents on IBM watsonx.ai and Granite. IBM Business Partner." />+ <meta name="twitter:image" content="https://three.ws/og-image.png" />++ <link rel="icon" href="/favicon.ico" />+ <style>+ :root { color-scheme: dark; --accent:#ffffff; --accent2:#cccccc; --border:#222222; --bg:#000000; --panel:#141414; --panel2:#1a1a1a; --text:#e8e8f0; --muted:#888888; --green:#22c55e; --ibm:#0f62fe; --ibm-light:#78a9ff; }+ * { box-sizing: border-box; margin: 0; padding: 0; }+ body { font: 16px/1.6 -apple-system, system-ui, "Segoe UI", Roboto, sans-serif; color: var(--text); background: var(--bg); min-height: 100vh; }++ header { padding: 18px 24px; border-bottom: 1px solid var(--border); display: flex; align-items: center; justify-content: space-between; max-width: 1100px; margin: 0 auto; }+ header a.home { color: var(--text); text-decoration: none; font-weight: 600; font-size: 15px; letter-spacing: -0.01em; }+ header nav { display: flex; gap: 22px; align-items: center; }+ header nav a { color: var(--muted); text-decoration: none; font-size: 14px; transition: color 0.15s; }+ header nav a:hover { color: var(--text); }++ main { max-width: 880px; margin: 0 auto; padding: 80px 24px 120px; }++ .partner-badge { display: inline-flex; align-items: center; gap: 10px; background: var(--panel); border: 1px solid var(--border); border-radius: 99px; padding: 7px 16px 7px 12px; font-size: 13px; color: var(--muted); margin-bottom: 32px; }+ .partner-badge .dot { width: 8px; height: 8px; border-radius: 50%; background: var(--ibm); box-shadow: 0 0 12px var(--ibm); }+ .partner-badge strong { color: var(--text); font-weight: 500; }++ h1 { font-size: clamp(36px, 6vw, 56px); letter-spacing: -0.03em; line-height: 1.05; font-weight: 600; margin-bottom: 20px; }+ h1 .gradient { background: linear-gradient(110deg, var(--ibm-light) 25%, var(--ibm) 80%); -webkit-background-clip: text; background-clip: text; color: transparent; }++ .lede { font-size: clamp(17px, 2vw, 19px); color: var(--muted); line-height: 1.55; max-width: 640px; margin-bottom: 40px; }+ .lede strong { color: var(--text); font-weight: 500; }++ .cta-row { display: flex; gap: 12px; flex-wrap: wrap; margin-bottom: 80px; }+ .btn { display: inline-flex; align-items: center; gap: 8px; padding: 13px 22px; border-radius: 11px; border: 0; font-size: 14px; font-weight: 600; text-decoration: none; cursor: pointer; transition: filter 0.15s, transform 0.15s; }+ .btn-primary { background: var(--ibm); color: #fff; }+ .btn-primary:hover { filter: brightness(1.12); }+ .btn-sec { background: var(--panel); border: 1px solid var(--border); color: var(--text); }+ .btn-sec:hover { background: var(--panel2); }+ .btn svg { width: 16px; height: 16px; }++ section { margin-bottom: 80px; }+ section h2 { font-size: clamp(24px, 3.5vw, 32px); letter-spacing: -0.02em; line-height: 1.15; font-weight: 600; margin-bottom: 16px; }+ section .sub { color: var(--muted); font-size: 16px; margin-bottom: 32px; max-width: 620px; }++ .benefit-grid { display: grid; grid-template-columns: repeat(auto-fit, minmax(240px, 1fr)); gap: 16px; }+ .benefit { background: var(--panel); border: 1px solid var(--border); border-radius: 14px; padding: 22px; }+ .benefit .icon { width: 36px; height: 36px; border-radius: 9px; background: rgba(15,98,254,0.10); border: 1px solid rgba(120,169,255,0.25); display: flex; align-items: center; justify-content: center; margin-bottom: 14px; }+ .benefit h3 { font-size: 15px; font-weight: 600; margin-bottom: 6px; letter-spacing: -0.01em; }+ .benefit p { font-size: 14px; color: var(--muted); line-height: 1.55; }++ .platform-grid { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }+ .platform { background: var(--panel); border: 1px solid var(--border); border-radius: 14px; padding: 20px 22px; }+ .platform .label { font-size: 12px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.08em; margin-bottom: 8px; }+ .platform .name { font-size: 17px; font-weight: 600; margin-bottom: 4px; }+ .platform .desc { font-size: 13px; color: var(--muted); }++ .endpoints { background: var(--panel); border: 1px solid var(--border); border-radius: 14px; overflow: hidden; }+ .endpoint { padding: 16px 22px; border-bottom: 1px solid var(--border); display: grid; grid-template-columns: auto 1fr; gap: 22px; align-items: baseline; }+ .endpoint:last-child { border-bottom: none; }+ .endpoint code { font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace; font-size: 13px; color: var(--ibm-light); white-space: nowrap; }+ .endpoint .desc { font-size: 14px; color: var(--muted); }+ .endpoint .desc code { white-space: normal; }++ .code-block { background: var(--panel); border: 1px solid var(--border); border-radius: 14px; padding: 20px 22px; font-family: ui-monospace, "SF Mono", Menlo, Consolas, monospace; font-size: 13px; line-height: 1.7; color: var(--text); overflow-x: auto; }+ .code-block .c { color: var(--muted); }+ .code-block .k { color: var(--ibm-light); }++ .note { background: var(--panel); border: 1px solid var(--border); border-radius: 12px; padding: 16px 20px; font-size: 14px; color: var(--muted); margin-top: 12px; }+ .note strong { color: var(--text); }+ .note a { color: var(--ibm-light); text-decoration: none; }+ .note a:hover { text-decoration: underline; }++ .footer { text-align: center; color: var(--muted); font-size: 13px; padding: 40px 24px 60px; border-top: 1px solid var(--border); }+ .footer a { color: var(--muted); text-decoration: none; }+ .footer a:hover { color: var(--text); }++ .disclaimer { font-size: 12px; color: var(--muted); margin-top: 60px; line-height: 1.55; max-width: 700px; }++ @media (max-width: 720px) {+ .platform-grid { grid-template-columns: 1fr; }+ main { padding: 56px 20px 96px; }+ .endpoint { grid-template-columns: 1fr; gap: 4px; }+ .endpoint code { white-space: normal; }+ }+ </style>+</head>+<body>+ <header>+ <a href="/" class="home">three.ws</a>+ <nav>+ <a href="/discover">Discover</a>+ <a href="/docs">Docs</a>+ <a href="https://github.com/nirholas/three.ws" target="_blank" rel="noopener">GitHub</a>+ </nav>+ </header>++ <main>+ <div class="partner-badge">+ <span class="dot"></span>+ <strong>IBM Business Partner</strong>+ <span>·</span>+ <span>watsonx.ai + Orchestrate</span>+ </div>++ <h1>three.ws on <span class="gradient">IBM watsonx</span>.</h1>+ <p class="lede">+ three.ws is an open-source 3D AI agent platform — WebGL viewer, LLM-driven runtime, on-chain identity, embed anywhere with one tag. <strong>An IBM Business Partner.</strong> Agents think on IBM Granite through watsonx.ai, and a watsonx Orchestrate agent gets a face, a voice, and a body that lives in the browser.+ </p>++ <div class="cta-row">+ <a href="https://three.ws" class="btn btn-primary">+ Try three.ws+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M5 12h14M13 5l7 7-7 7"/></svg>+ </a>+ <a href="https://github.com/nirholas/three.ws" class="btn btn-sec" target="_blank" rel="noopener">+ <svg viewBox="0 0 24 24" fill="currentColor"><path d="M12 .3C5.4.3 0 5.7 0 12.3c0 5.3 3.4 9.8 8.2 11.4.6.1.8-.3.8-.6v-2.1c-3.3.7-4-1.6-4-1.6-.6-1.4-1.4-1.8-1.4-1.8-1.1-.7.1-.7.1-.7 1.2.1 1.9 1.2 1.9 1.2 1.1 1.8 2.9 1.3 3.6 1 .1-.8.4-1.3.8-1.6-2.7-.3-5.5-1.3-5.5-5.9 0-1.3.5-2.4 1.2-3.2-.1-.3-.5-1.5.1-3.2 0 0 1-.3 3.3 1.2 1-.3 2-.4 3-.4s2 .1 3 .4c2.3-1.5 3.3-1.2 3.3-1.2.7 1.7.2 2.9.1 3.2.8.8 1.2 1.9 1.2 3.2 0 4.6-2.8 5.6-5.5 5.9.4.4.8 1.1.8 2.2v3.3c0 .3.2.7.8.6 4.8-1.6 8.2-6.1 8.2-11.4C24 5.7 18.6.3 12 .3z"/></svg>+ View source+ </a>+ <a href="/blog/three-ws-ibm-collaboration" class="btn btn-sec">+ Read the announcement+ </a>+ </div>++ <section>+ <h2>Built on IBM watsonx.</h2>+ <p class="sub">The agent brain runs on your own IBM Cloud account. Real inference, real IAM auth, no mock path.</p>++ <div class="benefit-grid">+ <div class="benefit">+ <div class="icon">+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#78a9ff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="3"/><path d="M12 2v3M12 19v3M2 12h3M19 12h3M5 5l2 2M17 17l2 2M19 5l-2 2M7 17l-2 2"/></svg>+ </div>+ <h3>Granite-powered brain</h3>+ <p>Agents reason on <code>ibm/granite-3-8b-instruct</code> by default — or any foundation model in your watsonx.ai account. Streaming chat over the watsonx text endpoint.</p>+ </div>+ <div class="benefit">+ <div class="icon">+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#78a9ff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><rect x="3" y="11" width="18" height="11" rx="2"/><path d="M7 11V7a5 5 0 0 1 10 0v4"/></svg>+ </div>+ <h3>Your IBM Cloud, your keys</h3>+ <p>An IBM Cloud API key is exchanged for a short-lived IAM bearer token and every call is scoped to your project. No three.ws intermediary sits between your agent and IBM.</p>+ </div>+ <div class="benefit">+ <div class="icon">+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#78a9ff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M8 12a4 4 0 0 1 8 0M12 8v8"/></svg>+ </div>+ <h3>watsonx Orchestrate, embodied</h3>+ <p>Point three.ws at a watsonx Orchestrate (Agent Connect) endpoint and your enterprise agent gets a 3D front-end — gestures, emotion, voice, and lip-sync.</p>+ </div>+ <div class="benefit">+ <div class="icon">+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#78a9ff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M4 7l8-4 8 4-8 4-8-4z"/><path d="M4 12l8 4 8-4M4 17l8 4 8-4"/></svg>+ </div>+ <h3>Open-source MCP server</h3>+ <p><code>@three-ws/ibm-watsonx-mcp</code> exposes watsonx.ai to Claude Desktop, Claude Code, Cursor, and any MCP host as five tools: chat, generate, embed, tokenize, and model discovery.</p>+ </div>+ <div class="benefit">+ <div class="icon">+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#78a9ff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="12" cy="12" r="10"/><path d="M2 12h20M12 2a15 15 0 0 1 0 20 15 15 0 0 1 0-20z"/></svg>+ </div>+ <h3>Every watsonx region</h3>+ <p>Route to <code>us-south</code>, <code>eu-de</code>, <code>eu-gb</code>, <code>jp-tok</code>, <code>au-syd</code>, or <code>ca-tor</code> with one environment variable — data stays in the region you choose.</p>+ </div>+ <div class="benefit">+ <div class="icon">+ <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#78a9ff" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><path d="M20 6L9 17l-5-5"/></svg>+ </div>+ <h3>No mock path</h3>+ <p>When credentials are present the agent thinks on Granite; when they're absent the provider reports unavailable. Auth and upstream errors surface as the real cause.</p>+ </div>+ </div>+ </section>++ <section>+ <h2>What you get.</h2>+ <p class="sub">Everything in three.ws — open source, production-ready, runs in any modern browser.</p>++ <div class="platform-grid">+ <div class="platform">+ <div class="label">Viewer</div>+ <div class="name">WebGL 3D Engine</div>+ <div class="desc">three.js r176, glTF 2.0 / GLB with Draco + KTX2, PBR materials, animations, morph targets.</div>+ </div>+ <div class="platform">+ <div class="label">Runtime</div>+ <div class="name">watsonx-Powered Brain</div>+ <div class="desc">Tool-loop runtime with gestures, emotion blending, memory, voice, and lip-sync — driven by IBM Granite on watsonx.ai or a watsonx Orchestrate agent.</div>+ </div>+ <div class="platform">+ <div class="label">Identity</div>+ <div class="name">On-Chain Registration</div>+ <div class="desc">ERC-8004 tokens on EVM chains and Metaplex Core assets on Solana. Signed action history, reputation scores.</div>+ </div>+ <div class="platform">+ <div class="label">Distribution</div>+ <div class="name"><agent-3d> Web Component</div>+ <div class="desc">One element, no framework dependency. Drop into any page. Embed an agent as easily as a YouTube video.</div>+ </div>+ <div class="platform">+ <div class="label">Protocols</div>+ <div class="name">MCP + OAuth 2.1 + x402</div>+ <div class="desc">Native Model Context Protocol endpoint, full OAuth 2.1 authorization server, x402 paid endpoints on Base + Solana.</div>+ </div>+ <div class="platform">+ <div class="label">License</div>+ <div class="name">Apache 2.0</div>+ <div class="desc">Entire stack — viewer, runtime, contracts, backend, web component, watsonx integration — open source. No lock-in.</div>+ </div>+ </div>+ </section>++ <section>+ <h2>The integration.</h2>+ <p class="sub">watsonx.ai and watsonx Orchestrate are first-class providers in the three.ws chat runtime, alongside an open-source MCP server. All grounded in real REST contracts.</p>++ <div class="endpoints">+ <div class="endpoint">+ <code>POST /api/chat</code>+ <div class="desc"><code>{ "provider": "watsonx" }</code> streams from watsonx.ai's <code>/ml/v1/text/chat_stream</code> on IBM Granite. IAM bearer minted from <code>WATSONX_API_KEY</code>, scoped to <code>WATSONX_PROJECT_ID</code>.</div>+ </div>+ <div class="endpoint">+ <code>POST /api/chat</code>+ <div class="desc"><code>{ "provider": "orchestrate" }</code> calls a watsonx Orchestrate (Agent Connect) OpenAI-compatible <code>/chat/completions</code> endpoint — the 3D avatar becomes the front-end of your enterprise agent.</div>+ </div>+ <div class="endpoint">+ <code>npx @three-ws/ibm-watsonx-mcp</code>+ <div class="desc">Standalone MCP server for watsonx.ai — five tools against IBM Granite and any model in your account. Works with any MCP host.</div>+ </div>+ </div>++ <div class="code-block">+<span class="c"># Run a three.ws agent on IBM Granite, in your own watsonx.ai project</span>+<span class="k">curl</span> https://three.ws/api/chat \+ -H 'content-type: application/json' \+ -d '{ <span class="k">"provider"</span>: <span class="k">"watsonx"</span>, <span class="k">"message"</span>: <span class="k">"Introduce yourself."</span> }'++<span class="c"># Or expose watsonx.ai to any MCP client with your IBM Cloud credentials</span>+<span class="k">WATSONX_API_KEY</span>=... <span class="k">WATSONX_PROJECT_ID</span>=... npx @three-ws/ibm-watsonx-mcp+ </div>++ <div class="note">+ <strong>Open source.</strong> The watsonx.ai client is at <a href="https://github.com/nirholas/three.ws/blob/main/api/_lib/watsonx.js" target="_blank" rel="noopener">api/_lib/watsonx.js</a>, the Orchestrate provider at <a href="https://github.com/nirholas/three.ws/blob/main/api/_lib/orchestrate.js" target="_blank" rel="noopener">api/_lib/orchestrate.js</a>, and the MCP server at <a href="https://github.com/nirholas/three.ws/tree/main/packages/ibm-watsonx-mcp" target="_blank" rel="noopener">packages/ibm-watsonx-mcp/</a>. Review it, fork it, run your own.+ </div>+ </section>++ <section>+ <h2>Give your IBM watsonx agent a body.</h2>+ <p class="sub">Bring an embodied 3D front-end to your watsonx.ai or watsonx Orchestrate deployment — in the browser, with no install.</p>++ <div class="cta-row">+ <a href="https://three.ws" class="btn btn-primary">+ Use three.ws now+ <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.5" stroke-linecap="round"><path d="M5 12h14M13 5l7 7-7 7"/></svg>+ </a>+ <a href="https://github.com/nirholas/three.ws" class="btn btn-sec" target="_blank" rel="noopener">Star on GitHub</a>+ <a href="mailto:[email protected]?subject=IBM%20watsonx%20%2B%20three.ws" class="btn btn-sec">Contact us</a>+ </div>+ </section>++ <p class="disclaimer">+ three.ws is an independent IBM Business Partner. The <code>@three-ws/ibm-watsonx-mcp</code> package is community-built and is not an IBM product. IBM, watsonx, watsonx.ai, watsonx Orchestrate, IBM Cloud, and Granite are trademarks of International Business Machines Corporation, registered in many jurisdictions worldwide. Use of watsonx requires your own IBM Cloud account, subject to IBM's terms.+ </p>+ </main>++ <div class="footer">+ <a href="/">three.ws</a> · <a href="/blog/three-ws-ibm-collaboration">IBM partnership</a> · <a href="/docs">Docs</a> · <a href="/legal/privacy">Privacy</a> · <a href="/legal/tos">Terms</a>+ </div>+ <script src="/brand.js" defer></script>+</body>+</html>diff --git a/public/.well-known/lobehub-plugin.json b/public/.well-known/lobehub-plugin.jsonindex dbe230f6c..51e2dcbaf 100644--- a/public/.well-known/lobehub-plugin.json+++ b/public/.well-known/lobehub-plugin.json@@ -8,7 +8,7 @@"meta": {"title": "three.ws","description": "Embed any on-chain or off-chain three.ws as an embodied avatar inside your chat.",- "avatar": "https://three.ws/favicon.png",+ "avatar": "https://three.ws/pwa-icon.svg","tags": ["3d", "avatar", "embodied-agent", "erc-8004"]},"ui": {@@ -24,7 +24,7 @@},"api": [{- "url": "https://three.ws/api/mcp",+ "url": "https://three.ws/api/chat-plugin/render-agent","name": "render_agent","description": "Mount the 3D avatar for a given agent id.","parameters": {@@ -39,7 +39,7 @@}},{- "url": "https://three.ws/api/mcp",+ "url": "https://three.ws/api/chat-plugin/speak","name": "speak","description": "Make the avatar speak with optional emotional valence.","parameters": {@@ -60,7 +60,7 @@}},{- "url": "https://three.ws/api/mcp",+ "url": "https://three.ws/api/chat-plugin/gesture","name": "gesture","description": "Trigger a named gesture on the avatar.","parameters": {@@ -75,7 +75,7 @@}},{- "url": "https://three.ws/api/mcp",+ "url": "https://three.ws/api/chat-plugin/emote","name": "emote","description": "Inject an emotion into the avatar's Empathy Layer blend.","parameters": {diff --git a/public/docs/embedding.md b/public/docs/embedding.mdindex 9174f36a2..aa7aa57f5 100644--- a/public/docs/embedding.md+++ b/public/docs/embedding.md@@ -12,6 +12,7 @@| [iframe embed](#iframe-embed) | Very low | Limited (postMessage) | Third-party pages, CMS platforms, sandboxed contexts || [oEmbed (paste URL)](#oembed) | None | None | Notion, Ghost, Substack, WordPress || [Claude Artifact](#claude-artifact) | None | None | AI-generated interactive demos in Claude.ai |+| [Chat plugin](#chat-plugins-speraxos--lobechat) | None | Tool-driven | SperaxOS / LobeChat — the agent gets a body in the chat |If you control the page, use the web component. If you're pasting into a CMS or embedding in a third-party context, use the iframe. If you just want to share a link and let the platform render it, paste the widget URL and let oEmbed do the rest.@@ -396,6 +397,48 @@ You can also configure embed policy via Dashboard → Agent Settings → Embed P---+## Chat plugins (SperaxOS / LobeChat)++Give an agent a body inside an AI chat host. SperaxOS and LobeChat are the same plugin lineage, so three.ws ships one **standalone plugin** that targets both — a hosted iframe the platform frames in its chat panel, plus four LLM-callable tools. When the model calls a tool, the avatar speaks, gestures, or shifts its body language in real time.++### Install++Paste the manifest URL into the host's custom-plugin dialog:++| Host | Manifest URL |+|------|--------------|+| SperaxOS | `https://three.ws/.well-known/sperax-plugin.json` |+| LobeChat | `https://three.ws/.well-known/chat-plugin.json` |++Then set the one setting — your **Agent ID** (a UUID or `@handle` from the dashboard). No API key, no bundle to install.++### Tools the model can call++| Tool | Arguments | Effect |+|------|-----------|--------|+| `render_agent` | `{ agentId }` | Bind / swap the avatar to an agent |+| `speak` | `{ text, sentiment? }` | Speak aloud with emotional valence (`-1`…`1`) |+| `gesture` | `{ name: wave\|nod\|point\|shrug }` | Play a physical gesture |+| `emote` | `{ trigger, weight? }` | Blend an emotion into the Empathy Layer |++### Protocol++The host renders the manifest's `ui.url` iframe and delivers the triggering call over postMessage. Channel names differ only by prefix — `speraxos:` on SperaxOS, `lobe-chat:` on LobeChat — and are otherwise identical:++```json+{+ "type": "speraxos:init-standalone-plugin",+ "payload": { "apiName": "speak", "arguments": "{\"text\":\"Hi\",\"sentiment\":0.4}" },+ "settings": { "agentId": "<uuid>" }+}+```++The iframe announces itself with `{ type: '<ns>:plugin-ready-for-render' }`, then parses `payload.apiName` + the JSON-string `payload.arguments` and drives the `<agent-3d>` element. In parallel, the host's gateway POSTs the arguments to the tool's endpoint (`/api/chat-plugin/{tool}`, with the user's settings in the `Sperax-Plugin-Settings` header) to get the concise result the model reads back.++Full setup, submission, and chain notes: [`/sperax/README.md`](https://three.ws/sperax/README.md).++---+## oEmbedMany platforms support oEmbed — paste a URL and the platform auto-fetches a rich preview. No code required.diff --git a/public/ibm-og.png b/public/ibm-og.pngnew file mode 100644index 000000000..34d848abfBinary files /dev/null and b/public/ibm-og.png differdiff --git a/public/lobehub/iframe/boot.js b/public/lobehub/iframe/boot.jsindex ab9ca8366..a24cebefa 100644--- a/public/lobehub/iframe/boot.js+++ b/public/lobehub/iframe/boot.js@@ -10,8 +10,16 @@const EMBED_VERSION = '1.0.0';const CAPABILITIES = ['speak', 'gesture', 'emote', 'look', 'setAgent', 'subscribe', 'ping'];-// Origins unconditionally trusted.-const KNOWN_ORIGINS = new Set(['https://chat.lobehub.com', 'https://lobechat.ai']);+// Hosts that may frame this iframe as a chat plugin, unconditionally trusted.+// LobeChat and SperaxOS (a LobeChat-lineage host) both embed standalone plugins.+const KNOWN_ORIGINS = new Set([+ 'https://chat.lobehub.com',+ 'https://lobechat.ai',+ 'https://chat.sperax.io',+ 'https://sperax.io',+ 'https://sperax-iota.vercel.app',+ 'https://sperax-jam2emun9-moomsi.vercel.app',+]);function isDev(origin) {try {@@ -100,12 +108,27 @@ function setStatus(text) {if (statusEl) statusEl.textContent = text;}+// The agent can be specified three ways, in priority order:+// 1. ?src=<glb-url> or ?agent=<id> on the iframe URL (direct embeds, dev harness)+// 2. the host plugin's `settings.agentId` (LobeChat / SperaxOS)+// 3. a `render_agent` tool call from the LLM+// (2) and (3) arrive over postMessage after boot, so an empty start is normal.+let boundAgentId = agentId;+function bindAgent(id) {+ if (!id || typeof id !== 'string') return;+ if (id === boundAgentId && el.getAttribute('agent-id')) return;+ boundAgentId = id;+ el.removeAttribute('src');+ el.setAttribute('agent-id', id);+ setStatus('Loading…');+}+if (srcParam) {el.setAttribute('src', decodeURIComponent(srcParam));} else if (agentId) {el.setAttribute('agent-id', agentId);} else {- setStatus('No agent specified — add ?agent=<id> or ?src=<glb-url> to the URL.');+ setStatus('Waiting for an agent…');}el.addEventListener('agent:ready', (ev) => {@@ -193,6 +216,85 @@ async function dispatchAction(op, payload, replyId) {}}+// ── LobeChat / SperaxOS standalone-plugin protocol ────────────────────────────+// Both platforms are LobeChat-lineage and speak an identical message contract,+// differing only in the channel prefix: 'lobe-chat:' vs 'speraxos:'. We announce+// readiness on both and accept tool calls from either.+// host → iframe: { type:'<ns>:init-standalone-plugin', payload:{ apiName, arguments }, settings, state }+// iframe → host: { type:'<ns>:plugin-ready-for-render' }+const CHAT_PLUGIN_PREFIXES = ['lobe-chat:', 'speraxos:'];++function chatPluginChannel(type) {+ if (typeof type !== 'string') return null;+ for (const prefix of CHAT_PLUGIN_PREFIXES) {+ if (type.startsWith(prefix)) return type.slice(prefix.length);+ }+ return null;+}++// Normalise the function-call payload. The wire carries `payload.apiName` and a+// JSON-string `payload.arguments`; older builds nest it under `props`. We also+// accept an already-parsed arguments object for robustness across host versions.+function readChatPluginCall(data) {+ const p = data.payload || data.props || {};+ const apiName = p.apiName || p.name || data.apiName || data.name || '';+ const raw = p.arguments ?? data.arguments;+ let args = {};+ if (typeof raw === 'string') {+ try {+ args = JSON.parse(raw || '{}');+ } catch {+ args = {};+ }+ } else if (raw && typeof raw === 'object') {+ args = raw;+ }+ const settings = data.settings || p.settings || {};+ return { apiName, args, settings };+}++function handleChatPluginMessage(channel, data) {+ const { apiName, args, settings } = readChatPluginCall(data);++ // Bind the avatar to the configured agent whenever the host sends settings.+ if (settings && typeof settings.agentId === 'string') bindAgent(settings.agentId);++ // Only the render/init channels carry a function call; the state/settings+ // channels are not used by this plugin.+ if (channel !== 'init-standalone-plugin' && channel !== 'render-plugin') return;+ if (!apiName) return;++ switch (apiName) {+ case 'render_agent':+ case 'render-agent':+ if (typeof args.agentId === 'string') bindAgent(args.agentId);+ break;+ case 'speak':+ dispatchAction(+ 'speak',+ {+ text: typeof args.text === 'string' ? args.text : '',+ sentiment: typeof args.sentiment === 'number' ? args.sentiment : 0,+ },+ null,+ );+ break;+ case 'gesture':+ dispatchAction('gesture', { name: args.name, duration: args.duration }, null);+ break;+ case 'emote':+ dispatchAction(+ 'emote',+ {+ trigger: args.trigger,+ weight: typeof args.weight === 'number' ? args.weight : 1,+ },+ null,+ );+ break;+ }+}+// ── postMessage handler ───────────────────────────────────────────────────────function onMessage(ev) {@@ -214,6 +316,13 @@ function onMessage(ev) {if (!isAllowedOrigin(origin)) return;if (!lockedOrigin) lockedOrigin = origin;+ // ── LobeChat / SperaxOS standalone-plugin channels ──────────────────────────+ const chatChannel = chatPluginChannel(data.type);+ if (chatChannel) {+ handleChatPluginMessage(chatChannel, data);+ return;+ }+// ── v1 spec envelope ──────────────────────────────────────────────────────if (data.v === 1 && data.source === 'agent-host' && data.kind && data.op) {const { id, kind, op, payload = {} } = data;@@ -294,3 +403,13 @@ post('ready', {embedVersion: EMBED_VERSION,capabilities: CAPABILITIES,});++// Announce readiness on the LobeChat / SperaxOS channels so those hosts deliver+// the standalone-plugin init payload (settings + the triggering tool call). The+// ready signal carries no sensitive data, so we broadcast it to the parent+// regardless of which host framed us; all subsequent exchange is origin-locked.+for (const prefix of CHAT_PLUGIN_PREFIXES) {+ try {+ window.parent.postMessage({ type: `${prefix}plugin-ready-for-render` }, '*');+ } catch (_) {}+}diff --git a/public/lobehub/iframe/index.html b/public/lobehub/iframe/index.htmlindex f66892211..3872b42d0 100644--- a/public/lobehub/iframe/index.html+++ b/public/lobehub/iframe/index.html@@ -2,7 +2,7 @@<html lang="en"><head><meta charset="utf-8" />- <title>three.ws — LobeHub Embed</title>+ <title>three.ws — Chat Embed</title><meta name="viewport" content="width=device-width, initial-scale=1" /><meta name="robots" content="noindex" /><style>@@ -36,7 +36,8 @@<!--Loads the <agent-3d> web component. In production loads from CDN; in devloads from the local Vite dev server so local changes are reflected immediately.- LobeChat's sandbox CSP must allow module scripts from this origin.+ The host's sandbox CSP (LobeChat / SperaxOS) must allow module scripts from+ this origin. boot.js speaks the LobeChat + SperaxOS standalone-plugin protocol.--><script type="module">const CDN = 'https://three.ws/agent-3d/latest/agent-3d.js';diff --git a/public/lobehub/plugin.json b/public/lobehub/plugin.jsonindex 0a1565b4e..728354ade 100644--- a/public/lobehub/plugin.json+++ b/public/lobehub/plugin.json@@ -7,7 +7,7 @@"meta": {"title": "three.ws","description": "Embodied 3D avatar agent with continuous emotion blending. Renders a rigged glTF avatar inside chat, responds with gestures, speech, and on-chain ERC-8004 identity.",- "avatar": "https://three.ws/icon.svg",+ "avatar": "https://three.ws/pwa-icon.svg","tags": ["3d", "avatar", "agent", "embodied", "empathy", "erc-8004"]},"ui": {@@ -16,7 +16,7 @@},"api": [{- "url": "https://three.ws/api/mcp",+ "url": "https://three.ws/api/chat-plugin/render-agent","name": "render_agent","description": "Mount the 3D avatar for a given agent id. Call this first to bind the iframe to a specific agent before using speak/gesture/emote.","parameters": {@@ -31,7 +31,7 @@}},{- "url": "https://three.ws/api/mcp",+ "url": "https://three.ws/api/chat-plugin/speak","name": "speak","description": "Make the avatar speak with optional emotional valence.","parameters": {@@ -52,7 +52,7 @@}},{- "url": "https://three.ws/api/mcp",+ "url": "https://three.ws/api/chat-plugin/gesture","name": "gesture","description": "Trigger a named gesture on the avatar.","parameters": {@@ -72,7 +72,7 @@}},{- "url": "https://three.ws/api/mcp",+ "url": "https://three.ws/api/chat-plugin/emote","name": "emote","description": "Inject an emotion into the avatar's continuous Empathy Layer blend.","parameters": {diff --git a/public/sperax/README.md b/public/sperax/README.mdnew file mode 100644index 000000000..55f1a5a21--- /dev/null+++ b/public/sperax/README.md@@ -0,0 +1,105 @@+# three.ws — SperaxOS plugin++Give a SperaxOS agent a body: a rigged 3D avatar, rendered in the chat panel, that+speaks, gestures, and shifts its body language in real time as the agent acts —+bound to an on-chain ERC-8004 identity.++SperaxOS is a LobeChat-lineage host, so this ships as a **standalone plugin**: a+hosted iframe the platform frames directly, plus a small set of LLM-callable tools.+No bundle to submit, no SDK to vendor.++---++## Files++| File | Purpose |+| ---------------------------------- | --------------------------------------------------------------------------------------------------------------------------------------------------- |+| [`manifest.json`](./manifest.json) | The `plugin.delivery` manifest (`type: standalone`). Served with CORS at `/.well-known/sperax-plugin.json` and verbatim at `/sperax/manifest.json`. |+| [`icon-256.svg`](./icon-256.svg) | The plugin avatar (`meta.avatar`). |+| `/sperax/iframe/` | The rendered panel (`ui.url`). Shares `boot.js` with the LobeChat embed; speaks both the `speraxos:` and `lobe-chat:` protocols. |+| `/api/chat-plugin/{tool}` | The gateway-facing tool endpoints (`render-agent`, `speak`, `gesture`, `emote`). |++---++## Install (end users)++1. In SperaxOS, open **Plugins → Add Plugin → Custom Plugin**.+2. Paste the manifest URL:+ ```+ https://three.ws/.well-known/sperax-plugin.json+ ```+3. Install, then set your **Agent ID** (a UUID or `@handle` from+ [your dashboard](https://three.ws/dashboard)).+4. The avatar appears in the chat panel and reacts to the agent's tool calls.++---++## How it works++```+SperaxOS host+ │ 1. LLM calls a tool (speak / gesture / emote / render_agent)+ │+ ├─ 2a. renders ui.url in an iframe and posts the call to it:+ │ { type: 'speraxos:init-standalone-plugin',+ │ payload: { apiName, arguments }, settings: { agentId } }+ │ ▼+ │ /sperax/iframe/ (boot.js) → <agent-3d> animates the avatar+ │+ └─ 2b. gateway POSTs the arguments to api[].url for the model-facing result:+ POST /api/chat-plugin/speak (header: Sperax-Plugin-Settings)+ ▼+ { ok: true, action: 'speak', spoken: "…" }+```++Both halves run for every tool call. The iframe drives the visible avatar; the+endpoint returns the concise result the model reads back into the conversation.++### Tools++| Tool | Arguments | Effect |+| -------------- | -------------------------------------------------------------------------------- | --------------------------------------- |+| `render_agent` | `{ agentId }` | Bind / swap the avatar to an agent |+| `speak` | `{ text, sentiment? [-1,1] }` | Speak aloud with emotional valence |+| `gesture` | `{ name: wave\|nod\|point\|shrug, duration? }` | Play a physical gesture |+| `emote` | `{ trigger: concern\|celebration\|patience\|curiosity\|empathy, weight? [0,1] }` | Blend an emotion into the Empathy Layer |++The agent can also be set once via the plugin's `settings.agentId`, delivered to+the iframe in the init message — no `render_agent` call required.++---++## Submitting to the marketplace++The manifest is hosted and ready. To list it on `plugin.delivery`:++1. Confirm every URL resolves over HTTPS:+ - `https://three.ws/.well-known/sperax-plugin.json` (the manifest, CORS-enabled)+ - `https://three.ws/sperax/iframe/` (the panel)+ - `https://three.ws/api/chat-plugin/speak` and the three sibling tools+2. Open a **Plugin Submission** issue (or PR the manifest) at the+ `Sperax/AI-Plugin-Marketplace-SDK` repo, per its `docs/SUBMIT_PLUGIN.md`.+3. Tested in SperaxOS, no API key required (the only setting is a public Agent ID).++---++## Local testing++Run the dev server and drive the iframe with the protocol harness — it posts the+exact `speraxos:` / `lobe-chat:` messages a real host sends:++```bash+npm run dev # http://localhost:3000+open "http://localhost:3000/chat-plugin/dev/sperax.html?origin=http://localhost:3000&agent=<agentId>"+```++---++## Chain note++SperaxOS is EVM-native and settles agent payments via x402 over USDC on Base+(`x402.sperax.io`), which matches three.ws's existing Base x402 rail. The avatar+panel itself is chain-agnostic — it renders and animates regardless of which chain+the bound agent transacts on. Solana-native actions are not driven by the host+wallet (SperaxOS injects no wallet provider); route any in-panel payment UX through+Base x402 or a self-contained flow.diff --git a/public/sperax/icon-256.svg b/public/sperax/icon-256.svgnew file mode 100644index 000000000..418d63bd9--- /dev/null+++ b/public/sperax/icon-256.svg@@ -0,0 +1,64 @@+<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 256 256" width="256" height="256" role="img" aria-label="three.ws embodied avatar">+ <defs>+ <linearGradient id="bg" x1="0" y1="0" x2="1" y2="1">+ <stop offset="0%" stop-color="#0b0b16"/>+ <stop offset="100%" stop-color="#10101f"/>+ </linearGradient>+ <radialGradient id="avatarGlow" cx="50%" cy="42%" r="60%">+ <stop offset="0%" stop-color="#e0e7ff" stop-opacity="0.95"/>+ <stop offset="45%" stop-color="#818cf8" stop-opacity="0.85"/>+ <stop offset="100%" stop-color="#60a5fa" stop-opacity="0"/>+ </radialGradient>+ <linearGradient id="figure" x1="0" y1="0" x2="0" y2="1">+ <stop offset="0%" stop-color="#eef2ff"/>+ <stop offset="100%" stop-color="#a5b4fc"/>+ </linearGradient>+ <linearGradient id="edge" x1="0" y1="0" x2="1" y2="1">+ <stop offset="0%" stop-color="#7ec8e3"/>+ <stop offset="100%" stop-color="#818cf8"/>+ </linearGradient>+ <filter id="soft" x="-30%" y="-30%" width="160%" height="160%">+ <feGaussianBlur stdDeviation="2.4" result="b"/>+ <feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>+ </filter>+ <filter id="vtx" x="-150%" y="-150%" width="400%" height="400%">+ <feGaussianBlur stdDeviation="5" result="b"/>+ <feMerge><feMergeNode in="b"/><feMergeNode in="SourceGraphic"/></feMerge>+ </filter>+ </defs>++ <!-- App-tile background -->+ <rect width="256" height="256" rx="56" fill="url(#bg)"/>+ <rect x="0.75" y="0.75" width="254.5" height="254.5" rx="55.25" fill="none" stroke="#ffffff" stroke-opacity="0.06"/>++ <!-- Isometric cube — the three.ws mark.+ top=128,46 left=44,87 right=212,87 mid=128,128 bl=44,201 br=212,201 bottom=128,242 -->+ <!-- Faces (subtle, so the avatar reads first) -->+ <polygon points="128,46 44,87 128,128 212,87" fill="#1b1b30" fill-opacity="0.55"/>+ <polygon points="44,87 44,201 128,242 128,128" fill="#15152a" fill-opacity="0.6"/>+ <polygon points="212,87 212,201 128,242 128,128" fill="#10101f" fill-opacity="0.6"/>++ <!-- Glowing embodied avatar suspended inside the cube -->+ <circle cx="128" cy="132" r="58" fill="url(#avatarGlow)" opacity="0.55"/>+ <g filter="url(#soft)">+ <!-- head -->+ <circle cx="128" cy="112" r="20" fill="url(#figure)"/>+ <!-- shoulders / torso -->+ <path d="M92 178 q0 -34 36 -34 q36 0 36 34 q0 8 -8 8 h-56 q-8 0 -8 -8 z" fill="url(#figure)"/>+ </g>++ <!-- Cube edges, drawn over the avatar so it sits inside the lattice -->+ <g stroke="url(#edge)" stroke-linejoin="round" fill="none" filter="url(#soft)">+ <polygon points="128,46 212,87 212,201 128,242 44,201 44,87" stroke-width="4.5" opacity="0.9"/>+ <path d="M128,46 L128,128 M44,87 L128,128 M212,87 L128,128 M128,128 L128,242"+ stroke-width="2.6" opacity="0.5"/>+ </g>++ <!-- Bright vertices -->+ <g fill="#eaf6ff" filter="url(#vtx)">+ <circle cx="128" cy="46" r="5.5"/>+ <circle cx="212" cy="87" r="4" opacity="0.8"/>+ <circle cx="44" cy="87" r="4" opacity="0.8"/>+ <circle cx="128" cy="128" r="3.5" opacity="0.6"/>+ </g>+</svg>diff --git a/public/sperax/manifest.json b/public/sperax/manifest.jsonnew file mode 100644index 000000000..60074778e--- /dev/null+++ b/public/sperax/manifest.json@@ -0,0 +1,111 @@+{+ "$schema": "https://plugin.delivery/schema.json",+ "identifier": "three-ws",+ "version": "1.0.0",+ "author": "three.ws",+ "homepage": "https://three.ws/",+ "type": "standalone",+ "meta": {+ "title": "three.ws — Embodied Avatar",+ "description": "Give your SperaxOS agent a body. Renders a rigged 3D avatar in the chat that speaks, gestures, and reflects emotion in real time — bound to an on-chain ERC-8004 identity.",+ "avatar": "https://three.ws/sperax/icon-256.svg",+ "tags": ["3d", "avatar", "embodied-agent", "erc-8004", "defi"]+ },+ "ui": {+ "url": "https://three.ws/sperax/iframe/",+ "height": 480,+ "mode": "iframe"+ },+ "settings": {+ "type": "object",+ "required": ["agentId"],+ "properties": {+ "agentId": {+ "type": "string",+ "title": "Agent ID",+ "description": "A three.ws agent ID (UUID) or @handle. Copy it from your dashboard at https://three.ws/dashboard. The avatar binds to this identity when the panel opens."+ }+ }+ },+ "api": [+ {+ "url": "https://three.ws/api/chat-plugin/render-agent",+ "name": "render_agent",+ "description": "Mount or swap the 3D avatar to a specific three.ws agent. Call this first if the avatar has not been bound yet, or to switch to a different agent mid-conversation.",+ "parameters": {+ "type": "object",+ "properties": {+ "agentId": {+ "type": "string",+ "description": "The three.ws agent ID (UUID) or @handle to render in the panel."+ }+ },+ "required": ["agentId"]+ }+ },+ {+ "url": "https://three.ws/api/chat-plugin/speak",+ "name": "speak",+ "description": "Make the embodied avatar speak a line out loud with emotional valence. Use for greetings, narrating an action you just took, or reacting to the user.",+ "parameters": {+ "type": "object",+ "properties": {+ "text": {+ "type": "string",+ "description": "The line for the avatar to speak aloud."+ },+ "sentiment": {+ "type": "number",+ "description": "Emotional valence in [-1, 1]. Negative leans concerned, positive leans celebratory. Defaults to neutral (0).",+ "minimum": -1,+ "maximum": 1+ }+ },+ "required": ["text"]+ }+ },+ {+ "url": "https://three.ws/api/chat-plugin/gesture",+ "name": "gesture",+ "description": "Play a named physical gesture on the avatar to punctuate a message.",+ "parameters": {+ "type": "object",+ "properties": {+ "name": {+ "type": "string",+ "description": "Which gesture to play.",+ "enum": ["wave", "nod", "point", "shrug"]+ },+ "duration": {+ "type": "number",+ "description": "Optional gesture duration in seconds."+ }+ },+ "required": ["name"]+ }+ },+ {+ "url": "https://three.ws/api/chat-plugin/emote",+ "name": "emote",+ "description": "Inject an emotion into the avatar's continuous Empathy Layer blend so its body language reflects the moment — e.g. concern as a position nears liquidation, celebration when a yield target is hit.",+ "parameters": {+ "type": "object",+ "properties": {+ "trigger": {+ "type": "string",+ "description": "The emotion to blend in.",+ "enum": ["concern", "celebration", "patience", "curiosity", "empathy"]+ },+ "weight": {+ "type": "number",+ "description": "Blend weight in [0, 1]. Defaults to 1.",+ "minimum": 0,+ "maximum": 1+ }+ },+ "required": ["trigger"]+ }+ }+ ],+ "systemRole": "You have an embodied 3D avatar visible in the SperaxOS chat panel. It conveys emotion in real time through a continuous Empathy Layer blend. Call render_agent first to bind it to a specific agent (skip if an Agent ID is already configured in settings), speak to give it a voice with emotional valence, gesture for physical punctuation, and emote to shift its body language to match what is happening on-chain. Prefer a brief gesture or emote alongside substantive replies so the avatar feels alive."+}diff --git a/scripts/gen-ibm-og.mjs b/scripts/gen-ibm-og.mjsnew file mode 100644index 000000000..0e2e82d77--- /dev/null+++ b/scripts/gen-ibm-og.mjs@@ -0,0 +1,91 @@+#!/usr/bin/env node+// Generate the social share card for the three.ws × IBM partnership post.+//+// Produces public/ibm-og.png (1200×630) — the og:image / twitter:image for+// /blog/three-ws-ibm-collaboration. Mirrors the in-repo OG card convention+// (api/walk-og.js): a self-contained SVG on the post's dark gradient, with the+// three.ws accent, rasterized to a real PNG via sharp so every crawler (X,+// Slack, Discord, LinkedIn) caches a guaranteed-supported image.+//+// Text-only branding: "IBM" and the public IBM quote are named factually; no+// third-party logo asset is embedded.+//+// Usage: node scripts/gen-ibm-og.mjs++import sharp from 'sharp';+import { fileURLToPath } from 'node:url';+import { dirname, join } from 'node:path';++const root = join(dirname(fileURLToPath(import.meta.url)), '..');+const OUT = join(root, 'public/ibm-og.png');++// Single-quote multi-word family names — these are interpolated into+// double-quoted SVG attributes, so embedded double quotes would break parsing.+const FONT = "Inter, -apple-system, system-ui, 'Segoe UI', Roboto, sans-serif";+const MONO = "ui-monospace, 'SFMono-Regular', Menlo, monospace";++// 1200×630 OG card. Colours match blog/three-ws-ibm-collaboration.html:+// bg #060611, text #e7e7f5, accent #9ad4ff, muted #7a85a8 / #c8c8e0.+const svg = `<?xml version="1.0" encoding="UTF-8"?>+<svg xmlns="http://www.w3.org/2000/svg" width="1200" height="630" viewBox="0 0 1200 630"+ role="img" aria-label="three.ws times IBM — showcasing the partnership">+ <defs>+ <linearGradient id="bg" x1="0" y1="0" x2="1200" y2="630" gradientUnits="userSpaceOnUse">+ <stop offset="0%" stop-color="#070713"/>+ <stop offset="100%" stop-color="#05050d"/>+ </linearGradient>+ <radialGradient id="glow" cx="0.18" cy="0.0" r="0.9">+ <stop offset="0%" stop-color="rgba(154,212,255,0.16)"/>+ <stop offset="55%" stop-color="rgba(154,212,255,0.0)"/>+ </radialGradient>+ </defs>++ <rect width="1200" height="630" fill="url(#bg)"/>+ <rect width="1200" height="630" fill="url(#glow)"/>++ <!-- subtle grid lines -->+ <line x1="0" y1="158" x2="1200" y2="158" stroke="rgba(154,212,255,0.06)" stroke-width="1"/>+ <line x1="0" y1="472" x2="1200" y2="472" stroke="rgba(154,212,255,0.06)" stroke-width="1"/>++ <!-- top row: wordmark + tag -->+ <text x="80" y="92" fill="#e7e7f5" font-family="${FONT}" font-size="30" font-weight="700"+ letter-spacing="-0.5">three.ws</text>+ <rect x="262" y="68" width="124" height="32" rx="16" fill="rgba(154,212,255,0.10)"/>+ <text x="324" y="90" fill="#9ad4ff" font-family="${FONT}" font-size="15" font-weight="600"+ letter-spacing="1.5" text-anchor="middle">PARTNERSHIP</text>++ <!-- accent bar -->+ <rect x="80" y="214" width="5" height="150" rx="2.5" fill="#9ad4ff"/>++ <!-- headline -->+ <text x="112" y="278" fill="#e7e7f5" font-family="${FONT}" font-size="92" font-weight="700"+ letter-spacing="-2">three.ws <tspan fill="#9ad4ff">× IBM</tspan></text>++ <!-- subhead -->+ <text x="112" y="338" fill="#c8c8e0" font-family="${FONT}" font-size="34" font-weight="500"+ letter-spacing="-0.4">Showcasing the partnership</text>++ <!-- body line -->+ <text x="112" y="392" fill="#7a85a8" font-family="${FONT}" font-size="25" font-weight="400">+ A persistent, on-chain 3D agent — embedded like a YouTube video,</text>+ <text x="112" y="426" fill="#7a85a8" font-family="${FONT}" font-size="25" font-weight="400">+ thinking on IBM watsonx.ai and Granite.</text>++ <!-- IBM quote -->+ <text x="80" y="556" fill="#9ad4ff" font-family="${MONO}" font-size="23" font-weight="400">+ “We’re super excited about this.”<tspan fill="#5a6486" font-size="20"> — @IBM</tspan></text>++ <!-- url -->+ <text x="1120" y="556" fill="rgba(231,231,245,0.45)" font-family="${FONT}" font-size="20"+ font-weight="500" letter-spacing="1" text-anchor="end">three.ws/blog</text>+</svg>`;++// Rasterize at 2× density for crisp text, then downscale to the exact+// 1200×630 OG dimensions declared in the post's meta.+await sharp(Buffer.from(svg), { density: 192 })+ .resize(1200, 630)+ .png({ compressionLevel: 9 })+ .toFile(OUT);++const meta = await sharp(OUT).metadata();+console.log(`Wrote ${OUT} (${meta.width}x${meta.height} ${meta.format})`);diff --git a/src/runtime/speech.js b/src/runtime/speech.jsindex 45583c857..4a538fcc1 100644--- a/src/runtime/speech.js+++ b/src/runtime/speech.js@@ -15,7 +15,7 @@ export class BrowserTTS {this._lipsync = null;// Global hooks — set by callers that manage lipsync externally (e.g. AgentAvatar).this.onStart = null;- this.onEnd = null;+ this.onEnd = null;}async speak(text, { onStart, onEnd, scene } = {}) {@@ -162,7 +162,7 @@ export class BrowserSTT {** voice_settings mapping:* `rate` is mapped onto `style` (0..1) — ElevenLabs has no true playback-- * rate control on the Turbo models, but `style` shifts delivery+ * rate control on the Turbo/Flash models, but `style` shifts delivery* pacing, so a higher rate translates to a more emphatic/faster* feel. `rate` 0.5..1.5 → `style` 0..1, clamped.* `pitch` has no analogue in ElevenLabs voice_settings, so it is dropped@@ -174,7 +174,7 @@ export class BrowserSTT {export class ElevenLabsTTS {constructor({voiceId,- modelId = 'eleven_turbo_v2_5',+ modelId = 'eleven_flash_v2_5',apiKey = null,proxyURL = null,rate = 1,@@ -204,12 +204,12 @@ export class ElevenLabsTTS {this._lipsync = null;this._positionalAudio = null; // THREE.PositionalAudio, optional// Web Audio nodes for LipSyncAnalyser integration- this._audioCtx = null;- this._analyserNode = null;- this._mediaSource = null;+ this._audioCtx = null;+ this._analyserNode = null;+ this._mediaSource = null;// Global hooks — set by callers that manage lipsync externally (e.g. AgentAvatar).this.onStart = null;- this.onEnd = null;+ this.onEnd = null;}/** Expose the shared AnalyserNode so LipSyncAnalyser can read frequency data. */@@ -345,9 +345,9 @@ export class ElevenLabsTTS {if (!AC) return;try {if (!this._audioCtx || this._audioCtx.state === 'closed') {- this._audioCtx = new AC();+ this._audioCtx = new AC();this._analyserNode = this._audioCtx.createAnalyser();- this._analyserNode.fftSize = 256;+ this._analyserNode.fftSize = 256;this._analyserNode.smoothingTimeConstant = 0.7;this._analyserNode.connect(this._audioCtx.destination);}@@ -366,7 +366,9 @@ export class ElevenLabsTTS {const pa = this._positionalAudio;if (!pa) return;// Disconnect any previous MediaElementSource from this PositionalAudio- try { pa.source?.disconnect(); } catch {}+ try {+ pa.source?.disconnect();+ } catch {}// Wire the new element through the spatial panner already set up by Three.js:// MediaElementSource → panner → audio.gain → listener.gain → context.destinationpa.source = pa.context.createMediaElementSource(audioEl);@@ -473,11 +475,15 @@ export class ElevenLabsTTS {_cleanupAudio() {// Disconnect the per-speak MediaElementSourceNode (analyser + ctx are reused).if (this._mediaSource) {- try { this._mediaSource.disconnect(); } catch {}+ try {+ this._mediaSource.disconnect();+ } catch {}this._mediaSource = null;}if (this._positionalAudio?.source) {- try { this._positionalAudio.source.disconnect(); } catch {}+ try {+ this._positionalAudio.source.disconnect();+ } catch {}this._positionalAudio.source = null;}if (this._audio) {diff --git a/tests/api-tts-elevenlabs.test.js b/tests/api-tts-elevenlabs.test.jsnew file mode 100644index 000000000..8e3f0f5dc--- /dev/null+++ b/tests/api-tts-elevenlabs.test.js@@ -0,0 +1,217 @@+// Unit tests for the shared ElevenLabs client (api/_lib/elevenlabs.js).+// fetch and the @elevenlabs/elevenlabs-js SDK are mocked so these run with no+// network and no API key — they pin the contract the TTS proxy + agent-voice+// endpoints depend on (cache behavior, error→status mapping, best-effort delete).++import { vi, describe, it, expect, beforeEach, afterAll } from 'vitest';++// SDK mock — hoisted so vi.mock's factory can reference it.+const { ivcCreate } = vi.hoisted(() => ({ ivcCreate: vi.fn() }));+vi.mock('@elevenlabs/elevenlabs-js', () => ({+ // Plain function (constructable) that returns the client shape; an arrow or+ // vi.fn impl can't be used with `new`.+ ElevenLabsClient: function ElevenLabsClient() {+ return { voices: { ivc: { create: ivcCreate } } };+ },+}));++import {+ DEFAULT_TTS_MODEL,+ elevenApiKey,+ isConfigured,+ listVoices,+ invalidateVoiceCache,+ createClonedVoice,+ deleteVoice,+} from '../api/_lib/elevenlabs.js';++const realFetch = global.fetch;+afterAll(() => {+ global.fetch = realFetch;+});++function voicesResponse(voices) {+ return { ok: true, status: 200, json: async () => ({ voices }) };+}++beforeEach(() => {+ process.env.ELEVENLABS_API_KEY = 'sk_test_key';+ global.fetch = vi.fn();+ ivcCreate.mockReset();+ invalidateVoiceCache();+ vi.useRealTimers();+});++describe('config gate', () => {+ it('reflects ELEVENLABS_API_KEY presence', () => {+ expect(isConfigured()).toBe(true);+ expect(elevenApiKey()).toBe('sk_test_key');+ delete process.env.ELEVENLABS_API_KEY;+ expect(isConfigured()).toBe(false);+ expect(elevenApiKey()).toBeNull();+ });++ it('defaults to the low-latency flash model', () => {+ expect(DEFAULT_TTS_MODEL).toBe('eleven_flash_v2_5');+ });+});++describe('listVoices', () => {+ it('throws a 503 when unconfigured, without hitting the network', async () => {+ delete process.env.ELEVENLABS_API_KEY;+ await expect(listVoices()).rejects.toMatchObject({ status: 503 });+ expect(global.fetch).not.toHaveBeenCalled();+ });++ it('maps the upstream payload to safe public fields', async () => {+ global.fetch.mockResolvedValue(+ voicesResponse([+ {+ voice_id: 'v1',+ name: 'Rachel',+ category: 'premade',+ labels: { accent: 'american' },+ preview_url: 'https://x/preview.mp3',+ secret_internal_field: 'should-not-leak',+ },+ ]),+ );+ const { voices, cached } = await listVoices();+ expect(cached).toBe(false);+ expect(voices).toEqual([+ {+ voice_id: 'v1',+ name: 'Rachel',+ category: 'premade',+ labels: { accent: 'american' },+ preview_url: 'https://x/preview.mp3',+ },+ ]);+ expect(voices[0]).not.toHaveProperty('secret_internal_field');+ });++ it('serves a warm cache hit without refetching', async () => {+ global.fetch.mockResolvedValue(voicesResponse([{ voice_id: 'v1', name: 'A' }]));+ await listVoices();+ const second = await listVoices();+ expect(second.cached).toBe(true);+ expect(global.fetch).toHaveBeenCalledTimes(1);+ });++ it('refetches after the cache is invalidated', async () => {+ global.fetch.mockResolvedValue(voicesResponse([{ voice_id: 'v1', name: 'A' }]));+ await listVoices();+ invalidateVoiceCache();+ await listVoices();+ expect(global.fetch).toHaveBeenCalledTimes(2);+ });++ it('force:true bypasses the cache', async () => {+ global.fetch.mockResolvedValue(voicesResponse([{ voice_id: 'v1', name: 'A' }]));+ await listVoices();+ await listVoices({ force: true });+ expect(global.fetch).toHaveBeenCalledTimes(2);+ });++ it('expires the cache after the TTL', async () => {+ vi.useFakeTimers();+ global.fetch.mockResolvedValue(voicesResponse([{ voice_id: 'v1', name: 'A' }]));+ await listVoices();+ vi.advanceTimersByTime(4 * 60 * 1000);+ expect((await listVoices()).cached).toBe(true);+ vi.advanceTimersByTime(2 * 60 * 1000); // now > 5-min TTL+ expect((await listVoices()).cached).toBe(false);+ expect(global.fetch).toHaveBeenCalledTimes(2);+ });++ it('throws a 502 on a non-ok upstream response', async () => {+ global.fetch.mockResolvedValue({ ok: false, status: 429, json: async () => ({}) });+ await expect(listVoices()).rejects.toMatchObject({ status: 502 });+ });++ it('throws a 502 when fetch itself rejects', async () => {+ global.fetch.mockRejectedValue(new Error('ECONNRESET'));+ await expect(listVoices()).rejects.toMatchObject({ status: 502 });+ });+});++describe('createClonedVoice', () => {+ it('throws a 503 when unconfigured', async () => {+ delete process.env.ELEVENLABS_API_KEY;+ await expect(createClonedVoice({ name: 'x', files: [] })).rejects.toMatchObject({+ status: 503,+ });+ });++ it('returns the voice id and verification flag on success', async () => {+ ivcCreate.mockResolvedValue({ voice_id: 'cloned-1', requires_verification: true });+ const res = await createClonedVoice({ name: 'Mine', files: ['f'] });+ expect(res).toEqual({ voiceId: 'cloned-1', requiresVerification: true });+ });++ it('defaults requiresVerification to false', async () => {+ ivcCreate.mockResolvedValue({ voice_id: 'cloned-2' });+ expect((await createClonedVoice({ name: 'Mine', files: ['f'] })).requiresVerification).toBe(+ false,+ );+ });++ it('preserves the upstream status code and body (e.g. 422 quota)', async () => {+ // ElevenLabsError exposes `statusCode` + `body`.+ ivcCreate.mockRejectedValue({ statusCode: 422, body: { detail: 'audio too short' } });+ await expect(createClonedVoice({ name: 'x', files: ['f'] })).rejects.toMatchObject({+ status: 422,+ upstreamBody: expect.stringContaining('audio too short'),+ });+ });++ it('falls back to 502 when the SDK error has no status', async () => {+ ivcCreate.mockRejectedValue(new Error('socket hang up'));+ await expect(createClonedVoice({ name: 'x', files: ['f'] })).rejects.toMatchObject({+ status: 502,+ upstreamBody: 'socket hang up',+ });+ });++ it('throws a 502 when the SDK returns no voice_id', async () => {+ ivcCreate.mockResolvedValue({});+ await expect(createClonedVoice({ name: 'x', files: ['f'] })).rejects.toMatchObject({+ status: 502,+ });+ });++ it('invalidates the voice cache so a new clone shows up immediately', async () => {+ global.fetch.mockResolvedValue(voicesResponse([{ voice_id: 'v1', name: 'A' }]));+ await listVoices(); // prime cache+ ivcCreate.mockResolvedValue({ voice_id: 'cloned-3' });+ await createClonedVoice({ name: 'New', files: ['f'] });+ await listVoices(); // must refetch+ expect(global.fetch).toHaveBeenCalledTimes(2);+ });+});++describe('deleteVoice (best-effort)', () => {+ it('no-ops without a key or voice id', async () => {+ delete process.env.ELEVENLABS_API_KEY;+ await deleteVoice('v1');+ expect(global.fetch).not.toHaveBeenCalled();+ process.env.ELEVENLABS_API_KEY = 'sk_test_key';+ await deleteVoice('');+ expect(global.fetch).not.toHaveBeenCalled();+ });++ it('issues a DELETE with the api key header', async () => {+ global.fetch.mockResolvedValue({ ok: true, status: 200 });+ await deleteVoice('v-del');+ expect(global.fetch).toHaveBeenCalledTimes(1);+ const [url, opts] = global.fetch.mock.calls[0];+ expect(url).toContain('/voices/v-del');+ expect(opts.method).toBe('DELETE');+ expect(opts.headers['xi-api-key']).toBe('sk_test_key');+ });++ it('never throws even if the upstream call fails', async () => {+ global.fetch.mockRejectedValue(new Error('network down'));+ await expect(deleteVoice('v-del')).resolves.toBeUndefined();+ });+});diff --git a/tests/api/chat-plugin-tool.test.js b/tests/api/chat-plugin-tool.test.jsnew file mode 100644index 000000000..c02d16c1c--- /dev/null+++ b/tests/api/chat-plugin-tool.test.js@@ -0,0 +1,118 @@+// /api/chat-plugin/[tool] — the gateway-facing tool endpoint LobeChat / SperaxOS+// call when the LLM invokes a plugin function. Validates arguments, reads the+// agent id from the Sperax-Plugin-Settings header, and returns the concise tool+// result the model reads back. Rate-limit is mocked so the test stays offline.++import { describe, it, expect, vi } from 'vitest';+import { Readable } from 'node:stream';++vi.mock('../../api/_lib/rate-limit.js', () => ({+ limits: { widgetRead: vi.fn(async () => ({ success: true })) },+ clientIp: () => '127.0.0.1',+}));++const { default: handler } = await import('../../api/chat-plugin/[tool].js');++function makeReq({ method = 'POST', tool, body, headers = {} } = {}) {+ const req = Readable.from([Buffer.from(JSON.stringify(body ?? {}))]);+ req.method = method;+ req.url = `/api/chat-plugin/${tool}`;+ req.query = { tool };+ req.headers = { 'content-type': 'application/json', ...headers };+ return req;+}++function makeRes() {+ return {+ statusCode: 200,+ _h: {},+ headersSent: false,+ writableEnded: false,+ setHeader(k, v) {+ this._h[k.toLowerCase()] = v;+ },+ getHeader(k) {+ return this._h[k.toLowerCase()];+ },+ end(b) {+ this._body = b;+ this.writableEnded = true;+ },+ };+}++async function call(opts) {+ const res = makeRes();+ await handler(makeReq(opts), res);+ let body = null;+ try {+ body = JSON.parse(res._body);+ } catch {+ /* non-JSON body */+ }+ return { res, body };+}++describe('/api/chat-plugin/[tool]', () => {+ it('speak returns ok and clamps sentiment to [-1,1]', async () => {+ const { res, body } = await call({ tool: 'speak', body: { text: 'gm', sentiment: 5 } });+ expect(res.statusCode).toBe(200);+ expect(body).toMatchObject({ ok: true, action: 'speak', spoken: 'gm', sentiment: 1 });+ expect(res.getHeader('access-control-allow-origin')).toBe('*');+ });++ it('speak rejects missing text', async () => {+ const { res, body } = await call({ tool: 'speak', body: {} });+ expect(res.statusCode).toBe(400);+ expect(body.error).toBe('validation_error');+ });++ it('gesture validates the enum', async () => {+ expect((await call({ tool: 'gesture', body: { name: 'wave' } })).res.statusCode).toBe(200);+ expect((await call({ tool: 'gesture', body: { name: 'breakdance' } })).res.statusCode).toBe(+ 400,+ );+ });++ it('emote validates the enum and clamps weight', async () => {+ const { body } = await call({+ tool: 'emote',+ body: { trigger: 'celebration', weight: 9 },+ });+ expect(body).toMatchObject({ ok: true, emotion: 'celebration', weight: 1 });+ expect((await call({ tool: 'emote', body: { trigger: 'nope' } })).res.statusCode).toBe(400);+ });++ it('render-agent reads agentId from the Sperax-Plugin-Settings header', async () => {+ const { res, body } = await call({+ tool: 'render-agent',+ body: {},+ headers: { 'sperax-plugin-settings': JSON.stringify({ agentId: 'a-77' }) },+ });+ expect(res.statusCode).toBe(200);+ expect(body).toMatchObject({ ok: true, action: 'render_agent', agentId: 'a-77' });+ });++ it('render-agent also accepts the lobe-chat-plugin-settings header', async () => {+ const { body } = await call({+ tool: 'render-agent',+ body: {},+ headers: { 'lobe-chat-plugin-settings': JSON.stringify({ agentId: 'a-9' }) },+ });+ expect(body).toMatchObject({ ok: true, agentId: 'a-9' });+ });++ it('render-agent 400s without an agentId', async () => {+ expect((await call({ tool: 'render-agent', body: {} })).res.statusCode).toBe(400);+ });++ it('unknown tool returns 404', async () => {+ expect((await call({ tool: 'frobnicate', body: {} })).res.statusCode).toBe(404);+ });++ it('rejects non-POST methods', async () => {+ const res = makeRes();+ await handler(makeReq({ method: 'GET', tool: 'speak', body: {} }), res);+ expect(res.statusCode).toBe(405);+ });+});diff --git a/tests/chat-plugin-protocol.test.js b/tests/chat-plugin-protocol.test.jsnew file mode 100644index 000000000..e9719c2c1--- /dev/null+++ b/tests/chat-plugin-protocol.test.js@@ -0,0 +1,108 @@+// @vitest-environment jsdom+//+// Verifies the LobeChat / SperaxOS standalone-plugin protocol handling inside+// the embed iframe boot script (public/lobehub/iframe/boot.js). The host posts+// `<ns>:init-standalone-plugin` tool calls; boot.js must parse apiName + the+// JSON-string arguments and drive the <agent-3d> element, and must announce+// readiness on both the `lobe-chat:` and `speraxos:` channels.+import { describe, it, expect, vi, beforeAll } from 'vitest';++describe('chat plugin protocol (boot.js) — LobeChat / SperaxOS', () => {+ let el;+ let parentPost;++ beforeAll(async () => {+ document.body.innerHTML = '<div id="status"></div>';+ el = document.createElement('agent-3d');+ el.id = 'agent';+ document.body.appendChild(el);+ el.speak = vi.fn();+ el.play = vi.fn().mockResolvedValue(undefined);+ el.wave = vi.fn().mockResolvedValue(undefined);+ const realDispatch = el.dispatchEvent.bind(el);+ el.dispatchEvent = vi.fn(realDispatch);++ // window.parent === window in jsdom; record outbound posts without+ // re-dispatching them back into the listener.+ parentPost = vi.spyOn(window.parent, 'postMessage').mockImplementation(() => {});++ // Executes boot.js side effects: registers the message listener and+ // announces readiness.+ await import('../public/lobehub/iframe/boot.js');+ });++ // A host message, with event.source pinned to the parent window (boot.js+ // requires ev.source === window.parent).+ function hostSend(type, body) {+ const ev = new MessageEvent('message', {+ data: { type, ...body },+ origin: 'https://chat.sperax.io',+ });+ Object.defineProperty(ev, 'source', { value: window, configurable: true });+ window.dispatchEvent(ev);+ }++ function toolCall(ns, apiName, args, settings) {+ hostSend(`${ns}:init-standalone-plugin`, {+ payload: { identifier: 'three-ws', apiName, arguments: JSON.stringify(args) },+ ...(settings ? { settings } : {}),+ });+ }++ it('announces plugin-ready on both channels at boot', () => {+ const types = parentPost.mock.calls.map((c) => c[0] && c[0].type);+ expect(types).toContain('lobe-chat:plugin-ready-for-render');+ expect(types).toContain('speraxos:plugin-ready-for-render');+ });++ it('drives speak from a speraxos init-standalone-plugin call', () => {+ toolCall('speraxos', 'speak', { text: 'gm', sentiment: 0.5 });+ expect(el.speak).toHaveBeenCalledWith('gm', { sentiment: 0.5 });+ });++ it('accepts the lobe-chat: prefix identically', () => {+ el.speak.mockClear();+ toolCall('lobe-chat', 'speak', { text: 'hi' });+ expect(el.speak).toHaveBeenCalledWith('hi', { sentiment: 0 });+ });++ it('binds the agent from settings.agentId', () => {+ toolCall('speraxos', 'speak', { text: 'x' }, { agentId: 'agent-123' });+ expect(el.getAttribute('agent-id')).toBe('agent-123');+ });++ it('binds the agent from a render_agent call', () => {+ toolCall('speraxos', 'render_agent', { agentId: 'agent-999' });+ expect(el.getAttribute('agent-id')).toBe('agent-999');+ });++ it('plays a named gesture', () => {+ toolCall('speraxos', 'gesture', { name: 'wave' });+ expect(el.wave).toHaveBeenCalled();+ });++ it('dispatches emote as an agent:action CustomEvent', () => {+ el.dispatchEvent.mockClear();+ toolCall('speraxos', 'emote', { trigger: 'celebration', weight: 0.8 });+ const evt = el.dispatchEvent.mock.calls.at(-1)?.[0];+ expect(evt?.type).toBe('agent:action');+ expect(evt?.detail).toMatchObject({+ type: 'emote',+ payload: { trigger: 'celebration', weight: 0.8 },+ });+ });++ it('parses an already-parsed arguments object (defensive)', () => {+ el.speak.mockClear();+ hostSend('speraxos:init-standalone-plugin', {+ payload: { apiName: 'speak', arguments: { text: 'obj-args', sentiment: -0.3 } },+ });+ expect(el.speak).toHaveBeenCalledWith('obj-args', { sentiment: -0.3 });+ });++ it('ignores unrelated plugin channels', () => {+ el.speak.mockClear();+ hostSend('speraxos:render-plugin-state', { payload: {} });+ expect(el.speak).not.toHaveBeenCalled();+ });+});diff --git a/tests/speech-factories.test.js b/tests/speech-factories.test.jsindex 591b7fe54..55f89e395 100644--- a/tests/speech-factories.test.js+++ b/tests/speech-factories.test.js@@ -33,6 +33,37 @@ describe('createTTS', () => {});});+describe('ElevenLabsTTS defaults', () => {+ it('requires a voiceId', () => {+ expect(() => new ElevenLabsTTS({})).toThrowError(/requires voiceId/);+ });++ it('defaults to the low-latency flash model', () => {+ expect(new ElevenLabsTTS({ voiceId: 'v' }).modelId).toBe('eleven_flash_v2_5');+ });++ it('uses ElevenLabs recommended voice-setting defaults', () => {+ const tts = new ElevenLabsTTS({ voiceId: 'v' });+ expect(tts.stability).toBe(0.5);+ expect(tts.similarityBoost).toBe(0.75);+ expect(tts.useSpeakerBoost).toBe(true);+ });++ it('lets callers override model and settings per instance', () => {+ const tts = new ElevenLabsTTS({+ voiceId: 'v',+ modelId: 'eleven_multilingual_v2',+ stability: 0.2,+ similarityBoost: 0.9,+ useSpeakerBoost: false,+ });+ expect(tts.modelId).toBe('eleven_multilingual_v2');+ expect(tts.stability).toBe(0.2);+ expect(tts.similarityBoost).toBe(0.9);+ expect(tts.useSpeakerBoost).toBe(false);+ });+});+describe('createSTT', () => {it('returns a BrowserSTT for provider "browser"', () => {expect(createSTT({ provider: 'browser' })).toBeInstanceOf(BrowserSTT);diff --git a/vercel.json b/vercel.jsonindex 65dc66dc9..6e958bdbf 100644--- a/vercel.json+++ b/vercel.json@@ -73,6 +73,14 @@"src": "/aws/","dest": "/aws/index.html"},+ {+ "src": "/ibm",+ "dest": "/ibm/index.html"+ },+ {+ "src": "/ibm/",+ "dest": "/ibm/index.html"+ },{"src": "/rss/announcements\\.xml","dest": "/api/rss/announcements"@@ -105,6 +113,10 @@"src": "/\\.well-known/chat-plugin\\.json","dest": "/api/wk?name=chat-plugin"},+ {+ "src": "/\\.well-known/sperax-plugin\\.json",+ "dest": "/api/wk?name=sperax-plugin"+ },{"src": "/\\.well-known/x402\\.json","dest": "/api/wk?name=x402-discovery"@@ -1803,6 +1815,18 @@"src": "/lobehub/iframe/(.*)","dest": "/lobehub/iframe/$1"},+ {+ "src": "/sperax/iframe",+ "dest": "/lobehub/iframe/index.html"+ },+ {+ "src": "/sperax/iframe/",+ "dest": "/lobehub/iframe/index.html"+ },+ {+ "src": "/sperax/iframe/(.*)",+ "dest": "/lobehub/iframe/$1"+ },{"src": "/reputation","dest": "/reputation/index.html"@@ -2588,4 +2612,4 @@"schedule": "*/5 * * * *"}]-}\ No newline at end of file+}diff --git a/vite.config.js b/vite.config.jsindex d2b199ca6..1547b2c43 100644--- a/vite.config.js+++ b/vite.config.js@@ -349,6 +349,7 @@ const appConfig = {'agents-auto-rig': resolve(__dirname, 'public/demos/agents/auto-rig.html'),'aws-marketplace-welcome': resolve(__dirname, 'pages/aws-marketplace/welcome.html'),'aws': resolve(__dirname, 'pages/aws/index.html'),+ 'ibm': resolve(__dirname, 'pages/ibm/index.html'),// dashboard-next prototype — sub-pages auto-discovered so the parallel// agents that land new pages/dashboard-next/*.html files don't have to// touch this config to register them as Rollup inputs.@@ -555,6 +556,8 @@ const appConfig = {'/aws-marketplace/error/': resolve(root, 'pages/aws-marketplace/welcome.html'),'/aws': resolve(root, 'pages/aws/index.html'),'/aws/': resolve(root, 'pages/aws/index.html'),+ '/ibm': resolve(root, 'pages/ibm/index.html'),+ '/ibm/': resolve(root, 'pages/ibm/index.html'),'/voice': resolve(root, 'pages/voice.html'),'/voice/': resolve(root, 'pages/voice.html'),'/brain': resolve(root, 'pages/brain.html'),