@shogo-ai/voice 1.10.0 → 2.4.2
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +89 -0
- package/dist/{chunk-S3S2RNO6.js → chunk-BI6SL35K.js} +1 -184
- package/dist/chunk-IOFWML5L.js +1078 -0
- package/dist/chunk-KMSL5PWK.js +540 -0
- package/dist/chunk-ME3SIZZU.js +581 -0
- package/dist/{chunk-T3T4EBWY.js → chunk-RALZRMFL.js} +6 -2
- package/dist/chunk-TQOBJMEK.js +17 -0
- package/dist/chunk-U5UC7ZVS.js +988 -0
- package/dist/chunk-UW7VQ3S6.js +148 -0
- package/dist/chunk-ZAW6F3YT.js +172 -0
- package/dist/index.cjs +748 -25
- package/dist/index.d.cts +396 -3
- package/dist/index.d.ts +396 -3
- package/dist/index.js +63 -3
- package/dist/live/client.cjs +173 -0
- package/dist/live/client.d.cts +132 -0
- package/dist/live/client.d.ts +132 -0
- package/dist/live/client.js +9 -0
- package/dist/native/index.d.cts +5 -2
- package/dist/native/index.d.ts +5 -2
- package/dist/native/index.js +15 -11
- package/dist/{organicParticlesShaders-DIva0vBO.d.ts → organicParticlesShaders-seZq7jYX.d.cts} +1 -421
- package/dist/{organicParticlesShaders-DIva0vBO.d.cts → organicParticlesShaders-seZq7jYX.d.ts} +1 -421
- package/dist/particlesConfig-0YbdPOdY.d.cts +223 -0
- package/dist/particlesConfig-0YbdPOdY.d.ts +223 -0
- package/dist/react/conversation.cjs +789 -0
- package/dist/react/conversation.d.cts +134 -0
- package/dist/react/conversation.d.ts +134 -0
- package/dist/react/conversation.js +13 -0
- package/dist/react/index.cjs +374 -36
- package/dist/react/index.d.cts +10 -141
- package/dist/react/index.d.ts +10 -141
- package/dist/react/index.js +23 -770
- package/dist/react/visuals.cjs +1048 -0
- package/dist/react/visuals.d.cts +70 -0
- package/dist/react/visuals.d.ts +70 -0
- package/dist/react/visuals.js +10 -0
- package/dist/route/agent.cjs +1047 -85
- package/dist/route/agent.js +3 -3
- package/dist/route/audio-tags.cjs +1047 -85
- package/dist/route/audio-tags.js +3 -3
- package/dist/route/index.cjs +1051 -85
- package/dist/route/index.d.cts +19 -3
- package/dist/route/index.d.ts +19 -3
- package/dist/route/index.js +3 -3
- package/dist/route/music.cjs +1047 -85
- package/dist/route/music.js +3 -3
- package/dist/route/op.cjs +2127 -0
- package/dist/route/op.d.cts +43 -0
- package/dist/route/op.d.ts +43 -0
- package/dist/route/op.js +27 -0
- package/dist/route/signed-url.cjs +1047 -85
- package/dist/route/signed-url.js +3 -3
- package/dist/route/tts-preview.cjs +1047 -85
- package/dist/route/tts-preview.d.cts +6 -4
- package/dist/route/tts-preview.d.ts +6 -4
- package/dist/route/tts-preview.js +3 -3
- package/dist/server.cjs +1047 -85
- package/dist/server.d.cts +40 -8
- package/dist/server.d.ts +40 -8
- package/dist/server.js +2 -2
- package/dist/types-Bfhu-aQH.d.cts +199 -0
- package/dist/types-Bfhu-aQH.d.ts +199 -0
- package/dist/{types-W9y6eMj3.d.ts → types-CadjTXNH.d.cts} +193 -12
- package/dist/{types-W9y6eMj3.d.cts → types-CadjTXNH.d.ts} +193 -12
- package/package.json +21 -1
- package/dist/chunk-B4JC3DK2.js +0 -529
- package/dist/chunk-O362EJQR.js +0 -524
|
@@ -191,19 +191,74 @@ function composeAgentPrompt(basePrompt, options = {}) {
|
|
|
191
191
|
|
|
192
192
|
// src/elevenlabs.ts
|
|
193
193
|
var DEFAULT_ELEVENLABS_BASE_URL = "https://api.elevenlabs.io";
|
|
194
|
-
var
|
|
195
|
-
"
|
|
196
|
-
"
|
|
197
|
-
"
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
194
|
+
var VOICE_TTS_MODELS = [
|
|
195
|
+
{ id: "eleven_v4", label: "Eleven v4", realtime: false, maxChars: 1e4 },
|
|
196
|
+
{ id: "eleven_v4_turbo", label: "Eleven v4 Turbo", realtime: true, maxChars: 1e4 },
|
|
197
|
+
{ id: "eleven_v3", label: "Eleven v3", realtime: false, maxChars: 5e3 },
|
|
198
|
+
{
|
|
199
|
+
id: "eleven_v3_conversational",
|
|
200
|
+
label: "Eleven v3 Conversational",
|
|
201
|
+
realtime: true,
|
|
202
|
+
maxChars: 5e3
|
|
203
|
+
},
|
|
204
|
+
{ id: "eleven_multilingual_v2", label: "Eleven Multilingual v2", realtime: false, maxChars: 1e4 },
|
|
205
|
+
{ id: "eleven_flash_v2_5", label: "Eleven Flash v2.5", realtime: true, maxChars: 4e4 },
|
|
206
|
+
{ id: "eleven_flash_v2", label: "Eleven Flash v2", realtime: true, maxChars: 3e4 },
|
|
207
|
+
{ id: "eleven_turbo_v2_5", label: "Eleven Turbo v2.5", realtime: true, maxChars: 4e4 },
|
|
208
|
+
{ id: "eleven_turbo_v2", label: "Eleven Turbo v2", realtime: true, maxChars: 3e4, deprecated: true }
|
|
209
|
+
];
|
|
210
|
+
var VOICE_TTS_MODEL_IDS = VOICE_TTS_MODELS.map((m) => m.id);
|
|
211
|
+
var DEFAULT_TTS_MODEL = "eleven_v4";
|
|
212
|
+
var CONVAI_SUPPORTED_TTS_MODELS = new Set(
|
|
213
|
+
VOICE_TTS_MODELS.filter((m) => m.realtime).map((m) => m.id)
|
|
214
|
+
);
|
|
215
|
+
var CONVAI_TTS_MODEL_FALLBACK = "eleven_v4_turbo";
|
|
216
|
+
var TTS_FALLBACK_MODEL = "eleven_flash_v2_5";
|
|
217
|
+
function getVoiceTtsModel(modelId) {
|
|
218
|
+
if (!modelId) return void 0;
|
|
219
|
+
return VOICE_TTS_MODELS.find((m) => m.id === modelId);
|
|
220
|
+
}
|
|
221
|
+
var loggedDowngrades = /* @__PURE__ */ new Set();
|
|
222
|
+
function resolveConvaiTtsModelDetailed(requested) {
|
|
223
|
+
if (requested && CONVAI_SUPPORTED_TTS_MODELS.has(requested)) {
|
|
224
|
+
return { modelId: requested, requested, downgraded: false };
|
|
225
|
+
}
|
|
226
|
+
const known = getVoiceTtsModel(requested);
|
|
227
|
+
const reason = !requested ? void 0 : known ? `${requested} is not supported by the convai realtime runtime` : `unknown TTS model ${requested}`;
|
|
228
|
+
if (reason && !loggedDowngrades.has(requested)) {
|
|
229
|
+
loggedDowngrades.add(requested);
|
|
230
|
+
try {
|
|
231
|
+
console.warn(
|
|
232
|
+
`[voice] convai TTS model ${requested} is unavailable (${reason}); using ${CONVAI_TTS_MODEL_FALLBACK}`
|
|
233
|
+
);
|
|
234
|
+
} catch {
|
|
235
|
+
}
|
|
236
|
+
}
|
|
237
|
+
return {
|
|
238
|
+
modelId: CONVAI_TTS_MODEL_FALLBACK,
|
|
239
|
+
requested: requested ?? null,
|
|
240
|
+
downgraded: Boolean(requested),
|
|
241
|
+
...reason ? { reason } : {}
|
|
242
|
+
};
|
|
243
|
+
}
|
|
202
244
|
function resolveConvaiTtsModel(requested) {
|
|
203
|
-
|
|
204
|
-
|
|
245
|
+
return resolveConvaiTtsModelDetailed(requested).modelId;
|
|
246
|
+
}
|
|
247
|
+
function isModelRelatedTtsFailure(status, body) {
|
|
248
|
+
if (status === 402) return true;
|
|
249
|
+
if (status !== 400 && status !== 403 && status !== 404 && status !== 422) return false;
|
|
250
|
+
return /model|plan|permission/i.test(body);
|
|
205
251
|
}
|
|
206
252
|
var DEFAULT_MUSIC_MODEL = "music_v1";
|
|
253
|
+
var VOICE_STS_MODEL_IDS = [
|
|
254
|
+
"eleven_multilingual_sts_v2",
|
|
255
|
+
"eleven_english_sts_v2"
|
|
256
|
+
];
|
|
257
|
+
var DEFAULT_STS_MODEL = "eleven_multilingual_sts_v2";
|
|
258
|
+
var VOICE_SPEECH_TO_TEXT_MODEL_IDS = ["scribe_v1"];
|
|
259
|
+
var DEFAULT_SPEECH_TO_TEXT_MODEL = "scribe_v1";
|
|
260
|
+
var VOICE_SOUND_GENERATION_MODEL_IDS = ["eleven_text_to_sound_v2"];
|
|
261
|
+
var DEFAULT_SOUND_GENERATION_MODEL = "eleven_text_to_sound_v2";
|
|
207
262
|
var ElevenLabsApiError = class extends Error {
|
|
208
263
|
constructor(message, status, body) {
|
|
209
264
|
super(message);
|
|
@@ -368,12 +423,18 @@ var ElevenLabsClient = class {
|
|
|
368
423
|
return data.signed_url;
|
|
369
424
|
}
|
|
370
425
|
/**
|
|
371
|
-
* One-shot TTS. Returns the raw audio bytes plus the model
|
|
372
|
-
*
|
|
373
|
-
*
|
|
426
|
+
* One-shot TTS. Returns the raw audio bytes plus the model that actually
|
|
427
|
+
* produced them.
|
|
428
|
+
*
|
|
429
|
+
* The requested model is never swapped silently: we only retry on
|
|
430
|
+
* {@link TTS_FALLBACK_MODEL} when the failure is plausibly about
|
|
431
|
+
* the model (400/403/404/422 whose body mentions model/plan/permission,
|
|
432
|
+
* or 402 for an out-of-plan model). Auth (401), rate limit (429), 5xx and
|
|
433
|
+
* network errors are surfaced as-is. When a fallback does happen the
|
|
434
|
+
* result reports `requestedModel`, `fellBack` and `fallbackReason`.
|
|
374
435
|
*/
|
|
375
436
|
async textToSpeech(params) {
|
|
376
|
-
const
|
|
437
|
+
const requestedModel = params.modelId && params.modelId.length > 0 ? params.modelId : DEFAULT_TTS_MODEL;
|
|
377
438
|
const accept = params.accept ?? "audio/mpeg";
|
|
378
439
|
const attempt = async (m) => {
|
|
379
440
|
const res2 = await this.fetchImpl(
|
|
@@ -390,19 +451,39 @@ var ElevenLabsClient = class {
|
|
|
390
451
|
);
|
|
391
452
|
return res2;
|
|
392
453
|
};
|
|
393
|
-
let res = await attempt(
|
|
394
|
-
let used =
|
|
395
|
-
|
|
396
|
-
|
|
397
|
-
used = "eleven_turbo_v2_5";
|
|
398
|
-
}
|
|
454
|
+
let res = await attempt(requestedModel);
|
|
455
|
+
let used = requestedModel;
|
|
456
|
+
let fellBack = false;
|
|
457
|
+
let fallbackReason;
|
|
399
458
|
if (!res.ok) {
|
|
400
|
-
const
|
|
401
|
-
|
|
459
|
+
const body = await res.text();
|
|
460
|
+
if (requestedModel !== TTS_FALLBACK_MODEL && isModelRelatedTtsFailure(res.status, body)) {
|
|
461
|
+
fallbackReason = `elevenlabs ${res.status} for ${requestedModel}: ${body.slice(0, 200)}`;
|
|
462
|
+
res = await attempt(TTS_FALLBACK_MODEL);
|
|
463
|
+
used = TTS_FALLBACK_MODEL;
|
|
464
|
+
fellBack = true;
|
|
465
|
+
if (!res.ok) {
|
|
466
|
+
const retryBody = await res.text();
|
|
467
|
+
throw new ElevenLabsApiError(
|
|
468
|
+
`textToSpeech failed: ${res.status}`,
|
|
469
|
+
res.status,
|
|
470
|
+
retryBody
|
|
471
|
+
);
|
|
472
|
+
}
|
|
473
|
+
} else {
|
|
474
|
+
throw new ElevenLabsApiError(`textToSpeech failed: ${res.status}`, res.status, body);
|
|
475
|
+
}
|
|
402
476
|
}
|
|
403
477
|
const audio = await res.arrayBuffer();
|
|
404
478
|
const contentType = res.headers.get("content-type") ?? accept;
|
|
405
|
-
return {
|
|
479
|
+
return {
|
|
480
|
+
audio,
|
|
481
|
+
modelId: used,
|
|
482
|
+
requestedModel,
|
|
483
|
+
fellBack,
|
|
484
|
+
...fallbackReason ? { fallbackReason } : {},
|
|
485
|
+
contentType
|
|
486
|
+
};
|
|
406
487
|
}
|
|
407
488
|
/**
|
|
408
489
|
* Low-level escape hatch for any ElevenLabs endpoint not covered by a
|
|
@@ -508,6 +589,119 @@ var ElevenLabsClient = class {
|
|
|
508
589
|
}
|
|
509
590
|
return { audio, contentType };
|
|
510
591
|
}
|
|
592
|
+
/**
|
|
593
|
+
* Convert speech to speech — the "voice changer": keep the performance,
|
|
594
|
+
* swap the voice. `POST /v1/speech-to-speech/{voiceId}` with a multipart
|
|
595
|
+
* audio part. Returns the converted audio bytes.
|
|
596
|
+
*
|
|
597
|
+
* @example
|
|
598
|
+
* ```ts
|
|
599
|
+
* const { audio } = await el.speechToSpeech({
|
|
600
|
+
* voiceId: '21m00Tcm4TlvDq8ikWAM',
|
|
601
|
+
* audio: await fetch(myRecording).then((r) => r.blob()),
|
|
602
|
+
* modelId: 'eleven_multilingual_sts_v2',
|
|
603
|
+
* })
|
|
604
|
+
* ```
|
|
605
|
+
*/
|
|
606
|
+
async speechToSpeech(params) {
|
|
607
|
+
if (!params.voiceId) throw new Error("speechToSpeech: voiceId is required");
|
|
608
|
+
if (!params.audio) throw new Error("speechToSpeech: audio is required");
|
|
609
|
+
const form = new FormData();
|
|
610
|
+
form.set("audio", params.audio, params.fileName ?? "audio");
|
|
611
|
+
form.set("model_id", params.modelId ?? DEFAULT_STS_MODEL);
|
|
612
|
+
if (params.voiceSettings) {
|
|
613
|
+
form.set("voice_settings", JSON.stringify(params.voiceSettings));
|
|
614
|
+
}
|
|
615
|
+
if (params.outputFormat) form.set("output_format", params.outputFormat);
|
|
616
|
+
if (params.fileFormat) form.set("file_format", params.fileFormat);
|
|
617
|
+
if (params.seed !== void 0) form.set("seed", String(params.seed));
|
|
618
|
+
if (params.removeBackgroundNoise !== void 0) {
|
|
619
|
+
form.set("remove_background_noise", String(params.removeBackgroundNoise));
|
|
620
|
+
}
|
|
621
|
+
const { audio, contentType } = await this.request({
|
|
622
|
+
method: "POST",
|
|
623
|
+
path: `/v1/speech-to-speech/${encodeURIComponent(params.voiceId)}`,
|
|
624
|
+
body: form,
|
|
625
|
+
accept: "audio/mpeg"
|
|
626
|
+
});
|
|
627
|
+
if (!audio) {
|
|
628
|
+
throw new ElevenLabsApiError(
|
|
629
|
+
"speechToSpeech: expected audio bytes but got a JSON response",
|
|
630
|
+
500,
|
|
631
|
+
""
|
|
632
|
+
);
|
|
633
|
+
}
|
|
634
|
+
return { audio, contentType };
|
|
635
|
+
}
|
|
636
|
+
/**
|
|
637
|
+
* Generate a sound effect from a text prompt. `POST /v1/sound-generation`.
|
|
638
|
+
*
|
|
639
|
+
* @example
|
|
640
|
+
* ```ts
|
|
641
|
+
* const { audio } = await el.soundEffects({ text: 'heavy wooden door creaking' })
|
|
642
|
+
* ```
|
|
643
|
+
*/
|
|
644
|
+
async soundEffects(params) {
|
|
645
|
+
if (!params.text || !params.text.trim()) {
|
|
646
|
+
throw new Error("soundEffects: text is required");
|
|
647
|
+
}
|
|
648
|
+
const body = {
|
|
649
|
+
text: params.text,
|
|
650
|
+
model_id: params.modelId ?? DEFAULT_SOUND_GENERATION_MODEL
|
|
651
|
+
};
|
|
652
|
+
if (params.durationSeconds !== void 0) body.duration_seconds = params.durationSeconds;
|
|
653
|
+
if (params.promptInfluence !== void 0) body.prompt_influence = params.promptInfluence;
|
|
654
|
+
if (params.loop !== void 0) body.loop = params.loop;
|
|
655
|
+
const { audio, contentType } = await this.request({
|
|
656
|
+
method: "POST",
|
|
657
|
+
path: "/v1/sound-generation",
|
|
658
|
+
body,
|
|
659
|
+
accept: "audio/mpeg",
|
|
660
|
+
...params.outputFormat ? { query: { output_format: params.outputFormat } } : {}
|
|
661
|
+
});
|
|
662
|
+
if (!audio) {
|
|
663
|
+
throw new ElevenLabsApiError(
|
|
664
|
+
"soundEffects: expected audio bytes but got a JSON response",
|
|
665
|
+
500,
|
|
666
|
+
""
|
|
667
|
+
);
|
|
668
|
+
}
|
|
669
|
+
return { audio, contentType };
|
|
670
|
+
}
|
|
671
|
+
/**
|
|
672
|
+
* Transcribe audio with Scribe. `POST /v1/speech-to-text` (multipart).
|
|
673
|
+
*
|
|
674
|
+
* @example
|
|
675
|
+
* ```ts
|
|
676
|
+
* const { text } = await el.transcribe({ file: recording })
|
|
677
|
+
* ```
|
|
678
|
+
*/
|
|
679
|
+
async transcribe(params) {
|
|
680
|
+
if (!params.file) throw new Error("transcribe: file is required");
|
|
681
|
+
const form = new FormData();
|
|
682
|
+
form.set("file", params.file, params.fileName ?? "audio");
|
|
683
|
+
form.set("model_id", params.modelId ?? DEFAULT_SPEECH_TO_TEXT_MODEL);
|
|
684
|
+
if (params.languageCode) form.set("language_code", params.languageCode);
|
|
685
|
+
if (params.diarize !== void 0) form.set("diarize", String(params.diarize));
|
|
686
|
+
if (params.tagAudioEvents !== void 0) {
|
|
687
|
+
form.set("tag_audio_events", String(params.tagAudioEvents));
|
|
688
|
+
}
|
|
689
|
+
if (params.numSpeakers !== void 0) form.set("num_speakers", String(params.numSpeakers));
|
|
690
|
+
const { json: json2 } = await this.request({
|
|
691
|
+
method: "POST",
|
|
692
|
+
path: "/v1/speech-to-text",
|
|
693
|
+
body: form,
|
|
694
|
+
accept: "application/json"
|
|
695
|
+
});
|
|
696
|
+
if (!json2 || typeof json2 !== "object") {
|
|
697
|
+
throw new ElevenLabsApiError(
|
|
698
|
+
"transcribe: expected a JSON transcription but got audio",
|
|
699
|
+
500,
|
|
700
|
+
""
|
|
701
|
+
);
|
|
702
|
+
}
|
|
703
|
+
return json2;
|
|
704
|
+
}
|
|
511
705
|
/** Probe whether a given voice id still exists on the caller's account. */
|
|
512
706
|
async voiceExists(voiceId) {
|
|
513
707
|
const res = await this.fetchImpl(
|
|
@@ -671,6 +865,321 @@ var MEMORY_CLIENT_TOOLS = [
|
|
|
671
865
|
}
|
|
672
866
|
];
|
|
673
867
|
|
|
868
|
+
// src/ops.ts
|
|
869
|
+
var MAX_AUDIO_BYTES = 25 * 1024 * 1024;
|
|
870
|
+
var MAX_JSON_BYTES = 8 * 1024;
|
|
871
|
+
var MAX_TEXT_BYTES = 256 * 1024;
|
|
872
|
+
var VOICE_OPS = [
|
|
873
|
+
{
|
|
874
|
+
id: "text-to-speech",
|
|
875
|
+
method: "POST",
|
|
876
|
+
hostedPath: "/voice/op/text-to-speech",
|
|
877
|
+
legacyHostedPath: "/voice/tts",
|
|
878
|
+
upstreamPath: "/v1/text-to-speech/{voiceId}",
|
|
879
|
+
pathParams: ["voiceId"],
|
|
880
|
+
transport: "json-binary",
|
|
881
|
+
call: "textToSpeech",
|
|
882
|
+
permission: "project:read",
|
|
883
|
+
maxBodyBytes: MAX_TEXT_BYTES,
|
|
884
|
+
cost: { unit: "character", per: 1 },
|
|
885
|
+
models: VOICE_TTS_MODEL_IDS,
|
|
886
|
+
defaultModel: CONVAI_TTS_MODEL_FALLBACK,
|
|
887
|
+
defaultVoiceId: true,
|
|
888
|
+
forward: {
|
|
889
|
+
text: "text",
|
|
890
|
+
voiceId: "voice_id",
|
|
891
|
+
modelId: "model_id",
|
|
892
|
+
voiceSettings: "voice_settings"
|
|
893
|
+
},
|
|
894
|
+
required: ["text"],
|
|
895
|
+
responseHeaders: ["x-tts-model-used", "x-tts-model-requested", "warning"],
|
|
896
|
+
accept: "audio/mpeg",
|
|
897
|
+
errorLabel: "TTS failed"
|
|
898
|
+
},
|
|
899
|
+
{
|
|
900
|
+
id: "text-to-speech-with-timestamps",
|
|
901
|
+
method: "POST",
|
|
902
|
+
hostedPath: "/voice/op/text-to-speech-with-timestamps",
|
|
903
|
+
upstreamPath: "/v1/text-to-speech/{voiceId}/with-timestamps",
|
|
904
|
+
pathParams: ["voiceId"],
|
|
905
|
+
transport: "json-json",
|
|
906
|
+
permission: "project:read",
|
|
907
|
+
maxBodyBytes: MAX_TEXT_BYTES,
|
|
908
|
+
cost: { unit: "character", per: 1 },
|
|
909
|
+
models: VOICE_TTS_MODEL_IDS,
|
|
910
|
+
defaultModel: CONVAI_TTS_MODEL_FALLBACK,
|
|
911
|
+
defaultVoiceId: true,
|
|
912
|
+
forward: {
|
|
913
|
+
text: "text",
|
|
914
|
+
voiceId: "voice_id",
|
|
915
|
+
modelId: "model_id",
|
|
916
|
+
voiceSettings: "voice_settings",
|
|
917
|
+
outputFormat: "output_format"
|
|
918
|
+
},
|
|
919
|
+
required: ["text"],
|
|
920
|
+
accept: "application/json"
|
|
921
|
+
},
|
|
922
|
+
{
|
|
923
|
+
id: "speech-to-speech",
|
|
924
|
+
method: "POST",
|
|
925
|
+
hostedPath: "/voice/op/speech-to-speech",
|
|
926
|
+
upstreamPath: "/v1/speech-to-speech/{voiceId}",
|
|
927
|
+
pathParams: ["voiceId"],
|
|
928
|
+
transport: "multipart-binary",
|
|
929
|
+
permission: "project:read",
|
|
930
|
+
maxBodyBytes: MAX_AUDIO_BYTES,
|
|
931
|
+
cost: { unit: "second", per: 1 },
|
|
932
|
+
models: VOICE_STS_MODEL_IDS,
|
|
933
|
+
defaultModel: DEFAULT_STS_MODEL,
|
|
934
|
+
defaultVoiceId: true,
|
|
935
|
+
forward: {
|
|
936
|
+
audio: "audio",
|
|
937
|
+
voiceId: "voice_id",
|
|
938
|
+
modelId: "model_id",
|
|
939
|
+
voiceSettings: "voice_settings",
|
|
940
|
+
outputFormat: "output_format",
|
|
941
|
+
fileFormat: "file_format",
|
|
942
|
+
seed: "seed",
|
|
943
|
+
removeBackgroundNoise: "remove_background_noise"
|
|
944
|
+
},
|
|
945
|
+
required: ["audio"],
|
|
946
|
+
accept: "audio/mpeg"
|
|
947
|
+
},
|
|
948
|
+
{
|
|
949
|
+
id: "speech-to-text",
|
|
950
|
+
method: "POST",
|
|
951
|
+
hostedPath: "/voice/op/speech-to-text",
|
|
952
|
+
upstreamPath: "/v1/speech-to-text",
|
|
953
|
+
transport: "multipart-json",
|
|
954
|
+
permission: "project:read",
|
|
955
|
+
maxBodyBytes: MAX_AUDIO_BYTES,
|
|
956
|
+
cost: { unit: "second", per: 1 },
|
|
957
|
+
models: VOICE_SPEECH_TO_TEXT_MODEL_IDS,
|
|
958
|
+
defaultModel: DEFAULT_SPEECH_TO_TEXT_MODEL,
|
|
959
|
+
forward: {
|
|
960
|
+
file: "file",
|
|
961
|
+
modelId: "model_id",
|
|
962
|
+
languageCode: "language_code",
|
|
963
|
+
diarize: "diarize",
|
|
964
|
+
tagAudioEvents: "tag_audio_events",
|
|
965
|
+
numSpeakers: "num_speakers"
|
|
966
|
+
},
|
|
967
|
+
required: ["file"],
|
|
968
|
+
accept: "application/json"
|
|
969
|
+
},
|
|
970
|
+
{
|
|
971
|
+
id: "sound-generation",
|
|
972
|
+
method: "POST",
|
|
973
|
+
hostedPath: "/voice/op/sound-generation",
|
|
974
|
+
upstreamPath: "/v1/sound-generation",
|
|
975
|
+
transport: "json-binary",
|
|
976
|
+
permission: "project:read",
|
|
977
|
+
maxBodyBytes: MAX_JSON_BYTES,
|
|
978
|
+
cost: { unit: "second", per: 1 },
|
|
979
|
+
models: VOICE_SOUND_GENERATION_MODEL_IDS,
|
|
980
|
+
defaultModel: DEFAULT_SOUND_GENERATION_MODEL,
|
|
981
|
+
forward: {
|
|
982
|
+
text: "text",
|
|
983
|
+
durationSeconds: "duration_seconds",
|
|
984
|
+
promptInfluence: "prompt_influence",
|
|
985
|
+
loop: "loop",
|
|
986
|
+
modelId: "model_id"
|
|
987
|
+
},
|
|
988
|
+
// `output_format` is a query param on this endpoint, not a body field — the
|
|
989
|
+
// typed `soundEffects()` client sends it there, and a body field is
|
|
990
|
+
// silently ignored upstream.
|
|
991
|
+
queryForward: ["output_format"],
|
|
992
|
+
required: ["text"],
|
|
993
|
+
accept: "audio/mpeg"
|
|
994
|
+
},
|
|
995
|
+
{
|
|
996
|
+
id: "music",
|
|
997
|
+
method: "POST",
|
|
998
|
+
hostedPath: "/voice/op/music",
|
|
999
|
+
legacyHostedPath: "/voice/music",
|
|
1000
|
+
upstreamPath: "/v1/music",
|
|
1001
|
+
transport: "json-binary",
|
|
1002
|
+
call: "composeMusic",
|
|
1003
|
+
permission: "project:read",
|
|
1004
|
+
maxBodyBytes: MAX_JSON_BYTES,
|
|
1005
|
+
cost: { unit: "second", per: 1 },
|
|
1006
|
+
models: [DEFAULT_MUSIC_MODEL],
|
|
1007
|
+
defaultModel: DEFAULT_MUSIC_MODEL,
|
|
1008
|
+
forward: {
|
|
1009
|
+
prompt: "prompt",
|
|
1010
|
+
compositionPlan: "composition_plan",
|
|
1011
|
+
musicLengthMs: "music_length_ms",
|
|
1012
|
+
modelId: "model_id",
|
|
1013
|
+
forceInstrumental: "force_instrumental",
|
|
1014
|
+
outputFormat: "output_format"
|
|
1015
|
+
},
|
|
1016
|
+
accept: "audio/mpeg",
|
|
1017
|
+
errorLabel: "Music generation failed",
|
|
1018
|
+
validate: (fields) => {
|
|
1019
|
+
const hasPrompt = typeof fields.prompt === "string" && fields.prompt.trim().length > 0;
|
|
1020
|
+
const hasPlan = fields.compositionPlan != null && typeof fields.compositionPlan === "object";
|
|
1021
|
+
return hasPrompt === hasPlan ? "Provide exactly one of `prompt` or `compositionPlan`" : null;
|
|
1022
|
+
}
|
|
1023
|
+
},
|
|
1024
|
+
{
|
|
1025
|
+
id: "voices",
|
|
1026
|
+
method: "GET",
|
|
1027
|
+
hostedPath: "/voice/op/voices",
|
|
1028
|
+
upstreamPath: "/v1/voices",
|
|
1029
|
+
transport: "json-json",
|
|
1030
|
+
permission: "project:read",
|
|
1031
|
+
maxBodyBytes: 0,
|
|
1032
|
+
cost: { unit: "request", per: 1 },
|
|
1033
|
+
queryForward: ["page_size", "search", "voice_type", "category", "next_page_token"],
|
|
1034
|
+
accept: "application/json"
|
|
1035
|
+
},
|
|
1036
|
+
{
|
|
1037
|
+
id: "models",
|
|
1038
|
+
method: "GET",
|
|
1039
|
+
hostedPath: "/voice/op/models",
|
|
1040
|
+
upstreamPath: "/v1/models",
|
|
1041
|
+
transport: "json-json",
|
|
1042
|
+
permission: "project:read",
|
|
1043
|
+
maxBodyBytes: 0,
|
|
1044
|
+
cost: { unit: "request", per: 1 },
|
|
1045
|
+
accept: "application/json"
|
|
1046
|
+
}
|
|
1047
|
+
];
|
|
1048
|
+
var VOICE_OP_IDS = VOICE_OPS.map((op) => op.id);
|
|
1049
|
+
function getVoiceOp(id) {
|
|
1050
|
+
if (!id) return void 0;
|
|
1051
|
+
return VOICE_OPS.find((op) => op.id === id);
|
|
1052
|
+
}
|
|
1053
|
+
function voiceOpForwardPath(op) {
|
|
1054
|
+
return op.legacyHostedPath ?? op.hostedPath;
|
|
1055
|
+
}
|
|
1056
|
+
function voiceOpReturnsAudio(op) {
|
|
1057
|
+
return op.transport === "json-binary" || op.transport === "multipart-binary";
|
|
1058
|
+
}
|
|
1059
|
+
function voiceOpUpstreamPath(op, params) {
|
|
1060
|
+
let path = op.upstreamPath;
|
|
1061
|
+
for (const name of op.pathParams ?? []) {
|
|
1062
|
+
const value = params[name];
|
|
1063
|
+
if (!value) {
|
|
1064
|
+
return { error: `Missing \`${name}\` (required path parameter for ${op.id})` };
|
|
1065
|
+
}
|
|
1066
|
+
path = path.split(`{${name}}`).join(encodeURIComponent(value));
|
|
1067
|
+
}
|
|
1068
|
+
return path;
|
|
1069
|
+
}
|
|
1070
|
+
var MODEL_FIELD = "modelId";
|
|
1071
|
+
function parseVoiceOpJsonBody(op, raw) {
|
|
1072
|
+
if (raw === null || typeof raw !== "object" || Array.isArray(raw)) {
|
|
1073
|
+
return { ok: false, status: 400, error: "Invalid JSON body" };
|
|
1074
|
+
}
|
|
1075
|
+
const body = raw;
|
|
1076
|
+
const fields = {};
|
|
1077
|
+
for (const [callerField, upstreamField] of Object.entries(op.forward ?? {})) {
|
|
1078
|
+
if (upstreamField && body[callerField] !== void 0) fields[callerField] = body[callerField];
|
|
1079
|
+
}
|
|
1080
|
+
for (const name of op.required ?? []) {
|
|
1081
|
+
const value = fields[name];
|
|
1082
|
+
if (value === void 0 || value === null || typeof value === "string" && !value.trim()) {
|
|
1083
|
+
return { ok: false, status: 400, error: `Missing \`${name}\`` };
|
|
1084
|
+
}
|
|
1085
|
+
}
|
|
1086
|
+
const modelCheck = checkVoiceOpModel(op, fields);
|
|
1087
|
+
if ("error" in modelCheck) return { ok: false, status: 400, ...modelCheck };
|
|
1088
|
+
if (op.validate) {
|
|
1089
|
+
const message = op.validate(fields);
|
|
1090
|
+
if (message) return { ok: false, status: 400, error: message };
|
|
1091
|
+
}
|
|
1092
|
+
return { ok: true, fields };
|
|
1093
|
+
}
|
|
1094
|
+
function parseVoiceOpForm(op, form) {
|
|
1095
|
+
const fields = {};
|
|
1096
|
+
for (const callerField of Object.keys(op.forward ?? {})) {
|
|
1097
|
+
const value = form.get(callerField);
|
|
1098
|
+
if (value !== null) fields[callerField] = value;
|
|
1099
|
+
}
|
|
1100
|
+
for (const name of op.required ?? []) {
|
|
1101
|
+
const value = fields[name];
|
|
1102
|
+
if (!(value instanceof Blob)) {
|
|
1103
|
+
return {
|
|
1104
|
+
ok: false,
|
|
1105
|
+
status: 400,
|
|
1106
|
+
error: `Missing \`${name}\` file part`,
|
|
1107
|
+
detail: value === void 0 ? `send a multipart body with a \`${name}\` file part` : `\`${name}\` must be a file part, not a text field`
|
|
1108
|
+
};
|
|
1109
|
+
}
|
|
1110
|
+
if (value.size === 0) {
|
|
1111
|
+
return { ok: false, status: 400, error: `Empty \`${name}\` file part` };
|
|
1112
|
+
}
|
|
1113
|
+
}
|
|
1114
|
+
const modelCheck = checkVoiceOpModel(op, fields);
|
|
1115
|
+
if ("error" in modelCheck) return { ok: false, status: 400, ...modelCheck };
|
|
1116
|
+
const forward = op.forward ?? {};
|
|
1117
|
+
const pathParams = new Set(op.pathParams ?? []);
|
|
1118
|
+
const out = new FormData();
|
|
1119
|
+
for (const [callerField, upstreamField] of Object.entries(forward)) {
|
|
1120
|
+
if (pathParams.has(callerField)) continue;
|
|
1121
|
+
const value = fields[callerField];
|
|
1122
|
+
if (value === void 0 || value === null || value === "") continue;
|
|
1123
|
+
if (value instanceof Blob) {
|
|
1124
|
+
const name = value instanceof File ? value.name : callerField;
|
|
1125
|
+
out.set(upstreamField, value, name);
|
|
1126
|
+
} else if (typeof value === "string") {
|
|
1127
|
+
out.set(upstreamField, value);
|
|
1128
|
+
} else {
|
|
1129
|
+
out.set(upstreamField, JSON.stringify(value));
|
|
1130
|
+
}
|
|
1131
|
+
}
|
|
1132
|
+
const modelField = forward[MODEL_FIELD];
|
|
1133
|
+
if (op.defaultModel && modelField && out.get(modelField) === null) {
|
|
1134
|
+
out.set(modelField, op.defaultModel);
|
|
1135
|
+
}
|
|
1136
|
+
return { ok: true, form: out, fields };
|
|
1137
|
+
}
|
|
1138
|
+
function voiceOpUpstreamBody(op, fields) {
|
|
1139
|
+
const pathParams = new Set(op.pathParams ?? []);
|
|
1140
|
+
const body = {};
|
|
1141
|
+
for (const [callerField, upstreamField] of Object.entries(op.forward ?? {})) {
|
|
1142
|
+
if (pathParams.has(callerField)) continue;
|
|
1143
|
+
const value = fields[callerField];
|
|
1144
|
+
if (value === void 0 || value === null) continue;
|
|
1145
|
+
body[upstreamField] = value;
|
|
1146
|
+
}
|
|
1147
|
+
return body;
|
|
1148
|
+
}
|
|
1149
|
+
function voiceOpPathParams(op, fields, query) {
|
|
1150
|
+
const out = {};
|
|
1151
|
+
for (const name of op.pathParams ?? []) {
|
|
1152
|
+
const fromBody = fields[name];
|
|
1153
|
+
const value = typeof fromBody === "string" && fromBody.length > 0 ? fromBody : query.get(name);
|
|
1154
|
+
if (value) out[name] = value;
|
|
1155
|
+
}
|
|
1156
|
+
return out;
|
|
1157
|
+
}
|
|
1158
|
+
function checkVoiceOpModel(op, fields) {
|
|
1159
|
+
const requested = fields[MODEL_FIELD];
|
|
1160
|
+
if (requested === void 0 || requested === null || requested === "") return { ok: true };
|
|
1161
|
+
if (typeof requested !== "string") {
|
|
1162
|
+
return { error: `\`${MODEL_FIELD}\` must be a string` };
|
|
1163
|
+
}
|
|
1164
|
+
if (op.models && !op.models.includes(requested)) {
|
|
1165
|
+
return {
|
|
1166
|
+
error: "unknown_model",
|
|
1167
|
+
detail: `Unknown model '${requested}' for ${op.id}`,
|
|
1168
|
+
allowed: op.models
|
|
1169
|
+
};
|
|
1170
|
+
}
|
|
1171
|
+
return { ok: true };
|
|
1172
|
+
}
|
|
1173
|
+
|
|
1174
|
+
// src/runtime-token.ts
|
|
1175
|
+
var WORKSPACE_RUNTIME_TOKEN_MESSAGE = "RUNTIME_AUTH_SECRET is the workspace runtime token; app code needs its project token (rt_v1_\u2026). Start the app through the preview (server_sync / restart), not from a workspace shell.";
|
|
1176
|
+
function readRuntimeAuthSecret(env = typeof process === "undefined" ? void 0 : process.env) {
|
|
1177
|
+
const token = env?.RUNTIME_AUTH_SECRET;
|
|
1178
|
+
if (!token) return void 0;
|
|
1179
|
+
if (token.startsWith("wrt_v1_")) throw new Error(WORKSPACE_RUNTIME_TOKEN_MESSAGE);
|
|
1180
|
+
return token;
|
|
1181
|
+
}
|
|
1182
|
+
|
|
674
1183
|
// src/server.ts
|
|
675
1184
|
function json(data, status = 200, extraHeaders = {}) {
|
|
676
1185
|
return new Response(JSON.stringify(data), {
|
|
@@ -711,26 +1220,112 @@ function parseMusicBody(raw) {
|
|
|
711
1220
|
}
|
|
712
1221
|
return { params };
|
|
713
1222
|
}
|
|
1223
|
+
var MISSING_API_HOST_MESSAGE = "createVoiceHandlers: runtime-token proxy mode needs SHOGO_API_URL (or SHOGO_CLOUD_URL) in env; refusing to guess an API host";
|
|
1224
|
+
function envApiUrl() {
|
|
1225
|
+
if (typeof process === "undefined" || !process.env) return void 0;
|
|
1226
|
+
return process.env.SHOGO_API_URL ?? process.env.SHOGO_CLOUD_URL;
|
|
1227
|
+
}
|
|
714
1228
|
function resolveProxyOptions(config) {
|
|
1229
|
+
if (config.mode === "byo") {
|
|
1230
|
+
if (config.proxy) {
|
|
1231
|
+
throw new Error(
|
|
1232
|
+
"createVoiceHandlers: mode 'byo' cannot be combined with an explicit proxy"
|
|
1233
|
+
);
|
|
1234
|
+
}
|
|
1235
|
+
return null;
|
|
1236
|
+
}
|
|
1237
|
+
const envProxy = () => {
|
|
1238
|
+
if (config.mode === "proxy" && config.apiKey) {
|
|
1239
|
+
LOG_WARN_CACHE.apiKeyIgnored(config.logger);
|
|
1240
|
+
}
|
|
1241
|
+
if (typeof process === "undefined" || !process.env) return null;
|
|
1242
|
+
const runtimeToken = readRuntimeAuthSecret();
|
|
1243
|
+
const projectId = process.env.PROJECT_ID;
|
|
1244
|
+
if (!runtimeToken || !projectId) return null;
|
|
1245
|
+
return {
|
|
1246
|
+
runtimeToken,
|
|
1247
|
+
projectId,
|
|
1248
|
+
// Deliberately not required here: see `resolveApiBase`. Throwing at
|
|
1249
|
+
// construction made every local-only handler (400 validation, 405s,
|
|
1250
|
+
// the static audio-tags catalog) unusable on a host with a token but
|
|
1251
|
+
// no URL — which is exactly CI's env.
|
|
1252
|
+
apiUrl: envApiUrl() ?? "",
|
|
1253
|
+
...config.fetch ? { fetch: config.fetch } : {}
|
|
1254
|
+
};
|
|
1255
|
+
};
|
|
715
1256
|
if (config.proxy) {
|
|
716
1257
|
if (!config.proxy.runtimeToken || !config.proxy.projectId || !config.proxy.apiUrl) {
|
|
717
1258
|
throw new Error(
|
|
718
1259
|
"createVoiceHandlers: proxy requires runtimeToken, projectId, and apiUrl"
|
|
719
1260
|
);
|
|
720
1261
|
}
|
|
1262
|
+
if (config.apiKey) LOG_WARN_CACHE.apiKeyIgnored(config.logger);
|
|
721
1263
|
return config.proxy;
|
|
722
1264
|
}
|
|
723
|
-
if (
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
1265
|
+
if (config.mode === "proxy") return envProxy();
|
|
1266
|
+
if (config.apiKey) return null;
|
|
1267
|
+
return envProxy();
|
|
1268
|
+
}
|
|
1269
|
+
var LOG_WARN_CACHE = {
|
|
1270
|
+
warned: false,
|
|
1271
|
+
apiKeyIgnored(logger) {
|
|
1272
|
+
if (LOG_WARN_CACHE.warned) return;
|
|
1273
|
+
LOG_WARN_CACHE.warned = true;
|
|
1274
|
+
(logger ?? NOOP_LOGGER)(
|
|
1275
|
+
"warn",
|
|
1276
|
+
'createVoiceHandlers: apiKey provided but runtime-token proxy mode is active; apiKey is ignored (pass mode: "byo" to use it)'
|
|
1277
|
+
);
|
|
1278
|
+
}
|
|
1279
|
+
};
|
|
1280
|
+
function resolveOpId(req, opId) {
|
|
1281
|
+
if (opId) return opId;
|
|
1282
|
+
try {
|
|
1283
|
+
const url = new URL(req.url);
|
|
1284
|
+
const fromQuery = url.searchParams.get("op");
|
|
1285
|
+
if (fromQuery) return fromQuery;
|
|
1286
|
+
const segments = url.pathname.split("/").filter(Boolean);
|
|
1287
|
+
const last = segments[segments.length - 1];
|
|
1288
|
+
if (last && segments[segments.length - 2] === "op") return last;
|
|
1289
|
+
return void 0;
|
|
1290
|
+
} catch {
|
|
1291
|
+
return void 0;
|
|
1292
|
+
}
|
|
1293
|
+
}
|
|
1294
|
+
async function readVoiceOpBody(op, req) {
|
|
1295
|
+
if (op.method === "GET") return { kind: "none" };
|
|
1296
|
+
if (op.transport === "multipart-binary" || op.transport === "multipart-json") {
|
|
1297
|
+
let form;
|
|
1298
|
+
try {
|
|
1299
|
+
form = await req.formData();
|
|
1300
|
+
} catch {
|
|
1301
|
+
return json({ error: "Invalid multipart body", detail: "send a multipart/form-data body" }, 400);
|
|
1302
|
+
}
|
|
1303
|
+
const parsed2 = parseVoiceOpForm(op, form);
|
|
1304
|
+
if (!parsed2.ok) {
|
|
1305
|
+
return json(
|
|
1306
|
+
{
|
|
1307
|
+
error: parsed2.error,
|
|
1308
|
+
...parsed2.detail ? { detail: parsed2.detail } : {},
|
|
1309
|
+
...parsed2.allowed ? { allowed: parsed2.allowed } : {}
|
|
1310
|
+
},
|
|
1311
|
+
parsed2.status
|
|
1312
|
+
);
|
|
1313
|
+
}
|
|
1314
|
+
return { kind: "form", form: parsed2.form, fields: parsed2.fields };
|
|
1315
|
+
}
|
|
1316
|
+
const raw = await readJson(req);
|
|
1317
|
+
const parsed = parseVoiceOpJsonBody(op, raw);
|
|
1318
|
+
if (!parsed.ok) {
|
|
1319
|
+
return json(
|
|
1320
|
+
{
|
|
1321
|
+
error: parsed.error,
|
|
1322
|
+
...parsed.detail ? { detail: parsed.detail } : {},
|
|
1323
|
+
...parsed.allowed ? { allowed: parsed.allowed } : {}
|
|
1324
|
+
},
|
|
1325
|
+
parsed.status
|
|
1326
|
+
);
|
|
1327
|
+
}
|
|
1328
|
+
return { kind: "json", fields: parsed.fields };
|
|
734
1329
|
}
|
|
735
1330
|
function createProxyHandlers(proxy, log) {
|
|
736
1331
|
const fetchImpl = proxy.fetch ?? globalThis.fetch;
|
|
@@ -739,8 +1334,12 @@ function createProxyHandlers(proxy, log) {
|
|
|
739
1334
|
"createVoiceHandlers proxy: global fetch is unavailable; pass proxy.fetch"
|
|
740
1335
|
);
|
|
741
1336
|
}
|
|
742
|
-
|
|
743
|
-
|
|
1337
|
+
function resolveApiBase() {
|
|
1338
|
+
const raw = proxy.apiUrl || envApiUrl();
|
|
1339
|
+
if (!raw) throw new Error(MISSING_API_HOST_MESSAGE);
|
|
1340
|
+
return raw.replace(/\/+$/, "");
|
|
1341
|
+
}
|
|
1342
|
+
function proxyUrl(base, path, forward) {
|
|
744
1343
|
const tail = [`projectId=${encodeURIComponent(proxy.projectId)}`];
|
|
745
1344
|
for (const [k, v] of Object.entries(forward)) {
|
|
746
1345
|
if (typeof v === "string" && v.length > 0) {
|
|
@@ -748,11 +1347,12 @@ function createProxyHandlers(proxy, log) {
|
|
|
748
1347
|
}
|
|
749
1348
|
}
|
|
750
1349
|
const sep = path.includes("?") ? "&" : "?";
|
|
751
|
-
return `${
|
|
1350
|
+
return `${base}${path}${sep}${tail.join("&")}`;
|
|
752
1351
|
}
|
|
753
1352
|
const FORWARDED_SIGNED_URL_PARAMS = ["agentName"];
|
|
754
1353
|
async function doSignedUrl(req) {
|
|
755
1354
|
if (req.method !== "GET") return json({ error: "Method Not Allowed" }, 405);
|
|
1355
|
+
const base = resolveApiBase();
|
|
756
1356
|
try {
|
|
757
1357
|
let incomingUrl = null;
|
|
758
1358
|
try {
|
|
@@ -766,7 +1366,7 @@ function createProxyHandlers(proxy, log) {
|
|
|
766
1366
|
if (v != null) forward[key] = v;
|
|
767
1367
|
}
|
|
768
1368
|
}
|
|
769
|
-
const upstream = await fetchImpl(proxyUrl("/api/voice/signed-url", forward), {
|
|
1369
|
+
const upstream = await fetchImpl(proxyUrl(base, "/api/voice/signed-url", forward), {
|
|
770
1370
|
method: "GET",
|
|
771
1371
|
headers: { "x-runtime-token": proxy.runtimeToken },
|
|
772
1372
|
credentials: "omit"
|
|
@@ -796,34 +1396,80 @@ function createProxyHandlers(proxy, log) {
|
|
|
796
1396
|
}
|
|
797
1397
|
});
|
|
798
1398
|
}
|
|
799
|
-
async function
|
|
800
|
-
|
|
801
|
-
const
|
|
802
|
-
|
|
803
|
-
|
|
1399
|
+
async function doOp(req, opId) {
|
|
1400
|
+
const id = resolveOpId(req, opId);
|
|
1401
|
+
const op = getVoiceOp(id);
|
|
1402
|
+
if (!op) {
|
|
1403
|
+
return json(
|
|
1404
|
+
{ error: "unknown_op", detail: `Unknown voice op '${id ?? ""}'`, allowed: VOICE_OP_IDS },
|
|
1405
|
+
404
|
|
1406
|
+
);
|
|
1407
|
+
}
|
|
1408
|
+
if (req.method !== op.method) return json({ error: "Method Not Allowed" }, 405);
|
|
1409
|
+
const parsed = await readVoiceOpBody(op, req);
|
|
1410
|
+
if (parsed instanceof Response) return parsed;
|
|
1411
|
+
const base = resolveApiBase();
|
|
1412
|
+
const forward = {};
|
|
1413
|
+
let incomingUrl = null;
|
|
804
1414
|
try {
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
1415
|
+
incomingUrl = new URL(req.url);
|
|
1416
|
+
} catch {
|
|
1417
|
+
}
|
|
1418
|
+
if (incomingUrl) {
|
|
1419
|
+
for (const key of [...op.pathParams ?? [], ...op.queryForward ?? []]) {
|
|
1420
|
+
const value = incomingUrl.searchParams.get(key);
|
|
1421
|
+
if (value != null) forward[key] = value;
|
|
1422
|
+
}
|
|
1423
|
+
}
|
|
1424
|
+
if (parsed.kind === "form") {
|
|
1425
|
+
for (const name of op.pathParams ?? []) {
|
|
1426
|
+
const value = parsed.fields[name];
|
|
1427
|
+
if (typeof value === "string" && value.length > 0) forward[name] = value;
|
|
1428
|
+
}
|
|
1429
|
+
}
|
|
1430
|
+
const hostedPath = `/api${voiceOpForwardPath(op)}`;
|
|
1431
|
+
const headers = { "x-runtime-token": proxy.runtimeToken };
|
|
1432
|
+
let body;
|
|
1433
|
+
if (parsed.kind === "json") {
|
|
1434
|
+
headers["content-type"] = "application/json";
|
|
1435
|
+
body = JSON.stringify(parsed.fields);
|
|
1436
|
+
} else if (parsed.kind === "form") {
|
|
1437
|
+
body = parsed.form;
|
|
1438
|
+
}
|
|
1439
|
+
if (op.accept) headers.accept = op.accept;
|
|
1440
|
+
try {
|
|
1441
|
+
const upstream = await fetchImpl(proxyUrl(base, hostedPath, forward), {
|
|
1442
|
+
method: op.method,
|
|
1443
|
+
headers,
|
|
1444
|
+
...body !== void 0 ? { body } : {},
|
|
813
1445
|
credentials: "omit"
|
|
814
1446
|
});
|
|
1447
|
+
if (upstream.status === 404) {
|
|
1448
|
+
return json(
|
|
1449
|
+
{
|
|
1450
|
+
error: "Not Implemented",
|
|
1451
|
+
detail: `this Shogo API has no voice routes (desktop without ELEVENLABS_API_KEY?) \u2014 ${hostedPath} returned 404 upstream`
|
|
1452
|
+
},
|
|
1453
|
+
501
|
|
1454
|
+
);
|
|
1455
|
+
}
|
|
815
1456
|
const buf = await upstream.arrayBuffer();
|
|
816
|
-
const
|
|
1457
|
+
const responseHeaders = {};
|
|
817
1458
|
const ct = upstream.headers.get("content-type");
|
|
818
|
-
if (ct)
|
|
819
|
-
|
|
1459
|
+
if (ct) responseHeaders["content-type"] = ct;
|
|
1460
|
+
for (const name of op.responseHeaders ?? []) {
|
|
1461
|
+
const value = upstream.headers.get(name);
|
|
1462
|
+
if (value) responseHeaders[name] = value;
|
|
1463
|
+
}
|
|
1464
|
+
return new Response(buf, { status: upstream.status, headers: responseHeaders });
|
|
820
1465
|
} catch (err) {
|
|
821
|
-
log("error",
|
|
1466
|
+
log("error", `proxy ${op.id} failed`, {
|
|
822
1467
|
error: err instanceof Error ? err.message : String(err)
|
|
823
1468
|
});
|
|
824
|
-
return json({ error:
|
|
1469
|
+
return json({ error: `${op.id} proxy failed` }, 502);
|
|
825
1470
|
}
|
|
826
1471
|
}
|
|
1472
|
+
const doMusic = (req) => doOp(req, "music");
|
|
827
1473
|
function notImplemented(label) {
|
|
828
1474
|
return async () => json(
|
|
829
1475
|
{
|
|
@@ -833,9 +1479,204 @@ function createProxyHandlers(proxy, log) {
|
|
|
833
1479
|
501
|
|
834
1480
|
);
|
|
835
1481
|
}
|
|
1482
|
+
async function doTts(req) {
|
|
1483
|
+
if (req.method === "POST") {
|
|
1484
|
+
let raw = null;
|
|
1485
|
+
try {
|
|
1486
|
+
const parsed = await req.clone().json();
|
|
1487
|
+
if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
|
|
1488
|
+
raw = parsed;
|
|
1489
|
+
}
|
|
1490
|
+
} catch {
|
|
1491
|
+
}
|
|
1492
|
+
if (raw && (typeof raw.text !== "string" || raw.text.trim().length === 0)) {
|
|
1493
|
+
const sentTags = Array.isArray(raw.audioTags) && raw.audioTags.length > 0;
|
|
1494
|
+
if (sentTags) {
|
|
1495
|
+
const tags = normalizeAudioTags(raw.audioTags) ?? [];
|
|
1496
|
+
const characterName = typeof raw.characterName === "string" ? raw.characterName : void 0;
|
|
1497
|
+
const text = buildPreviewLine(tags, characterName ?? "your companion");
|
|
1498
|
+
return doOp(
|
|
1499
|
+
new Request(req.url, {
|
|
1500
|
+
method: "POST",
|
|
1501
|
+
headers: { "content-type": "application/json" },
|
|
1502
|
+
body: JSON.stringify({ ...raw, text })
|
|
1503
|
+
}),
|
|
1504
|
+
"text-to-speech"
|
|
1505
|
+
);
|
|
1506
|
+
}
|
|
1507
|
+
}
|
|
1508
|
+
}
|
|
1509
|
+
return doOp(req, "text-to-speech");
|
|
1510
|
+
}
|
|
1511
|
+
function createProxyElevenLabs() {
|
|
1512
|
+
const unsupported = (prop) => {
|
|
1513
|
+
throw new Error(
|
|
1514
|
+
`createVoiceHandlers: elevenLabs.${prop} is not available in runtime-token proxy mode (textToSpeech, composeMusic, speechToSpeech, soundEffects and transcribe are hosted); pass mode: 'byo' with an apiKey`
|
|
1515
|
+
);
|
|
1516
|
+
};
|
|
1517
|
+
const textToSpeech = async (params) => {
|
|
1518
|
+
const upstream = await fetchImpl(proxyUrl(resolveApiBase(), "/api/voice/tts", {}), {
|
|
1519
|
+
method: "POST",
|
|
1520
|
+
headers: {
|
|
1521
|
+
"x-runtime-token": proxy.runtimeToken,
|
|
1522
|
+
"content-type": "application/json",
|
|
1523
|
+
accept: params.accept ?? "audio/mpeg"
|
|
1524
|
+
},
|
|
1525
|
+
body: JSON.stringify({
|
|
1526
|
+
text: params.text,
|
|
1527
|
+
voiceId: params.voiceId,
|
|
1528
|
+
...params.modelId ? { modelId: params.modelId } : {},
|
|
1529
|
+
...params.voiceSettings ? { voiceSettings: params.voiceSettings } : {}
|
|
1530
|
+
}),
|
|
1531
|
+
credentials: "omit"
|
|
1532
|
+
});
|
|
1533
|
+
if (upstream.status === 404) {
|
|
1534
|
+
throw new Error(
|
|
1535
|
+
"this Shogo API has no voice routes (desktop without ELEVENLABS_API_KEY?) \u2014 /api/voice/tts returned 404 upstream"
|
|
1536
|
+
);
|
|
1537
|
+
}
|
|
1538
|
+
if (!upstream.ok) {
|
|
1539
|
+
throw new ElevenLabsApiError(
|
|
1540
|
+
`textToSpeech failed: ${upstream.status}`,
|
|
1541
|
+
upstream.status,
|
|
1542
|
+
await upstream.text()
|
|
1543
|
+
);
|
|
1544
|
+
}
|
|
1545
|
+
const requestedModel = params.modelId ?? DEFAULT_TTS_MODEL;
|
|
1546
|
+
const usedModel = upstream.headers.get("x-tts-model-used") ?? requestedModel;
|
|
1547
|
+
const requestedHeader = upstream.headers.get("x-tts-model-requested") ?? requestedModel;
|
|
1548
|
+
return {
|
|
1549
|
+
audio: await upstream.arrayBuffer(),
|
|
1550
|
+
modelId: usedModel,
|
|
1551
|
+
requestedModel: requestedHeader,
|
|
1552
|
+
fellBack: usedModel !== requestedHeader,
|
|
1553
|
+
contentType: upstream.headers.get("content-type") ?? params.accept ?? "audio/mpeg"
|
|
1554
|
+
};
|
|
1555
|
+
};
|
|
1556
|
+
const composeMusic = async (params) => {
|
|
1557
|
+
const upstream = await fetchImpl(proxyUrl(resolveApiBase(), "/api/voice/music", {}), {
|
|
1558
|
+
method: "POST",
|
|
1559
|
+
headers: {
|
|
1560
|
+
"x-runtime-token": proxy.runtimeToken,
|
|
1561
|
+
"content-type": "application/json",
|
|
1562
|
+
accept: "audio/mpeg"
|
|
1563
|
+
},
|
|
1564
|
+
body: JSON.stringify(params),
|
|
1565
|
+
credentials: "omit"
|
|
1566
|
+
});
|
|
1567
|
+
if (upstream.status === 404) {
|
|
1568
|
+
throw new Error(
|
|
1569
|
+
"this Shogo API has no voice routes (desktop without ELEVENLABS_API_KEY?) \u2014 /api/voice/music returned 404 upstream"
|
|
1570
|
+
);
|
|
1571
|
+
}
|
|
1572
|
+
if (!upstream.ok) {
|
|
1573
|
+
throw new ElevenLabsApiError(
|
|
1574
|
+
`composeMusic failed: ${upstream.status}`,
|
|
1575
|
+
upstream.status,
|
|
1576
|
+
await upstream.text()
|
|
1577
|
+
);
|
|
1578
|
+
}
|
|
1579
|
+
return {
|
|
1580
|
+
audio: await upstream.arrayBuffer(),
|
|
1581
|
+
contentType: upstream.headers.get("content-type") ?? "audio/mpeg"
|
|
1582
|
+
};
|
|
1583
|
+
};
|
|
1584
|
+
const opResponse = async (opId, req) => {
|
|
1585
|
+
const op = getVoiceOp(opId);
|
|
1586
|
+
const res = await doOp(req, opId);
|
|
1587
|
+
if (res.status === 404) {
|
|
1588
|
+
throw new Error(
|
|
1589
|
+
`this Shogo API has no voice routes (desktop without ELEVENLABS_API_KEY?) \u2014 /api${voiceOpForwardPath(op)} returned 404 upstream`
|
|
1590
|
+
);
|
|
1591
|
+
}
|
|
1592
|
+
if (!res.ok) {
|
|
1593
|
+
throw new ElevenLabsApiError(
|
|
1594
|
+
`${opId} failed: ${res.status}`,
|
|
1595
|
+
res.status,
|
|
1596
|
+
await res.text()
|
|
1597
|
+
);
|
|
1598
|
+
}
|
|
1599
|
+
return res;
|
|
1600
|
+
};
|
|
1601
|
+
const opAudio = async (opId, req) => {
|
|
1602
|
+
const res = await opResponse(opId, req);
|
|
1603
|
+
return {
|
|
1604
|
+
audio: await res.arrayBuffer(),
|
|
1605
|
+
contentType: res.headers.get("content-type") ?? "audio/mpeg"
|
|
1606
|
+
};
|
|
1607
|
+
};
|
|
1608
|
+
const speechToSpeech = (params) => {
|
|
1609
|
+
const form = new FormData();
|
|
1610
|
+
form.set("audio", params.audio, params.fileName ?? "audio");
|
|
1611
|
+
if (params.modelId) form.set("modelId", params.modelId);
|
|
1612
|
+
if (params.voiceSettings) form.set("voiceSettings", JSON.stringify(params.voiceSettings));
|
|
1613
|
+
if (params.outputFormat) form.set("outputFormat", params.outputFormat);
|
|
1614
|
+
if (params.fileFormat) form.set("fileFormat", params.fileFormat);
|
|
1615
|
+
if (params.seed !== void 0) form.set("seed", String(params.seed));
|
|
1616
|
+
if (params.removeBackgroundNoise !== void 0) {
|
|
1617
|
+
form.set("removeBackgroundNoise", String(params.removeBackgroundNoise));
|
|
1618
|
+
}
|
|
1619
|
+
const query = `?voiceId=${encodeURIComponent(params.voiceId)}`;
|
|
1620
|
+
return opAudio(
|
|
1621
|
+
"speech-to-speech",
|
|
1622
|
+
new Request(`http://voice.invalid/voice/op/speech-to-speech${query}`, {
|
|
1623
|
+
method: "POST",
|
|
1624
|
+
body: form
|
|
1625
|
+
})
|
|
1626
|
+
);
|
|
1627
|
+
};
|
|
1628
|
+
const soundEffects = (params) => opAudio(
|
|
1629
|
+
"sound-generation",
|
|
1630
|
+
new Request(
|
|
1631
|
+
// `output_format` is a query param on this endpoint (see the row's
|
|
1632
|
+
// `queryForward`); sending it in the body would be dropped at EL.
|
|
1633
|
+
`http://voice.invalid/voice/op/sound-generation${params.outputFormat ? `?output_format=${encodeURIComponent(params.outputFormat)}` : ""}`,
|
|
1634
|
+
{
|
|
1635
|
+
method: "POST",
|
|
1636
|
+
headers: { "content-type": "application/json" },
|
|
1637
|
+
body: JSON.stringify({
|
|
1638
|
+
text: params.text,
|
|
1639
|
+
...params.durationSeconds !== void 0 ? { durationSeconds: params.durationSeconds } : {},
|
|
1640
|
+
...params.promptInfluence !== void 0 ? { promptInfluence: params.promptInfluence } : {},
|
|
1641
|
+
...params.loop !== void 0 ? { loop: params.loop } : {},
|
|
1642
|
+
...params.modelId ? { modelId: params.modelId } : {}
|
|
1643
|
+
})
|
|
1644
|
+
}
|
|
1645
|
+
)
|
|
1646
|
+
);
|
|
1647
|
+
const transcribe = async (params) => {
|
|
1648
|
+
const form = new FormData();
|
|
1649
|
+
form.set("file", params.file, params.fileName ?? "audio");
|
|
1650
|
+
if (params.modelId) form.set("modelId", params.modelId);
|
|
1651
|
+
if (params.languageCode) form.set("languageCode", params.languageCode);
|
|
1652
|
+
if (params.diarize !== void 0) form.set("diarize", String(params.diarize));
|
|
1653
|
+
if (params.tagAudioEvents !== void 0) {
|
|
1654
|
+
form.set("tagAudioEvents", String(params.tagAudioEvents));
|
|
1655
|
+
}
|
|
1656
|
+
if (params.numSpeakers !== void 0) form.set("numSpeakers", String(params.numSpeakers));
|
|
1657
|
+
const res = await opResponse(
|
|
1658
|
+
"speech-to-text",
|
|
1659
|
+
new Request("http://voice.invalid/voice/op/speech-to-text", {
|
|
1660
|
+
method: "POST",
|
|
1661
|
+
body: form
|
|
1662
|
+
})
|
|
1663
|
+
);
|
|
1664
|
+
return await res.json();
|
|
1665
|
+
};
|
|
1666
|
+
return new Proxy({}, {
|
|
1667
|
+
get(_t, prop) {
|
|
1668
|
+
if (prop === "textToSpeech") return textToSpeech;
|
|
1669
|
+
if (prop === "composeMusic") return composeMusic;
|
|
1670
|
+
if (prop === "speechToSpeech") return speechToSpeech;
|
|
1671
|
+
if (prop === "soundEffects") return soundEffects;
|
|
1672
|
+
if (prop === "transcribe") return transcribe;
|
|
1673
|
+
return unsupported(String(prop));
|
|
1674
|
+
}
|
|
1675
|
+
});
|
|
1676
|
+
}
|
|
836
1677
|
return {
|
|
837
1678
|
signedUrl: doSignedUrl,
|
|
838
|
-
tts:
|
|
1679
|
+
tts: doTts,
|
|
839
1680
|
music: doMusic,
|
|
840
1681
|
agent: {
|
|
841
1682
|
create: notImplemented("agent.create"),
|
|
@@ -843,30 +1684,23 @@ function createProxyHandlers(proxy, log) {
|
|
|
843
1684
|
delete: notImplemented("agent.delete")
|
|
844
1685
|
},
|
|
845
1686
|
audioTags: doAudioTags,
|
|
846
|
-
|
|
847
|
-
//
|
|
848
|
-
//
|
|
849
|
-
elevenLabs:
|
|
850
|
-
get(_t, prop) {
|
|
851
|
-
throw new Error(
|
|
852
|
-
`createVoiceHandlers: elevenLabs.${String(prop)} is not available in runtime-token proxy mode`
|
|
853
|
-
);
|
|
854
|
-
}
|
|
855
|
-
})
|
|
1687
|
+
op: doOp,
|
|
1688
|
+
// In proxy mode we don't own an EL client: media calls go through the
|
|
1689
|
+
// Shogo API, anything else is a loud error.
|
|
1690
|
+
elevenLabs: createProxyElevenLabs()
|
|
856
1691
|
};
|
|
857
1692
|
}
|
|
858
1693
|
function createVoiceHandlers(config) {
|
|
859
1694
|
const log = config.logger ?? NOOP_LOGGER;
|
|
860
1695
|
const proxy = resolveProxyOptions(config);
|
|
861
1696
|
if (proxy) {
|
|
862
|
-
if (config.apiKey) {
|
|
863
|
-
log("warn", "createVoiceHandlers: apiKey provided but runtime-token proxy mode is active; apiKey is ignored");
|
|
864
|
-
}
|
|
865
1697
|
return createProxyHandlers(proxy, log);
|
|
866
1698
|
}
|
|
867
|
-
if (!config.apiKey)
|
|
868
|
-
|
|
869
|
-
|
|
1699
|
+
if (!config.apiKey) {
|
|
1700
|
+
throw new Error(
|
|
1701
|
+
config.mode === "proxy" ? 'createVoiceHandlers: mode "proxy" needs RUNTIME_AUTH_SECRET + PROJECT_ID (+ SHOGO_API_URL) in env' : "createVoiceHandlers: apiKey is required (or run in a pod with RUNTIME_AUTH_SECRET + PROJECT_ID for proxy mode)"
|
|
1702
|
+
);
|
|
1703
|
+
}
|
|
870
1704
|
const getUser = config.getUser;
|
|
871
1705
|
const companionStore = config.companionStore;
|
|
872
1706
|
const includeMemoryTools = config.includeMemoryTools ?? true;
|
|
@@ -878,10 +1712,28 @@ function createVoiceHandlers(config) {
|
|
|
878
1712
|
};
|
|
879
1713
|
const el = new ElevenLabsClient(elConfig);
|
|
880
1714
|
async function resolveUser(req) {
|
|
1715
|
+
if (!getUser) {
|
|
1716
|
+
return json(
|
|
1717
|
+
{
|
|
1718
|
+
error: "Voice handler misconfigured",
|
|
1719
|
+
detail: "signedUrl / agent.* need getUser (and companionStore); tts and music do not."
|
|
1720
|
+
},
|
|
1721
|
+
500
|
|
1722
|
+
);
|
|
1723
|
+
}
|
|
881
1724
|
const u = await getUser(req);
|
|
882
1725
|
if (!u) return json({ error: "Unauthorized" }, 401);
|
|
883
1726
|
return u;
|
|
884
1727
|
}
|
|
1728
|
+
function missingCompanionStore() {
|
|
1729
|
+
return json(
|
|
1730
|
+
{
|
|
1731
|
+
error: "Voice handler misconfigured",
|
|
1732
|
+
detail: "companionStore is required for signedUrl / agent.*; tts and music do not need it."
|
|
1733
|
+
},
|
|
1734
|
+
500
|
|
1735
|
+
);
|
|
1736
|
+
}
|
|
885
1737
|
function handleElError(e, fallbackLabel) {
|
|
886
1738
|
if (e instanceof ElevenLabsApiError) {
|
|
887
1739
|
log("warn", `${fallbackLabel}: 11Labs ${e.status}`, { body: e.body });
|
|
@@ -895,6 +1747,7 @@ function createVoiceHandlers(config) {
|
|
|
895
1747
|
if (req.method !== "GET") return json({ error: "Method Not Allowed" }, 405);
|
|
896
1748
|
const u = await resolveUser(req);
|
|
897
1749
|
if (u instanceof Response) return u;
|
|
1750
|
+
if (!companionStore) return missingCompanionStore();
|
|
898
1751
|
const companion = await companionStore.findByUserId(u.id);
|
|
899
1752
|
if (!companion || !companion.agentId) return json({ error: "No companion" }, 404);
|
|
900
1753
|
const basePrompt = extractBasePrompt(companion.systemPrompt || "");
|
|
@@ -944,8 +1797,10 @@ function createVoiceHandlers(config) {
|
|
|
944
1797
|
}
|
|
945
1798
|
async function doTts(req) {
|
|
946
1799
|
if (req.method !== "POST") return json({ error: "Method Not Allowed" }, 405);
|
|
947
|
-
|
|
948
|
-
|
|
1800
|
+
if (getUser) {
|
|
1801
|
+
const u = await resolveUser(req);
|
|
1802
|
+
if (u instanceof Response) return u;
|
|
1803
|
+
}
|
|
949
1804
|
const raw = await readJson(req);
|
|
950
1805
|
if (raw === null || typeof raw !== "object") return json({ error: "Invalid JSON body" }, 400);
|
|
951
1806
|
const body = raw;
|
|
@@ -960,27 +1815,37 @@ function createVoiceHandlers(config) {
|
|
|
960
1815
|
text = buildPreviewLine(tags, body.characterName ?? "your companion").slice(0, 400);
|
|
961
1816
|
}
|
|
962
1817
|
try {
|
|
963
|
-
const
|
|
1818
|
+
const result = await el.textToSpeech({
|
|
964
1819
|
voiceId,
|
|
965
1820
|
text,
|
|
966
1821
|
...body.modelId ? { modelId: body.modelId } : {},
|
|
967
1822
|
voiceSettings
|
|
968
1823
|
});
|
|
969
|
-
|
|
970
|
-
|
|
971
|
-
|
|
972
|
-
|
|
973
|
-
|
|
974
|
-
|
|
975
|
-
|
|
1824
|
+
const headers = {
|
|
1825
|
+
"content-type": result.contentType,
|
|
1826
|
+
"cache-control": "private, max-age=3600",
|
|
1827
|
+
"x-tts-model-used": result.modelId,
|
|
1828
|
+
"x-tts-model-requested": result.requestedModel
|
|
1829
|
+
};
|
|
1830
|
+
if (result.fellBack) {
|
|
1831
|
+
headers.warning = `199 - "model ${result.requestedModel} not available, used ${result.modelId}"`;
|
|
1832
|
+
log("warn", "tts fell back to another model", {
|
|
1833
|
+
requested: result.requestedModel,
|
|
1834
|
+
used: result.modelId,
|
|
1835
|
+
reason: result.fallbackReason
|
|
1836
|
+
});
|
|
1837
|
+
}
|
|
1838
|
+
return new Response(result.audio, { headers });
|
|
976
1839
|
} catch (e) {
|
|
977
1840
|
return handleElError(e, "TTS failed");
|
|
978
1841
|
}
|
|
979
1842
|
}
|
|
980
1843
|
async function doMusic(req) {
|
|
981
1844
|
if (req.method !== "POST") return json({ error: "Method Not Allowed" }, 405);
|
|
982
|
-
|
|
983
|
-
|
|
1845
|
+
if (getUser) {
|
|
1846
|
+
const u = await resolveUser(req);
|
|
1847
|
+
if (u instanceof Response) return u;
|
|
1848
|
+
}
|
|
984
1849
|
const raw = await readJson(req);
|
|
985
1850
|
const parsed = parseMusicBody(raw);
|
|
986
1851
|
if ("error" in parsed) return json({ error: parsed.error }, 400);
|
|
@@ -996,10 +1861,104 @@ function createVoiceHandlers(config) {
|
|
|
996
1861
|
return handleElError(e, "Music generation failed");
|
|
997
1862
|
}
|
|
998
1863
|
}
|
|
1864
|
+
async function doOp(req, opId) {
|
|
1865
|
+
const id = resolveOpId(req, opId);
|
|
1866
|
+
const op = getVoiceOp(id);
|
|
1867
|
+
if (!op) {
|
|
1868
|
+
return json(
|
|
1869
|
+
{ error: "unknown_op", detail: `Unknown voice op '${id ?? ""}'`, allowed: VOICE_OP_IDS },
|
|
1870
|
+
404
|
|
1871
|
+
);
|
|
1872
|
+
}
|
|
1873
|
+
if (req.method !== op.method) return json({ error: "Method Not Allowed" }, 405);
|
|
1874
|
+
const parsed = await readVoiceOpBody(op, req);
|
|
1875
|
+
if (parsed instanceof Response) return parsed;
|
|
1876
|
+
const fields = parsed.kind === "none" ? {} : parsed.fields;
|
|
1877
|
+
let query;
|
|
1878
|
+
try {
|
|
1879
|
+
query = new URL(req.url).searchParams;
|
|
1880
|
+
} catch {
|
|
1881
|
+
query = new URLSearchParams();
|
|
1882
|
+
}
|
|
1883
|
+
const pathParams = voiceOpPathParams(op, fields, query);
|
|
1884
|
+
const upstream = voiceOpUpstreamPath(op, pathParams);
|
|
1885
|
+
if (typeof upstream !== "string") {
|
|
1886
|
+
return json({ error: upstream.error, detail: `set it in the body or as ?${op.pathParams?.[0]}=` }, 400);
|
|
1887
|
+
}
|
|
1888
|
+
const forwardedQuery = {};
|
|
1889
|
+
for (const key of op.queryForward ?? []) {
|
|
1890
|
+
const value = query.get(key);
|
|
1891
|
+
if (value) forwardedQuery[key] = value;
|
|
1892
|
+
}
|
|
1893
|
+
if (op.defaultVoiceId && !pathParams.voiceId) {
|
|
1894
|
+
return json(
|
|
1895
|
+
{
|
|
1896
|
+
error: "Missing `voiceId`",
|
|
1897
|
+
detail: `BYO mode has no project default voice \u2014 pass voiceId (or ?voiceId=)`
|
|
1898
|
+
},
|
|
1899
|
+
400
|
|
1900
|
+
);
|
|
1901
|
+
}
|
|
1902
|
+
try {
|
|
1903
|
+
if (op.call === "textToSpeech") {
|
|
1904
|
+
const result = await el.textToSpeech({
|
|
1905
|
+
voiceId: pathParams.voiceId ?? String(fields.voiceId ?? ""),
|
|
1906
|
+
text: String(fields.text ?? ""),
|
|
1907
|
+
...typeof fields.modelId === "string" ? { modelId: fields.modelId } : {},
|
|
1908
|
+
...fields.voiceSettings ? { voiceSettings: fields.voiceSettings } : {},
|
|
1909
|
+
...op.accept ? { accept: op.accept } : {}
|
|
1910
|
+
});
|
|
1911
|
+
const headers2 = {
|
|
1912
|
+
"content-type": result.contentType,
|
|
1913
|
+
"cache-control": "private, max-age=3600",
|
|
1914
|
+
"x-tts-model-used": result.modelId,
|
|
1915
|
+
"x-tts-model-requested": result.requestedModel
|
|
1916
|
+
};
|
|
1917
|
+
if (result.fellBack) {
|
|
1918
|
+
headers2.warning = `199 - "model ${result.requestedModel} not available, used ${result.modelId}"`;
|
|
1919
|
+
}
|
|
1920
|
+
return new Response(result.audio, { headers: headers2 });
|
|
1921
|
+
}
|
|
1922
|
+
if (op.call === "composeMusic") {
|
|
1923
|
+
const { audio, contentType } = await el.composeMusic({
|
|
1924
|
+
...typeof fields.prompt === "string" ? { prompt: fields.prompt } : {},
|
|
1925
|
+
...fields.compositionPlan ? { compositionPlan: fields.compositionPlan } : {},
|
|
1926
|
+
...typeof fields.musicLengthMs === "number" ? { musicLengthMs: fields.musicLengthMs } : {},
|
|
1927
|
+
...typeof fields.modelId === "string" ? { modelId: fields.modelId } : {},
|
|
1928
|
+
...typeof fields.forceInstrumental === "boolean" ? { forceInstrumental: fields.forceInstrumental } : {},
|
|
1929
|
+
...typeof fields.outputFormat === "string" ? { outputFormat: fields.outputFormat } : {}
|
|
1930
|
+
});
|
|
1931
|
+
return new Response(audio, {
|
|
1932
|
+
headers: {
|
|
1933
|
+
"content-type": contentType,
|
|
1934
|
+
"cache-control": "private, max-age=3600"
|
|
1935
|
+
}
|
|
1936
|
+
});
|
|
1937
|
+
}
|
|
1938
|
+
const upstreamBody = voiceOpUpstreamBody(op, fields);
|
|
1939
|
+
if (op.defaultModel && upstreamBody.model_id === void 0) {
|
|
1940
|
+
upstreamBody.model_id = op.defaultModel;
|
|
1941
|
+
}
|
|
1942
|
+
const response = await el.request({
|
|
1943
|
+
method: op.method,
|
|
1944
|
+
path: upstream,
|
|
1945
|
+
...parsed.kind === "form" ? { body: parsed.form } : parsed.kind === "json" ? { body: upstreamBody } : {},
|
|
1946
|
+
...Object.keys(forwardedQuery).length ? { query: forwardedQuery } : {},
|
|
1947
|
+
...op.accept ? { accept: op.accept } : {}
|
|
1948
|
+
});
|
|
1949
|
+
const headers = { "content-type": response.contentType };
|
|
1950
|
+
if (voiceOpReturnsAudio(op)) headers["cache-control"] = "private, max-age=3600";
|
|
1951
|
+
const body = response.audio ?? JSON.stringify(response.json ?? {});
|
|
1952
|
+
return new Response(body, { status: response.status, headers });
|
|
1953
|
+
} catch (e) {
|
|
1954
|
+
return handleElError(e, `${op.id} failed`);
|
|
1955
|
+
}
|
|
1956
|
+
}
|
|
999
1957
|
async function doAgentCreate(req) {
|
|
1000
1958
|
if (req.method !== "POST") return json({ error: "Method Not Allowed" }, 405);
|
|
1001
1959
|
const u = await resolveUser(req);
|
|
1002
1960
|
if (u instanceof Response) return u;
|
|
1961
|
+
if (!companionStore) return missingCompanionStore();
|
|
1003
1962
|
const existing = await companionStore.findByUserId(u.id);
|
|
1004
1963
|
if (existing) return json({ error: "Companion already exists" }, 409);
|
|
1005
1964
|
const raw = await readJson(req);
|
|
@@ -1050,6 +2009,7 @@ function createVoiceHandlers(config) {
|
|
|
1050
2009
|
if (req.method !== "PATCH") return json({ error: "Method Not Allowed" }, 405);
|
|
1051
2010
|
const u = await resolveUser(req);
|
|
1052
2011
|
if (u instanceof Response) return u;
|
|
2012
|
+
if (!companionStore) return missingCompanionStore();
|
|
1053
2013
|
const existing = await companionStore.findByUserId(u.id);
|
|
1054
2014
|
if (!existing) return json({ error: "No companion" }, 404);
|
|
1055
2015
|
const raw = await readJson(req);
|
|
@@ -1104,6 +2064,7 @@ function createVoiceHandlers(config) {
|
|
|
1104
2064
|
if (req.method !== "DELETE") return json({ error: "Method Not Allowed" }, 405);
|
|
1105
2065
|
const u = await resolveUser(req);
|
|
1106
2066
|
if (u instanceof Response) return u;
|
|
2067
|
+
if (!companionStore) return missingCompanionStore();
|
|
1107
2068
|
const existing = await companionStore.findByUserId(u.id);
|
|
1108
2069
|
if (!existing) return json({ ok: true });
|
|
1109
2070
|
if (existing.agentId) await el.deleteAgent(existing.agentId);
|
|
@@ -1133,6 +2094,7 @@ function createVoiceHandlers(config) {
|
|
|
1133
2094
|
delete: doAgentDelete
|
|
1134
2095
|
},
|
|
1135
2096
|
audioTags: doAudioTags,
|
|
2097
|
+
op: doOp,
|
|
1136
2098
|
elevenLabs: el
|
|
1137
2099
|
};
|
|
1138
2100
|
}
|