Skip to content

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

feat(voice): let users clone agent voices on their own ElevenLabs key

nirholas07efeda7f7aa
diff --git a/api/_lib/agent-voice-key.js b/api/_lib/agent-voice-key.js
new file mode 100644
index 000000000..38db9ef8c
--- /dev/null
+++ b/api/_lib/agent-voice-key.js
@@ -0,0 +1,95 @@
+// Which ElevenLabs credential serves a given agent's voice.
+//
+// There are three lanes, and they are not interchangeable: a cloned voice_id
+// only exists inside the ElevenLabs account that created it. Cloning on the
+// owner's key and synthesizing with the platform key returns a 404 from
+// ElevenLabs, so the lane a voice was bound on is recorded on the agent
+// (agent_identities.voice_key_source) and replayed on every synthesis.
+//
+// request — the caller sent `x-eleven-key` on this request. Highest priority:
+// an explicit per-request override, never stored.
+// owner — the agent owner saved an ElevenLabs key at /api/user/provider-keys.
+// Stored encrypted at rest (AES-256-GCM, api/_lib/provider-keys.js)
+// and decrypted per request. The owner's ElevenLabs account is
+// billed, so platform credits never apply.
+// platform — the platform ELEVENLABS_API_KEY. Metered to $THREE credits
+// (owner policy 2026-08-06: no free platform lane).
+//
+// BYOK is the activation path while no platform key exists: setting
+// ELEVENLABS_API_KEY on the service is the single change that lights up the
+// platform lane for every agent whose owner has no key of their own.
+
+import { sql } from './db.js';
+import { decryptProviderKey } from './provider-keys.js';
+import { elevenApiKey, resolveElevenKey } from './elevenlabs.js';
+
+/** Provider slug in users.provider_keys for an ElevenLabs BYOK key. */
+export const ELEVEN_PROVIDER = 'elevenlabs';
+
+/**
+ * Decrypt a user's stored ElevenLabs key, if they saved one.
+ * A corrupt or undecryptable blob resolves to null rather than throwing: the
+ * caller falls through to the next lane instead of failing the whole request.
+ * @param {string} userId
+ * @returns {Promise<string|null>}
+ */
+export async function loadOwnerElevenKey(userId) {
+ if (!userId) return null;
+ const [row] = await sql`SELECT provider_keys FROM users WHERE id = ${userId}`;
+ const encrypted = row?.provider_keys?.[ELEVEN_PROVIDER];
+ if (typeof encrypted !== 'string' || !encrypted) return null;
+ try {
+ return (await decryptProviderKey(encrypted)) || null;
+ } catch (err) {
+ console.warn('[voice-key] could not decrypt stored ElevenLabs key:', err?.message || err);
+ return null;
+ }
+}
+
+/**
+ * Resolve the credential to use for an agent's voice.
+ *
+ * @param {object} opts
+ * @param {import('http').IncomingMessage} [opts.req] request, for the `x-eleven-key` override.
+ * @param {string} [opts.ownerId] the agent's owner. Their stored key is the BYOK lane.
+ * @param {'owner'|'platform'|null} [opts.pin] replay a recorded lane instead of
+ * re-deciding it. Used on playback so a voice cloned on the owner's key is
+ * never synthesized with the platform key (which cannot see it).
+ * @returns {Promise<{ apiKey: string|null, source: 'request'|'owner'|'platform'|null }>}
+ */
+export async function resolveAgentElevenKey({ req = null, ownerId = null, pin = null } = {}) {
+ const fromRequest = req ? resolveElevenKey(req) : { apiKey: null, byok: false };
+ if (fromRequest.byok && fromRequest.apiKey) {
+ return { apiKey: fromRequest.apiKey, source: 'request' };
+ }
+
+ if (pin === 'owner') {
+ const ownerKey = await loadOwnerElevenKey(ownerId);
+ return ownerKey ? { apiKey: ownerKey, source: 'owner' } : { apiKey: null, source: null };
+ }
+ if (pin === 'platform') {
+ const platform = elevenApiKey();
+ return platform ? { apiKey: platform, source: 'platform' } : { apiKey: null, source: null };
+ }
+
+ // Unpinned (binding a new voice): the owner's own key wins over the platform
+ // key, because a user who saved one has opted into paying their own vendor
+ // bill rather than spending $THREE credits.
+ const ownerKey = await loadOwnerElevenKey(ownerId);
+ if (ownerKey) return { apiKey: ownerKey, source: 'owner' };
+
+ const platform = elevenApiKey();
+ if (platform) return { apiKey: platform, source: 'platform' };
+
+ return { apiKey: null, source: null };
+}
+
+/**
+ * The lane recorded on an agent row, normalized. Legacy rows (written before
+ * voice_key_source existed) predate BYOK binding and can only be platform clones.
+ * @param {string|null|undefined} stored
+ * @returns {'owner'|'platform'}
+ */
+export function normalizeKeySource(stored) {
+ return stored === 'owner' ? 'owner' : 'platform';
+}
diff --git a/api/_lib/elevenlabs.js b/api/_lib/elevenlabs.js
index cd485154b..e3a38dc5e 100644
--- a/api/_lib/elevenlabs.js
+++ b/api/_lib/elevenlabs.js
@@ -191,9 +191,15 @@ export async function createClonedVoice({ name, description, files, apiKey: keyO
/**
* 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.
+ *
+ * A voice only exists inside the account that created it, so `apiKey` must be
+ * the same credential the clone was made with (BYOK clones live on the user's
+ * own account, not the platform's).
+ * @param {string} voiceId
+ * @param {{ apiKey?: string|null }} [opts]
*/
-export async function deleteVoice(voiceId) {
- const apiKey = elevenApiKey();
+export async function deleteVoice(voiceId, { apiKey: keyOverride = null } = {}) {
+ const apiKey = keyOverride || elevenApiKey();
if (!apiKey || !voiceId) return;
try {
await fetch(`${ELEVEN_BASE}/voices/${encodeURIComponent(voiceId)}`, {
diff --git a/api/_lib/migrations/20260811130000_agent_voice_key_source.sql b/api/_lib/migrations/20260811130000_agent_voice_key_source.sql
new file mode 100644
index 000000000..8ff481021
--- /dev/null
+++ b/api/_lib/migrations/20260811130000_agent_voice_key_source.sql
@@ -0,0 +1,19 @@
+-- Which ElevenLabs credential owns an agent's bound voice.
+--
+-- A cloned voice_id only resolves against the account it was created on, so the
+-- credential and the voice are inseparable: synthesizing an owner-cloned voice
+-- with the platform key returns 404 from ElevenLabs. voice_key_source records
+-- the lane so playback can pick the same credential the clone was made with.
+--
+-- 'owner' — the agent owner's own ElevenLabs key (users.provider_keys.elevenlabs).
+-- The owner's ElevenLabs account is billed; no platform credits apply.
+-- 'platform' — the platform ELEVENLABS_API_KEY. Metered to $THREE credits.
+-- NULL — legacy rows written before this column existed; treated as 'platform'.
+--
+-- The voice columns themselves are re-declared idempotently here so a fresh
+-- database gets them from the migration runner rather than from the manual
+-- specs/schema/voice-cloning.sql apply.
+alter table agent_identities add column if not exists voice_provider text default 'browser';
+alter table agent_identities add column if not exists voice_id text;
+alter table agent_identities add column if not exists voice_cloned_at timestamptz;
+alter table agent_identities add column if not exists voice_key_source text;
diff --git a/api/_lib/provider-keys.js b/api/_lib/provider-keys.js
index 373276bf0..dacdcecd3 100644
--- a/api/_lib/provider-keys.js
+++ b/api/_lib/provider-keys.js
@@ -59,6 +59,7 @@ export const BYOK_PROVIDERS = {
rodin: { label: 'Rodin (Hyper3D)', prefix: '', hint: 'developer.hyper3d.ai' },
stability: { label: 'Stability AI', prefix: 'sk-', hint: 'platform.stability.ai/account/keys' },
replicate: { label: 'Replicate', prefix: 'r8_', hint: 'replicate.com/account/api-tokens' },
+ elevenlabs: { label: 'ElevenLabs', prefix: 'sk_', hint: 'elevenlabs.io/app/settings/api-keys' },
};
// Load and decrypt all stored provider keys for a user.
diff --git a/api/agents/_id/voice.js b/api/agents/_id/voice.js
index 3307feddd..27d5fa617 100644
--- a/api/agents/_id/voice.js
+++ b/api/agents/_id/voice.js
@@ -5,6 +5,14 @@
// 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
+//
+// Credentials. Every branch that touches ElevenLabs resolves its key through
+// api/_lib/agent-voice-key.js, which picks between an `x-eleven-key` request
+// override, the owner's stored BYOK key, and the platform key. The winning lane
+// is written to agent_identities.voice_key_source so playback replays the same
+// credential — a voice cloned onto the owner's account is invisible to the
+// platform key. Only the platform lane charges $THREE credits; a BYOK clone is
+// billed by ElevenLabs directly to the user whose key made it.
import { sql } from '../../_lib/db.js';
import { getSessionUser, authenticateBearer, extractBearer } from '../../_lib/auth.js';
@@ -14,19 +22,19 @@ import { limits } from '../../_lib/rate-limit.js';
import { requireCsrf } from '../../_lib/csrf.js';
import { chargeCreditsForAction, refundCredits } from '../../_lib/credits.js';
import {
- isConfigured,
listVoices,
createClonedVoice,
deleteVoice,
isValidModel,
normalizeVoiceSettings,
} from '../../_lib/elevenlabs.js';
+import { resolveAgentElevenKey, normalizeKeySource } from '../../_lib/agent-voice-key.js';
// Fire-and-forget ElevenLabs voice deletion. The clone slot is best-effort
// cleanup — a failure must be logged, never crash the process as an
// unhandled rejection.
-function deleteVoiceBestEffort(voiceId) {
- deleteVoice(voiceId).catch((err) =>
+function deleteVoiceBestEffort(voiceId, apiKey) {
+ deleteVoice(voiceId, { apiKey }).catch((err) =>
console.warn('[voice] deleteVoice failed for', voiceId, err?.message || err),
);
}
@@ -34,17 +42,41 @@ function deleteVoiceBestEffort(voiceId) {
const MAX_AUDIO_BYTES = 10 * 1024 * 1024; // 10 MB
const MIN_DURATION_SEC = 30;
+// Every ElevenLabs branch shares this shape when no credential is available at
+// all: neither the caller, the owner's saved key, nor the platform. It names the
+// two ways out so the UI can render a real next step instead of a dead 503.
+function noCredential(res, what) {
+ return json(res, 503, {
+ error: 'not_configured',
+ error_description: `${what} needs an ElevenLabs key. Save your own at /dashboard/account, or ask the operator to set ELEVENLABS_API_KEY.`,
+ byok_url: '/dashboard/account',
+ provider: 'elevenlabs',
+ });
+}
+
// Canonical voice-status response shape, shared by GET and the PUT branches.
-function voiceStatus(row) {
+function voiceStatus(row, extra = {}) {
return {
voice_provider: row?.voice_provider || 'browser',
voice_id: row?.voice_id || null,
voice_cloned_at: row?.voice_cloned_at || null,
voice_model: row?.voice_model || null,
voice_settings: row?.voice_settings || null,
+ voice_key_source: row?.voice_id ? normalizeKeySource(row?.voice_key_source) : null,
+ ...extra,
};
}
+// Binding a voice to an agent must use a credential that still exists on the
+// next request, because playback has to reach the same ElevenLabs account. The
+// stateless `x-eleven-key` header is explicitly never stored, so it is not a
+// binding lane here: only the owner's saved key (encrypted in users.provider_keys)
+// and the platform key qualify. The per-request override still works on the
+// stateless /api/tts/* endpoints where nothing is persisted.
+function resolveBindingKey(ownerId) {
+ return resolveAgentElevenKey({ ownerId });
+}
+
async function resolveAuth(req) {
const session = await getSessionUser(req);
if (session) return { userId: session.id };
@@ -90,8 +122,11 @@ export const handleVoice = wrap(async (req, res, id, action) => {
if (req.method === 'GET') {
const [row] =
- await sql`SELECT voice_provider, voice_id, voice_cloned_at, voice_model, voice_settings FROM agent_identities WHERE id = ${id}`;
- return json(res, 200, voiceStatus(row));
+ await sql`SELECT voice_provider, voice_id, voice_cloned_at, voice_model, voice_settings, voice_key_source FROM agent_identities WHERE id = ${id}`;
+ // Tell the client which lane is actually open, so it can render the
+ // "no key" state up front instead of discovering it on a failed clone.
+ const { source } = await resolveBindingKey(auth.userId);
+ return json(res, 200, voiceStatus(row, { available_key_source: source }));
}
// ── PUT — assign a voice and/or tune its settings ───────────────────────
@@ -108,13 +143,8 @@ export const handleVoice = wrap(async (req, res, id, action) => {
// frees the old clone in ElevenLabs to recover the quota slot.
if (req.method === 'PUT') {
- if (!isConfigured())
- return error(
- res,
- 503,
- 'not_configured',
- 'voice library is not configured on this server',
- );
+ const { apiKey, source: boundSource } = await resolveBindingKey(auth.userId);
+ if (!apiKey) return noCredential(res, 'The voice library');
let body;
try {
@@ -147,7 +177,16 @@ export const handleVoice = wrap(async (req, res, id, action) => {
}
const [current] =
- await sql`SELECT voice_id, voice_cloned_at, voice_model, voice_settings FROM agent_identities WHERE id = ${id}`;
+ await sql`SELECT voice_id, voice_cloned_at, voice_model, voice_settings, voice_key_source FROM agent_identities WHERE id = ${id}`;
+ // The old voice lives in whichever account cloned it; free it with that
+ // same credential, not with whichever one is winning today.
+ const oldKey =
+ normalizeKeySource(current?.voice_key_source) === boundSource
+ ? apiKey
+ : (await resolveAgentElevenKey({
+ ownerId: auth.userId,
+ pin: normalizeKeySource(current?.voice_key_source),
+ })).apiKey;
// Carry forward whatever wasn't explicitly provided.
const finalModel = hasModel ? model : (current?.voice_model ?? null);
diff --git a/api/user/provider-keys.js b/api/user/provider-keys.js
index 689209b37..cd3771574 100644
--- a/api/user/provider-keys.js
+++ b/api/user/provider-keys.js
@@ -1,6 +1,7 @@
// GET /api/user/provider-keys — returns which keys are set (never returns values)
// PATCH /api/user/provider-keys — set or clear individual provider keys
-// body: { anthropic?, openai?, grok?, meshy?, tripo?, rodin?, stability?, replicate? } — each string | null
+// body: { anthropic?, openai?, grok?, meshy?, tripo?, rodin?, stability?, replicate?, elevenlabs? }
+// — each string | null
// null = delete that key; string = store encrypted
import { sql } from '../_lib/db.js';
@@ -20,6 +21,7 @@ const patchSchema = z.object({
rodin: z.string().min(1).max(512).nullable().optional(),
stability: z.string().min(1).max(512).nullable().optional(),
replicate: z.string().min(1).max(512).nullable().optional(),
+ elevenlabs: z.string().min(1).max(512).nullable().optional(),
});
export default wrap(async (req, res) => {