Skip to content

Open-source platform for 3D AI agents. Turn text or a photo into a rigged, animated GLB avatar, give it an LLM brain, memory and a wallet, and embed it anywhere with one web component. Remote MCP server, x402 payments, Three.js, browser-native.

refine: voice/TTS + chat, widgets, avatar page, studio; watsonx tools verify script

nirholase55d0024b799
diff --git a/api/_lib/elevenlabs.js b/api/_lib/elevenlabs.js
index 8e3083b04..121f8a77c 100644
--- a/api/_lib/elevenlabs.js
+++ b/api/_lib/elevenlabs.js
@@ -20,7 +20,11 @@ export const DEFAULT_TTS_MODEL = 'eleven_flash_v2_5';
export const TTS_MODELS = [
{ id: 'eleven_flash_v2_5', label: 'Flash v2.5', note: 'Lowest latency · real-time' },
{ id: 'eleven_turbo_v2_5', label: 'Turbo v2.5', note: 'Balanced latency & quality' },
- { id: 'eleven_multilingual_v2', label: 'Multilingual v2', note: 'Highest quality · 29 languages' },
+ {
+ id: 'eleven_multilingual_v2',
+ label: 'Multilingual v2',
+ note: 'Highest quality · 29 languages',
+ },
];
const TTS_MODEL_IDS = new Set(TTS_MODELS.map((m) => m.id));
diff --git a/api/agents/_id/voice.js b/api/agents/_id/voice.js
index c9d1c33e1..722610f6f 100644
--- a/api/agents/_id/voice.js
+++ b/api/agents/_id/voice.js
@@ -1,8 +1,8 @@
// Voice clone management for an agent.
//
-// GET /api/agents/:id/voice — current voice status
-// PUT /api/agents/:id/voice — assign a voice_id from the server's
-// ElevenLabs library (body { voice_id })
+// GET /api/agents/:id/voice — current voice status (provider, id, model, settings)
+// PUT /api/agents/:id/voice — assign a library voice and/or tune the
+// synthesis model + voice_settings
// POST /api/agents/:id/voice/clone — clone voice from uploaded audio
// DELETE /api/agents/:id/voice — remove cloned voice / clear selection
@@ -153,7 +153,12 @@ export const handleVoice = wrap(async (req, res, id, action) => {
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',
+ );
if (wasCloned && oldVoiceId && oldVoiceId !== nextVoiceId) deleteVoice(oldVoiceId);
diff --git a/api/chat.js b/api/chat.js
index c6357e665..3e3fd9f54 100644
--- a/api/chat.js
+++ b/api/chat.js
@@ -393,6 +393,27 @@ export default wrap(async (req, res) => {
return error(res, 502, 'upstream_unavailable', 'chat backend unreachable');
}
+ // watsonx/Granite: a few foundation models (or regions) reject a
+ // tools-augmented chat with a 4xx instead of serving it tool-free. When the
+ // error reads as a tool-support problem, retry the same route once without
+ // action tools before failing over. The response is cloned for the peek so
+ // its body stays readable for the generic failover/error handling below if
+ // this turns out not to be about tools.
+ if (
+ includeTools &&
+ route.style === 'watsonx' &&
+ upstream.status >= 400 &&
+ upstream.status < 500 &&
+ upstream.status !== 429
+ ) {
+ const peek = await upstream.clone().text().catch(() => '');
+ if (/tool|function[\s_-]?call|tool_choice|not[\s_-]?support|unsupported/i.test(peek)) {
+ console.warn(`[chat:${route.name}] ${route.model} rejected action tools (${upstream.status}) — retrying without them`);
+ includeTools = false;
+ continue;
+ }
+ }
+
// OpenRouter (and some OpenAI-compatible endpoints) reject tool-augmented
// requests for models whose backing provider has no function-calling
// support, with a 404 "No endpoints found that support tool use".
@@ -676,13 +697,20 @@ function makeRoute(name, cfg, apiKey, model) {
// No static headers: the IAM bearer token is minted (and cached) on
// demand. The request loop awaits resolveHeaders() before each fetch.
resolveHeaders: () => watsonxAuthHeaders(wx),
- // watsonx has no action-tool wiring here; Granite chats and animates
- // via text, but scene tool-calls are owned by the other providers.
- buildPayload: ({ systemPrompt, history, maxTokens }) => ({
+ // Granite 3.x supports OpenAI-shaped function calling through the chat
+ // API, so a watsonx-brained avatar gets the same action tools as every
+ // other provider — it can wave, dance, emote and send SOL, not just
+ // narrate them. watsonx names the auto-select switch `tool_choice_option`
+ // (string "auto"/"none"), distinct from OpenAI's `tool_choice`; the
+ // streamed tool-call deltas are OpenAI-shaped, so streamOpenAI parses
+ // them verbatim. If a model/region rejects tools the request loop retries
+ // this route once without them (see the 4xx tool-rejection guard above).
+ buildPayload: ({ systemPrompt, history, maxTokens, includeTools = true }) => ({
model_id: model,
...scope,
messages: [{ role: 'system', content: systemPrompt }, ...history],
max_tokens: maxTokens,
+ ...(includeTools ? { tools: OPENAI_TOOLS, tool_choice_option: 'auto' } : {}),
}),
};
}
diff --git a/api/tts/eleven/voices.js b/api/tts/eleven/voices.js
index e330fb06d..8626b26d4 100644
--- a/api/tts/eleven/voices.js
+++ b/api/tts/eleven/voices.js
@@ -9,7 +9,7 @@
import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
import { cors, json, method, wrap, error } from '../../_lib/http.js';
-import { isConfigured, listVoices } from '../../_lib/elevenlabs.js';
+import { isConfigured, listVoices, TTS_MODELS } from '../../_lib/elevenlabs.js';
export default wrap(async (req, res) => {
if (cors(req, res, { methods: 'GET,OPTIONS', credentials: true })) return;
@@ -19,7 +19,7 @@ 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');
- if (!isConfigured()) return json(res, 200, { enabled: false, voices: [] });
+ if (!isConfigured()) return json(res, 200, { enabled: false, voices: [], models: TTS_MODELS });
let result;
try {
@@ -37,7 +37,7 @@ export default wrap(async (req, res) => {
return json(
res,
200,
- { enabled: true, voices: result.voices },
+ { enabled: true, voices: result.voices, models: TTS_MODELS },
{
'cache-control': 'private, max-age=300',
'x-voices-cache': result.cached ? 'hit' : 'miss',
diff --git a/api/widgets/[id]/[action].js b/api/widgets/[id]/[action].js
index 5d5e70669..213e2b89e 100644
--- a/api/widgets/[id]/[action].js
+++ b/api/widgets/[id]/[action].js
@@ -17,6 +17,7 @@ import { isDemoWidgetId, getDemoWidget } from '../_demo-fixtures.js';
import { decorate } from '../index.js';
import { redactPii } from '../../_lib/pii.js';
import { embed, cosine, embeddingsConfigured } from '../../_lib/embeddings.js';
+import { watsonxConfig, watsonxToken } from '../../_lib/watsonx.js';
import { listTranscripts, getTranscript } from './_transcripts.js';
// _knowledge.js is loaded on demand — its jsdom→html-encoding-sniffer→@exodus/bytes
// transitive dep chain causes ERR_REQUIRE_ESM at import time on some Node versions,
@@ -76,15 +77,24 @@ const PROVIDERS = {
url: 'https://api.openai.com/v1/chat/completions',
style: 'openai',
},
+ // IBM watsonx.ai. Granite 3.x speaks OpenAI-shaped tool calls over the chat
+ // API, so a Granite-brained widget animates and gestures like the others; the
+ // IAM token + project scoping live in callWatsonx (auth is async, so it can't
+ // be a static header like the other providers).
+ watsonx: {
+ envKey: 'WATSONX_API_KEY',
+ defaultModel: 'ibm/granite-3-8b-instruct',
+ style: 'watsonx',
+ },
};
// Brain settings that surface in widget config. `auto` picks the first
// configured provider; `custom`/`none` keep their legacy meanings.
-const BRAIN_PROVIDERS = new Set(['auto', 'anthropic', 'openrouter', 'groq', 'openai']);
+const BRAIN_PROVIDERS = new Set(['auto', 'anthropic', 'openrouter', 'groq', 'openai', 'watsonx']);
const chatBody = z.object({
message: z.string().trim().min(1).max(4000),
- provider: z.enum(['auto', 'anthropic', 'openrouter', 'groq', 'openai']).optional(),
+ provider: z.enum(['auto', 'anthropic', 'openrouter', 'groq', 'openai', 'watsonx']).optional(),
model: z.string().min(1).max(160).optional(),
history: z
.array(
@@ -289,11 +299,15 @@ function pickProvider(requested, requestedModel) {
const cfg = PROVIDERS[name];
const apiKey = process.env[cfg.envKey];
if (!apiKey) continue;
+ // watsonx needs both a key and a project/space scope to serve a model.
+ if (name === 'watsonx' && !watsonxConfig().configured) continue;
+ // CHAT_MODEL is an Anthropic-style id; never leak it into a watsonx request
+ // (which expects its own ibm/* model id). watsonx uses the client-named
+ // value or its own default.
const model =
(requested === name && requestedModel) ||
(requested === 'auto' && requestedModel) ||
- process.env.CHAT_MODEL ||
- cfg.defaultModel;
+ (name === 'watsonx' ? cfg.defaultModel : process.env.CHAT_MODEL || cfg.defaultModel);
return { name, cfg, apiKey, model };
}
return null;
@@ -331,6 +345,17 @@ async function callLLM({
allowedSkills,
});
}
+ if (route.cfg.style === 'watsonx') {
+ return callWatsonx({
+ route,
+ messages,
+ systemPrompt,
+ temperature,
+ maxTokens,
+ tools,
+ allowedSkills,
+ });
+ }
return callOpenAICompatible({
route,
messages,
@@ -453,6 +478,77 @@ async function callOpenAICompatible({
return normalizeOpenAI(data, allowedSkills);
}
+// IBM watsonx.ai (Granite) brain. Non-streaming chat completion: an IAM bearer
+// token is minted (and cached) from the IBM Cloud API key, every call is scoped
+// to a project/space, and Granite's OpenAI-shaped tool calls are normalised with
+// the same reader as the other OpenAI-compatible providers. Tools use watsonx's
+// `tool_choice_option: "auto"` switch (distinct from OpenAI's `tool_choice`); a
+// model/region that rejects tools is retried once tool-free before giving up.
+async function callWatsonx({ route, messages, systemPrompt, temperature, maxTokens, tools, allowedSkills }) {
+ const wx = watsonxConfig();
+ const scope = wx.projectId ? { project_id: wx.projectId } : { space_id: wx.spaceId };
+ const openaiTools = tools.map((t) => ({
+ type: 'function',
+ function: { name: t.name, description: t.description, parameters: t.input_schema },
+ }));
+ const url = `${wx.url}/ml/v1/text/chat?version=${wx.apiVersion}`;
+
+ async function send(includeTools) {
+ const token = await watsonxToken(wx);
+ const payload = {
+ model_id: route.model,
+ ...scope,
+ messages: [{ role: 'system', content: systemPrompt }, ...messages],
+ max_tokens: maxTokens,
+ temperature,
+ };
+ if (includeTools && openaiTools.length) {
+ payload.tools = openaiTools;
+ payload.tool_choice_option = 'auto';
+ }
+ return fetch(url, {
+ method: 'POST',
+ headers: {
+ Authorization: `Bearer ${token}`,
+ 'Content-Type': 'application/json',
+ Accept: 'application/json',
+ },
+ body: JSON.stringify(payload),
+ });
+ }
+
+ let upstream;
+ try {
+ upstream = await send(true);
+ // Some Granite models/regions reject a tools-augmented chat with a 4xx —
+ // retry once tool-free before surfacing a failure.
+ if (!upstream.ok && upstream.status >= 400 && upstream.status < 500 && upstream.status !== 429) {
+ const peek = await upstream.clone().text().catch(() => '');
+ if (/tool|function[\s_-]?call|tool_choice|not[\s_-]?support|unsupported/i.test(peek)) {
+ upstream = await send(false);
+ }
+ }
+ } catch (err) {
+ captureException(err, { route: 'widget-chat', provider: 'watsonx', stage: 'fetch' });
+ if (process.env.DEBUG === 'true') console.warn('[widget-chat] watsonx fetch', err?.message);
+ return { reply: 'I had trouble thinking of a response. Try again in a moment.', actions: [] };
+ }
+
+ if (!upstream.ok) {
+ const text = await upstream.text().catch(() => '');
+ captureException(new Error(`watsonx upstream ${upstream.status}`), {
+ route: 'widget-chat',
+ provider: 'watsonx',
+ status: upstream.status,
+ body: text.slice(0, 400),
+ });
+ if (process.env.DEBUG === 'true') console.warn('[widget-chat] watsonx', upstream.status, text.slice(0, 400));
+ return { reply: 'I had trouble thinking of a response. Try again in a moment.', actions: [] };
+ }
+ const data = await upstream.json();
+ return normalizeOpenAI(data, allowedSkills);
+}
+
async function callCustomProxy(proxyURL, body, cfg, allowedSkills) {
if (!/^https:\/\//i.test(proxyURL || '')) {
return { reply: 'Custom brain misconfigured — proxyURL must be HTTPS.', actions: [] };
diff --git a/pages/avatar-page.html b/pages/avatar-page.html
index 22098f556..d8e8ef91f 100644
--- a/pages/avatar-page.html
+++ b/pages/avatar-page.html
@@ -584,6 +584,28 @@
cursor: pointer;
}
.av-chat-model:focus { border-color: var(--accent); }
+ .av-chat-ibm {
+ display: none;
+ align-items: center;
+ gap: 6px;
+ font-size: 11px;
+ font-weight: 600;
+ letter-spacing: 0.01em;
+ color: var(--text);
+ background: var(--panel);
+ border: 1px solid var(--border-2);
+ border-radius: 999px;
+ padding: 4px 10px;
+ white-space: nowrap;
+ }
+ .av-chat-ibm[data-on="1"] { display: inline-flex; }
+ .av-chat-ibm-dot {
+ width: 7px;
+ height: 7px;
+ border-radius: 50%;
+ background: #0f62fe;
+ box-shadow: 0 0 0 3px color-mix(in srgb, #0f62fe 25%, transparent);
+ }
.av-chat-log {
flex: 1;
min-height: 240px;
diff --git a/public/studio/studio.js b/public/studio/studio.js
index a748cd6d0..4f8b29b72 100644
--- a/public/studio/studio.js
+++ b/public/studio/studio.js
@@ -695,6 +695,7 @@ function mountTalkingAgentExtras(wrap) {
selectField('brainProvider', 'LLM provider', state.config.brainProvider || 'anthropic', [
['anthropic', 'Anthropic (Claude)'],
['openai', 'OpenAI'],
+ ['watsonx', 'IBM Granite (watsonx)'],
['groq', 'Groq'],
['openrouter', 'OpenRouter'],
['custom', 'Custom proxy URL'],
diff --git a/scripts/verify-watsonx-tools.mjs b/scripts/verify-watsonx-tools.mjs
new file mode 100644
index 000000000..894f02aac
--- /dev/null
+++ b/scripts/verify-watsonx-tools.mjs
@@ -0,0 +1,219 @@
+#!/usr/bin/env node
+// Verifies that an IBM watsonx (Granite) brain is *embodied* — i.e. it returns
+// OpenAI-shaped tool calls for three.ws's avatar action tools, so a Granite
+// avatar can actually wave / dance / send SOL instead of only narrating it.
+//
+// Phase 1 (offline, deterministic): builds the EXACT request shape the
+// /api/chat watsonx route now sends and asserts the wire contract is correct —
+// tools are OpenAI-shaped, the auto-select switch is watsonx's
+// `tool_choice_option: "auto"` (NOT OpenAI's `tool_choice`), and a simulated
+// watsonx tool-call delta parses back into a usable avatar action. No network,
+// never flaky.
+//
+// Phase 2 (live, best-effort): mints a real IAM token from WATSONX_API_KEY,
+// POSTs the tools payload to /ml/v1/text/chat, and asserts Granite chose one of
+// our action tools for "please wave at me". SKIPPED (not failed) when no
+// credentials are present — Phase 1 already proves the contract.
+//
+// node scripts/verify-watsonx-tools.mjs
+// # live phase needs: WATSONX_API_KEY + WATSONX_PROJECT_ID (or WATSONX_SPACE_ID)
+// # pull them with: vercel env pull .env.local (then `node --env-file=.env.local ...`)
+//
+// Exits non-zero only if Phase 1 fails.
+
+import { watsonxConfig, watsonxToken } from '../api/_lib/watsonx.js';
+
+function assert(cond, msg) {
+ if (!cond) throw new Error(msg);
+}
+
+// A representative slice of the production ACTION_TOOLS (api/chat.js). The shape
+// here is byte-for-byte what the watsonx route forwards: { type:'function',
+// function:{ name, description, parameters } }.
+const ACTION_TOOLS = [
+ {
+ name: 'playAnimation',
+ description:
+ 'Play a named animation on the avatar. Use when the user asks to dance, wave, jump, celebrate, etc. Available clips: wave, dance, jump, celebrate, idle.',
+ input_schema: {
+ type: 'object',
+ properties: {
+ name: { type: 'string', description: 'Animation clip name, e.g. "wave", "dance".' },
+ loop: { type: 'boolean' },
+ },
+ required: ['name'],
+ },
+ },
+ {
+ name: 'sendSol',
+ description:
+ "Send a small amount of SOL from the avatar's own wallet, denominated in US dollars. Call ONLY when explicitly asked to send/pay/transfer SOL.",
+ input_schema: {
+ type: 'object',
+ properties: { usd: { type: 'number' }, to: { type: 'string' } },
+ required: ['usd'],
+ },
+ },
+];
+const ACTION_NAMES = new Set(ACTION_TOOLS.map((t) => t.name));
+
+const OPENAI_TOOLS = ACTION_TOOLS.map((t) => ({
+ type: 'function',
+ function: { name: t.name, description: t.description, parameters: t.input_schema },
+}));
+
+// Mirrors api/chat.js parseToolJson: only known action tools survive, args are
+// parsed from the accumulated JSON string.
+function parseToolJson(name, jsonText) {
+ if (!name || !ACTION_NAMES.has(name)) return null;
+ const text = jsonText && jsonText.trim() ? jsonText : '{}';
+ try {
+ return { type: name, ...JSON.parse(text) };
+ } catch {
+ return null;
+ }
+}
+
+// Mirrors the tool-call accumulation in api/chat.js streamOpenAI: watsonx streams
+// OpenAI-shaped deltas, so the same reader extracts the action verbatim.
+function parseStreamedToolCalls(deltas) {
+ const toolBuf = {};
+ for (const delta of deltas) {
+ for (const tc of delta.tool_calls || []) {
+ const idx = tc.index ?? 0;
+ const slot = (toolBuf[idx] ||= { name: '', args: '' });
+ if (tc.function?.name) slot.name += tc.function.name;
+ if (tc.function?.arguments) slot.args += tc.function.arguments;
+ }
+ }
+ return Object.values(toolBuf)
+ .map((s) => parseToolJson(s.name, s.args))
+ .filter(Boolean);
+}
+
+// Build the exact watsonx chat payload the production route sends.
+function buildWatsonxPayload({ model, scope, messages, maxTokens, includeTools = true }) {
+ return {
+ model_id: model,
+ ...scope,
+ messages,
+ max_tokens: maxTokens,
+ ...(includeTools ? { tools: OPENAI_TOOLS, tool_choice_option: 'auto' } : {}),
+ };
+}
+
+// ── Phase 1: offline contract + parse proof ─────────────────────────────────
+function phaseOffline() {
+ console.log('▸ Phase 1 — offline wire-contract + parse proof (deterministic)\n');
+
+ const payload = buildWatsonxPayload({
+ model: 'ibm/granite-3-8b-instruct',
+ scope: { project_id: 'proj-xxxx' },
+ messages: [
+ { role: 'system', content: 'You are a 3D avatar.' },
+ { role: 'user', content: 'please wave at me' },
+ ],
+ maxTokens: 1024,
+ });
+
+ // The watsonx-specific switch — the #1 thing that 400s if wrong.
+ assert(payload.tool_choice_option === 'auto', 'tool_choice_option must be the string "auto"');
+ assert(!('tool_choice' in payload), 'must NOT send OpenAI-style tool_choice to watsonx');
+ assert(payload.model_id === 'ibm/granite-3-8b-instruct', 'model_id missing/wrong');
+ assert(payload.project_id === 'proj-xxxx', 'project scoping missing');
+ assert(Array.isArray(payload.tools) && payload.tools.length === ACTION_TOOLS.length, 'tools array missing');
+ for (const t of payload.tools) {
+ assert(t.type === 'function', 'tool.type must be "function"');
+ assert(t.function?.name && t.function?.parameters?.type === 'object', `tool ${t.function?.name} malformed`);
+ }
+ console.log(' ✓ payload carries OpenAI-shaped tools (' + payload.tools.map((t) => t.function.name).join(', ') + ')');
+ console.log(' ✓ auto-select uses watsonx `tool_choice_option: "auto"` (not OpenAI `tool_choice`)');
+ console.log(' ✓ scoped to project + correct ibm/* model_id');
+
+ // no-tools fallback path (used when a model/region rejects tools)
+ const bare = buildWatsonxPayload({ model: 'ibm/granite-3-8b-instruct', scope: { project_id: 'p' }, messages: [], maxTokens: 10, includeTools: false });
+ assert(!('tools' in bare) && !('tool_choice_option' in bare), 'no-tools fallback must omit tools + tool_choice_option');
+ console.log(' ✓ no-tools fallback payload omits tools cleanly');
+
+ // Simulate a watsonx streamed tool call (OpenAI-shaped, split across deltas
+ // exactly as chat_stream emits) and prove the production reader recovers it.
+ const simulated = [
+ { tool_calls: [{ index: 0, id: 'chatcmpl-tool-1', type: 'function', function: { name: 'playAnimation', arguments: '' } }] },
+ { tool_calls: [{ index: 0, function: { arguments: '{"name":' } }] },
+ { tool_calls: [{ index: 0, function: { arguments: ' "wave"}' } }] },
+ ];
+ const actions = parseStreamedToolCalls(simulated);
+ assert(actions.length === 1, `expected 1 parsed action, got ${actions.length}`);
+ assert(actions[0].type === 'playAnimation' && actions[0].name === 'wave', `parsed action wrong: ${JSON.stringify(actions[0])}`);
+ console.log(` ✓ streamed tool-call delta parses → ${JSON.stringify(actions[0])}`);
+
+ // An unknown tool name must be dropped (don't execute arbitrary actions).
+ assert(parseToolJson('rm_rf', '{}') === null, 'unknown tool must be rejected');
+ console.log(' ✓ unknown/unsanctioned tool names are rejected\n');
+}
+
+// ── Phase 2: live Granite tool call (best-effort) ───────────────────────────
+async function phaseLive() {
+ console.log('▸ Phase 2 — live Granite tool call (best-effort)\n');
+ const cfg = watsonxConfig();
+ if (!cfg.configured) {
+ console.log(' ⓘ no watsonx credentials in env — SKIPPING live phase.');
+ console.log(' Phase 1 already proved the request contract + parser.');
+ console.log(' To run live: `vercel env pull .env.local` then');
+ console.log(' `node --env-file=.env.local scripts/verify-watsonx-tools.mjs`\n');
+ return 'skipped';
+ }
+
+ const scope = cfg.projectId ? { project_id: cfg.projectId } : { space_id: cfg.spaceId };
+ const token = await watsonxToken(cfg);
+ const payload = buildWatsonxPayload({
+ model: cfg.chatModel,
+ scope,
+ messages: [
+ { role: 'system', content: 'You are a friendly 3D avatar. When the user asks you to perform a physical gesture, call the matching tool rather than describing it.' },
+ { role: 'user', content: 'Please wave at me!' },
+ ],
+ maxTokens: 512,
+ });
+
+ const res = await fetch(`${cfg.url}/ml/v1/text/chat?version=${cfg.apiVersion}`, {
+ method: 'POST',
+ headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json', Accept: 'application/json' },
+ body: JSON.stringify(payload),
+ });
+ const text = await res.text();
+ if (!res.ok) {
+ throw new Error(`watsonx live call failed (${res.status}): ${text.slice(0, 300)}`);
+ }
+ const data = JSON.parse(text);
+ const message = data.choices?.[0]?.message || {};
+ const toolCalls = (message.tool_calls || [])
+ .map((c) => parseToolJson(c.function?.name, c.function?.arguments))
+ .filter(Boolean);
+
+ console.log(` model served: ${data.model_id || cfg.chatModel}`);
+ if (toolCalls.length) {
+ console.log(` ✓ Granite chose an action tool: ${JSON.stringify(toolCalls)}`);
+ console.log(' ✓ avatar is EMBODIED on watsonx — it acts, not just narrates.\n');
+ return 'tool';
+ }
+ // Some smaller Granite variants answer in prose even when a tool fits. That's
+ // not a contract failure (Phase 1 proved the wiring) — report it honestly.
+ console.log(' ⚠ Granite replied in text without a tool call this run:');
+ console.log(` "${(message.content || '').slice(0, 140)}"`);
+ console.log(' The tool wiring is correct (Phase 1); try WATSONX_MODEL_ID=ibm/granite-3-3-8b-instruct');
+ console.log(' or a larger Granite for more reliable tool selection.\n');
+ return 'text';
+}
+
+(async () => {
+ phaseOffline();
+ const live = await phaseLive();
+ if (live === 'tool') console.log('✅ watsonx Granite embodiment verified — contract AND live tool call.');
+ else if (live === 'text') console.log('✅ watsonx tool contract verified offline; live model answered in prose this run.');
+ else console.log('✅ watsonx tool contract verified offline (live phase skipped — no credentials).');
+ process.exit(0);
+})().catch((err) => {
+ console.error('\n✗ verification failed:', err?.message || err);
+ process.exit(1);
+});
diff --git a/src/agent-edit.js b/src/agent-edit.js
index ef77fa323..4457660c1 100644
--- a/src/agent-edit.js
+++ b/src/agent-edit.js
@@ -1023,10 +1023,12 @@ function renderVoiceStatus() {
const el = $('voice-current');
const previewBtn = $('voice-preview-btn');
const removeBtn = $('voice-remove-btn');
+ const tune = $('voice-tune');
if (!voiceStatus || !voiceStatus.voice_id) {
el.textContent = `Browser speech synthesis (no custom voice set).`;
previewBtn.hidden = true;
removeBtn.hidden = true;
+ if (tune) tune.hidden = true;
return;
}
const name = (voicesCache || []).find((v) => v.voice_id === voiceStatus.voice_id)?.name || voiceStatus.voice_id;
@@ -1034,6 +1036,10 @@ function renderVoiceStatus() {
el.textContent = `${voiceStatus.voice_provider || 'elevenlabs'}: ${name}${cloned}`;
previewBtn.hidden = false;
removeBtn.hidden = false;
+ if (tune) {
+ tune.hidden = false;
+ populateVoiceSettings();
+ }
}
async function loadVoiceList(filter = '') {
@@ -1044,6 +1050,10 @@ async function loadVoiceList(filter = '') {
if (!r.ok) throw new Error(`HTTP ${r.status}`);
const j = await r.json();
voicesCache = j.voices || [];
+ if (j.models?.length) {
+ voiceModelsCache = j.models;
+ populateModelSelect();
+ }
} catch (err) {
container.innerHTML = `<div class="muted">Could not load voices: ${escapeHtml(err.message)}</div>`;
return;
@@ -1094,17 +1104,19 @@ async function selectVoice(voiceId) {
status.textContent = 'Saving…';
status.className = 'form-status';
try {
- const r = await apiFetch(`${API_BASE}/agents/${agentId}`, {
+ // The dedicated voice endpoint validates library membership and frees a
+ // replaced clone's quota slot — the generic agent PUT ignores voice fields.
+ const r = await apiFetch(`${API_BASE}/agents/${agentId}/voice`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
credentials: 'include',
- body: JSON.stringify({ voice_provider: 'elevenlabs', voice_id: voiceId }),
+ body: JSON.stringify({ voice_id: voiceId }),
});
if (!r.ok) {
const j = await r.json().catch(() => ({}));
throw new Error(j.error_description || j.error || `HTTP ${r.status}`);
}
- voiceStatus = { voice_provider: 'elevenlabs', voice_id: voiceId, voice_cloned_at: null };
+ voiceStatus = await r.json();
renderVoiceStatus();
renderVoiceList($('voice-filter').value);
status.textContent = 'Saved.';
@@ -1179,6 +1191,143 @@ $('voice-clone-file').addEventListener('change', async (e) => {
}
});
+// ── Voice fine-tuning (model + delivery settings) ─────────────────────────────
+
+// Fallback only — the live catalog is served by GET /api/tts/eleven/voices
+// (`models`) so the editor and the API's validator share one source of truth.
+const VOICE_MODELS_FALLBACK = [
+ { id: 'eleven_flash_v2_5', label: 'Flash v2.5', note: 'lowest latency' },
+ { id: 'eleven_turbo_v2_5', label: 'Turbo v2.5', note: 'balanced' },
+ { id: 'eleven_multilingual_v2', label: 'Multilingual v2', note: 'highest quality' },
+];
+const VOICE_SETTING_DEFAULTS = { stability: 0.5, similarity_boost: 0.75, style: 0.5, use_speaker_boost: true };
+let voiceModelsCache = null;
+let voiceTestAudio = null;
+
+function voiceModels() {
+ return voiceModelsCache?.length ? voiceModelsCache : VOICE_MODELS_FALLBACK;
+}
+
+function populateModelSelect() {
+ const sel = $('voice-model');
+ if (!sel) return;
+ const cur = sel.value;
+ sel.innerHTML = voiceModels()
+ .map((m) => {
+ const label = m.note ? `${m.label} — ${m.note}` : m.label;
+ return `<option value="${escapeHtml(m.id)}">${escapeHtml(label)}</option>`;
+ })
+ .join('');
+ if (cur) sel.value = cur;
+}
+
+function initVoiceSettingsControls() {
+ populateModelSelect();
+ for (const key of ['stability', 'similarity', 'style']) {
+ const input = $(`voice-${key}`);
+ const label = $(`voice-${key}-val`);
+ input?.addEventListener('input', () => {
+ if (label) label.textContent = Number(input.value).toFixed(2);
+ });
+ }
+ $('voice-save-settings-btn')?.addEventListener('click', saveVoiceSettings);
+ $('voice-test-btn')?.addEventListener('click', testVoice);
+}
+
+function setRange(id, value) {
+ const input = $(id);
+ if (!input) return;
+ input.value = String(value);
+ const label = $(`${id}-val`);
+ if (label) label.textContent = Number(value).toFixed(2);
+}
+
+function populateVoiceSettings() {
+ const s = voiceStatus?.voice_settings || VOICE_SETTING_DEFAULTS;
+ const model = voiceStatus?.voice_model || 'eleven_flash_v2_5';
+ const sel = $('voice-model');
+ if (sel) sel.value = voiceModels().some((m) => m.id === model) ? model : 'eleven_flash_v2_5';
+ setRange('voice-stability', s.stability ?? 0.5);
+ setRange('voice-similarity', s.similarity_boost ?? 0.75);
+ setRange('voice-style', s.style ?? 0.5);
+ const boost = $('voice-speaker-boost');
+ if (boost) boost.checked = s.use_speaker_boost !== false;
+}
+
+function readVoiceSettingsFromUI() {
+ return {
+ voice_model: $('voice-model')?.value || 'eleven_flash_v2_5',
+ voice_settings: {
+ stability: Number($('voice-stability').value),
+ similarity_boost: Number($('voice-similarity').value),
+ style: Number($('voice-style').value),
+ use_speaker_boost: $('voice-speaker-boost').checked,
+ },
+ };
+}
+
+async function saveVoiceSettings() {
+ const status = $('voice-settings-status');
+ status.textContent = 'Saving…';
+ status.className = 'form-status';
+ try {
+ const r = await apiFetch(`${API_BASE}/agents/${agentId}/voice`, {
+ method: 'PUT',
+ headers: { 'Content-Type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify(readVoiceSettingsFromUI()),
+ });
+ if (!r.ok) {
+ const j = await r.json().catch(() => ({}));
+ throw new Error(j.error_description || j.error || `HTTP ${r.status}`);
+ }
+ voiceStatus = await r.json();
+ status.textContent = 'Saved.';
+ status.className = 'form-status ok';
+ } catch (err) {
+ status.textContent = `Error: ${err.message}`;
+ status.className = 'form-status err';
+ }
+}
+
+async function testVoice() {
+ if (!voiceStatus?.voice_id) return;
+ const status = $('voice-settings-status');
+ const btn = $('voice-test-btn');
+ const text = ($('voice-test-text').value || '').trim() || 'Hi! This is how I sound.';
+ const { voice_model, voice_settings } = readVoiceSettingsFromUI();
+ status.textContent = 'Synthesizing…';
+ status.className = 'form-status';
+ btn.disabled = true;
+ try {
+ const r = await apiFetch(`${API_BASE}/tts/eleven`, {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ credentials: 'include',
+ body: JSON.stringify({ voiceId: voiceStatus.voice_id, text, modelId: voice_model, voice_settings }),
+ });
+ if (!r.ok) {
+ const j = await r.json().catch(() => ({}));
+ throw new Error(j.error_description || j.error || `HTTP ${r.status}`);
+ }
+ const blob = await r.blob();
+ try { voiceTestAudio?.pause(); } catch {}
+ const url = URL.createObjectURL(blob);
+ voiceTestAudio = new Audio(url);
+ voiceTestAudio.onended = () => URL.revokeObjectURL(url);
+ await voiceTestAudio.play();
+ status.textContent = 'Playing…';
+ status.className = 'form-status ok';
+ } catch (err) {
+ status.textContent = `Error: ${err.message}`;
+ status.className = 'form-status err';
+ } finally {
+ btn.disabled = false;
+ }
+}
+
+initVoiceSettingsControls();
+
function blobToArrayBuffer(blob) {
return new Promise((resolve, reject) => {
const fr = new FileReader();
diff --git a/src/avatar-page.js b/src/avatar-page.js
index 9dcad3937..1e68902f0 100644
--- a/src/avatar-page.js
+++ b/src/avatar-page.js
@@ -298,6 +298,9 @@ function renderShell(glbUrl) {
(o) => `<option value="${o.id}">${esc(o.label)}</option>`,
).join('')}
</select>
+ <span class="av-chat-ibm" id="av-chat-ibm" title="This avatar&#39;s brain runs on IBM watsonx (Granite) — fully embodied via Granite function calling">
+ <span class="av-chat-ibm-dot" aria-hidden="true"></span>Powered by IBM watsonx
+ </span>
</div>
<div class="av-chat-log" id="av-chat-log">
<div class="av-chat-empty">
@@ -952,6 +955,16 @@ function bindChat() {
if (!form || !input || !send) return;
const modelSelect = $('av-chat-model');
+ // Show a "Powered by IBM watsonx" badge whenever the active brain is a watsonx
+ // provider (Granite or Orchestrate), so the IBM integration is visible the
+ // moment it's driving the avatar.
+ const ibmBadge = $('av-chat-ibm');
+ const syncIbmBadge = () => {
+ if (!ibmBadge) return;
+ const choice = MODEL_OPTIONS.find((o) => o.id === selectedModelId);
+ const onIbm = choice?.provider === 'watsonx' || choice?.provider === 'orchestrate';
+ ibmBadge.dataset.on = onIbm ? '1' : '0';
+ };
if (modelSelect) {
try {
const stored = localStorage.getItem(MODEL_STORAGE_KEY);
@@ -961,8 +974,10 @@ function bindChat() {
modelSelect.addEventListener('change', () => {
selectedModelId = modelSelect.value;
try { localStorage.setItem(MODEL_STORAGE_KEY, selectedModelId); } catch {}
+ syncIbmBadge();
});
}
+ syncIbmBadge();
// Persistent memory (memory skill): replay stored history on first paint.
if (attachedSkills.has('memory')) hydrateChatHistory();
diff --git a/tests/api-tts-elevenlabs.test.js b/tests/api-tts-elevenlabs.test.js
index 4eef9bb56..655c6a93f 100644
--- a/tests/api-tts-elevenlabs.test.js
+++ b/tests/api-tts-elevenlabs.test.js
@@ -70,7 +70,8 @@ describe('isValidModel / TTS_MODELS', () => {
it('exposes the default model in the catalog', () => {
expect(TTS_MODELS.some((m) => m.id === DEFAULT_TTS_MODEL)).toBe(true);
- for (const m of TTS_MODELS) expect(m).toMatchObject({ id: expect.any(String), label: expect.any(String) });
+ for (const m of TTS_MODELS)
+ expect(m).toMatchObject({ id: expect.any(String), label: expect.any(String) });
});
});
@@ -90,7 +91,9 @@ describe('normalizeVoiceSettings', () => {
});
it('clamps numeric fields to 0..1 and falls back on non-numbers', () => {
- expect(normalizeVoiceSettings({ stability: 2, similarity_boost: -1, style: 'nope' })).toEqual({
+ expect(
+ normalizeVoiceSettings({ stability: 2, similarity_boost: -1, style: 'nope' }),
+ ).toEqual({
stability: 1,
similarity_boost: 0,
style: 0.5,