@shogo-ai/voice 1.10.0 → 2.4.1

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.
Files changed (68) hide show
  1. package/README.md +89 -0
  2. package/dist/{chunk-S3S2RNO6.js → chunk-BI6SL35K.js} +1 -184
  3. package/dist/chunk-CLF25CZC.js +987 -0
  4. package/dist/chunk-KMSL5PWK.js +540 -0
  5. package/dist/chunk-ME3SIZZU.js +581 -0
  6. package/dist/chunk-TQOBJMEK.js +17 -0
  7. package/dist/{chunk-T3T4EBWY.js → chunk-UH75UVM2.js} +6 -2
  8. package/dist/chunk-UW7VQ3S6.js +148 -0
  9. package/dist/chunk-XE4LLC7Z.js +1067 -0
  10. package/dist/chunk-ZAW6F3YT.js +172 -0
  11. package/dist/index.cjs +735 -25
  12. package/dist/index.d.cts +373 -3
  13. package/dist/index.d.ts +373 -3
  14. package/dist/index.js +59 -3
  15. package/dist/live/client.cjs +173 -0
  16. package/dist/live/client.d.cts +132 -0
  17. package/dist/live/client.d.ts +132 -0
  18. package/dist/live/client.js +9 -0
  19. package/dist/native/index.d.cts +5 -2
  20. package/dist/native/index.d.ts +5 -2
  21. package/dist/native/index.js +15 -11
  22. package/dist/{organicParticlesShaders-DIva0vBO.d.ts → organicParticlesShaders-seZq7jYX.d.cts} +1 -421
  23. package/dist/{organicParticlesShaders-DIva0vBO.d.cts → organicParticlesShaders-seZq7jYX.d.ts} +1 -421
  24. package/dist/particlesConfig-0YbdPOdY.d.cts +223 -0
  25. package/dist/particlesConfig-0YbdPOdY.d.ts +223 -0
  26. package/dist/react/conversation.cjs +789 -0
  27. package/dist/react/conversation.d.cts +134 -0
  28. package/dist/react/conversation.d.ts +134 -0
  29. package/dist/react/conversation.js +13 -0
  30. package/dist/react/index.cjs +374 -36
  31. package/dist/react/index.d.cts +10 -141
  32. package/dist/react/index.d.ts +10 -141
  33. package/dist/react/index.js +23 -770
  34. package/dist/react/visuals.cjs +1048 -0
  35. package/dist/react/visuals.d.cts +70 -0
  36. package/dist/react/visuals.d.ts +70 -0
  37. package/dist/react/visuals.js +10 -0
  38. package/dist/route/agent.cjs +1038 -85
  39. package/dist/route/agent.js +3 -3
  40. package/dist/route/audio-tags.cjs +1038 -85
  41. package/dist/route/audio-tags.js +3 -3
  42. package/dist/route/index.cjs +1042 -85
  43. package/dist/route/index.d.cts +19 -3
  44. package/dist/route/index.d.ts +19 -3
  45. package/dist/route/index.js +3 -3
  46. package/dist/route/music.cjs +1038 -85
  47. package/dist/route/music.js +3 -3
  48. package/dist/route/op.cjs +2118 -0
  49. package/dist/route/op.d.cts +43 -0
  50. package/dist/route/op.d.ts +43 -0
  51. package/dist/route/op.js +27 -0
  52. package/dist/route/signed-url.cjs +1038 -85
  53. package/dist/route/signed-url.js +3 -3
  54. package/dist/route/tts-preview.cjs +1038 -85
  55. package/dist/route/tts-preview.d.cts +6 -4
  56. package/dist/route/tts-preview.d.ts +6 -4
  57. package/dist/route/tts-preview.js +3 -3
  58. package/dist/server.cjs +1038 -85
  59. package/dist/server.d.cts +40 -8
  60. package/dist/server.d.ts +40 -8
  61. package/dist/server.js +2 -2
  62. package/dist/types-Bfhu-aQH.d.cts +199 -0
  63. package/dist/types-Bfhu-aQH.d.ts +199 -0
  64. package/dist/{types-W9y6eMj3.d.ts → types-CadjTXNH.d.cts} +193 -12
  65. package/dist/{types-W9y6eMj3.d.cts → types-CadjTXNH.d.ts} +193 -12
  66. package/package.json +21 -1
  67. package/dist/chunk-B4JC3DK2.js +0 -529
  68. 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 CONVAI_SUPPORTED_TTS_MODELS = /* @__PURE__ */ new Set([
195
- "eleven_turbo_v2",
196
- "eleven_turbo_v2_5",
197
- "eleven_flash_v2",
198
- "eleven_flash_v2_5",
199
- "eleven_multilingual_v2"
200
- ]);
201
- var CONVAI_TTS_MODEL_FALLBACK = "eleven_turbo_v2_5";
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
- if (requested && CONVAI_SUPPORTED_TTS_MODELS.has(requested)) return requested;
204
- return CONVAI_TTS_MODEL_FALLBACK;
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 id that was
372
- * actually used (some models aren't available for every account, so we
373
- * fall back to `eleven_turbo_v2_5` on the first failure).
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 modelId = params.modelId && params.modelId.length > 0 ? params.modelId : "eleven_v3";
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(modelId);
394
- let used = modelId;
395
- if (!res.ok && modelId !== "eleven_turbo_v2_5") {
396
- res = await attempt("eleven_turbo_v2_5");
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 text = await res.text();
401
- throw new ElevenLabsApiError(`textToSpeech failed: ${res.status}`, res.status, text);
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 { audio, modelId: used, contentType };
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,312 @@ 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
+
674
1174
  // src/server.ts
675
1175
  function json(data, status = 200, extraHeaders = {}) {
676
1176
  return new Response(JSON.stringify(data), {
@@ -711,26 +1211,112 @@ function parseMusicBody(raw) {
711
1211
  }
712
1212
  return { params };
713
1213
  }
1214
+ 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";
1215
+ function envApiUrl() {
1216
+ if (typeof process === "undefined" || !process.env) return void 0;
1217
+ return process.env.SHOGO_API_URL ?? process.env.SHOGO_CLOUD_URL;
1218
+ }
714
1219
  function resolveProxyOptions(config) {
1220
+ if (config.mode === "byo") {
1221
+ if (config.proxy) {
1222
+ throw new Error(
1223
+ "createVoiceHandlers: mode 'byo' cannot be combined with an explicit proxy"
1224
+ );
1225
+ }
1226
+ return null;
1227
+ }
1228
+ const envProxy = () => {
1229
+ if (config.mode === "proxy" && config.apiKey) {
1230
+ LOG_WARN_CACHE.apiKeyIgnored(config.logger);
1231
+ }
1232
+ if (typeof process === "undefined" || !process.env) return null;
1233
+ const runtimeToken = process.env.RUNTIME_AUTH_SECRET;
1234
+ const projectId = process.env.PROJECT_ID;
1235
+ if (!runtimeToken || !projectId) return null;
1236
+ return {
1237
+ runtimeToken,
1238
+ projectId,
1239
+ // Deliberately not required here: see `resolveApiBase`. Throwing at
1240
+ // construction made every local-only handler (400 validation, 405s,
1241
+ // the static audio-tags catalog) unusable on a host with a token but
1242
+ // no URL — which is exactly CI's env.
1243
+ apiUrl: envApiUrl() ?? "",
1244
+ ...config.fetch ? { fetch: config.fetch } : {}
1245
+ };
1246
+ };
715
1247
  if (config.proxy) {
716
1248
  if (!config.proxy.runtimeToken || !config.proxy.projectId || !config.proxy.apiUrl) {
717
1249
  throw new Error(
718
1250
  "createVoiceHandlers: proxy requires runtimeToken, projectId, and apiUrl"
719
1251
  );
720
1252
  }
1253
+ if (config.apiKey) LOG_WARN_CACHE.apiKeyIgnored(config.logger);
721
1254
  return config.proxy;
722
1255
  }
723
- if (typeof process === "undefined" || !process.env) return null;
724
- const runtimeToken = process.env.RUNTIME_AUTH_SECRET;
725
- const projectId = process.env.PROJECT_ID;
726
- if (!runtimeToken || !projectId) return null;
727
- const apiUrl = process.env.SHOGO_API_URL ?? process.env.SHOGO_CLOUD_URL ?? "http://localhost:8002";
728
- return {
729
- runtimeToken,
730
- projectId,
731
- apiUrl,
732
- ...config.fetch ? { fetch: config.fetch } : {}
733
- };
1256
+ if (config.mode === "proxy") return envProxy();
1257
+ if (config.apiKey) return null;
1258
+ return envProxy();
1259
+ }
1260
+ var LOG_WARN_CACHE = {
1261
+ warned: false,
1262
+ apiKeyIgnored(logger) {
1263
+ if (LOG_WARN_CACHE.warned) return;
1264
+ LOG_WARN_CACHE.warned = true;
1265
+ (logger ?? NOOP_LOGGER)(
1266
+ "warn",
1267
+ 'createVoiceHandlers: apiKey provided but runtime-token proxy mode is active; apiKey is ignored (pass mode: "byo" to use it)'
1268
+ );
1269
+ }
1270
+ };
1271
+ function resolveOpId(req, opId) {
1272
+ if (opId) return opId;
1273
+ try {
1274
+ const url = new URL(req.url);
1275
+ const fromQuery = url.searchParams.get("op");
1276
+ if (fromQuery) return fromQuery;
1277
+ const segments = url.pathname.split("/").filter(Boolean);
1278
+ const last = segments[segments.length - 1];
1279
+ if (last && segments[segments.length - 2] === "op") return last;
1280
+ return void 0;
1281
+ } catch {
1282
+ return void 0;
1283
+ }
1284
+ }
1285
+ async function readVoiceOpBody(op, req) {
1286
+ if (op.method === "GET") return { kind: "none" };
1287
+ if (op.transport === "multipart-binary" || op.transport === "multipart-json") {
1288
+ let form;
1289
+ try {
1290
+ form = await req.formData();
1291
+ } catch {
1292
+ return json({ error: "Invalid multipart body", detail: "send a multipart/form-data body" }, 400);
1293
+ }
1294
+ const parsed2 = parseVoiceOpForm(op, form);
1295
+ if (!parsed2.ok) {
1296
+ return json(
1297
+ {
1298
+ error: parsed2.error,
1299
+ ...parsed2.detail ? { detail: parsed2.detail } : {},
1300
+ ...parsed2.allowed ? { allowed: parsed2.allowed } : {}
1301
+ },
1302
+ parsed2.status
1303
+ );
1304
+ }
1305
+ return { kind: "form", form: parsed2.form, fields: parsed2.fields };
1306
+ }
1307
+ const raw = await readJson(req);
1308
+ const parsed = parseVoiceOpJsonBody(op, raw);
1309
+ if (!parsed.ok) {
1310
+ return json(
1311
+ {
1312
+ error: parsed.error,
1313
+ ...parsed.detail ? { detail: parsed.detail } : {},
1314
+ ...parsed.allowed ? { allowed: parsed.allowed } : {}
1315
+ },
1316
+ parsed.status
1317
+ );
1318
+ }
1319
+ return { kind: "json", fields: parsed.fields };
734
1320
  }
735
1321
  function createProxyHandlers(proxy, log) {
736
1322
  const fetchImpl = proxy.fetch ?? globalThis.fetch;
@@ -739,8 +1325,12 @@ function createProxyHandlers(proxy, log) {
739
1325
  "createVoiceHandlers proxy: global fetch is unavailable; pass proxy.fetch"
740
1326
  );
741
1327
  }
742
- const apiBase = proxy.apiUrl.replace(/\/+$/, "");
743
- function proxyUrl(path, forward) {
1328
+ function resolveApiBase() {
1329
+ const raw = proxy.apiUrl || envApiUrl();
1330
+ if (!raw) throw new Error(MISSING_API_HOST_MESSAGE);
1331
+ return raw.replace(/\/+$/, "");
1332
+ }
1333
+ function proxyUrl(base, path, forward) {
744
1334
  const tail = [`projectId=${encodeURIComponent(proxy.projectId)}`];
745
1335
  for (const [k, v] of Object.entries(forward)) {
746
1336
  if (typeof v === "string" && v.length > 0) {
@@ -748,11 +1338,12 @@ function createProxyHandlers(proxy, log) {
748
1338
  }
749
1339
  }
750
1340
  const sep = path.includes("?") ? "&" : "?";
751
- return `${apiBase}${path}${sep}${tail.join("&")}`;
1341
+ return `${base}${path}${sep}${tail.join("&")}`;
752
1342
  }
753
1343
  const FORWARDED_SIGNED_URL_PARAMS = ["agentName"];
754
1344
  async function doSignedUrl(req) {
755
1345
  if (req.method !== "GET") return json({ error: "Method Not Allowed" }, 405);
1346
+ const base = resolveApiBase();
756
1347
  try {
757
1348
  let incomingUrl = null;
758
1349
  try {
@@ -766,7 +1357,7 @@ function createProxyHandlers(proxy, log) {
766
1357
  if (v != null) forward[key] = v;
767
1358
  }
768
1359
  }
769
- const upstream = await fetchImpl(proxyUrl("/api/voice/signed-url", forward), {
1360
+ const upstream = await fetchImpl(proxyUrl(base, "/api/voice/signed-url", forward), {
770
1361
  method: "GET",
771
1362
  headers: { "x-runtime-token": proxy.runtimeToken },
772
1363
  credentials: "omit"
@@ -796,34 +1387,80 @@ function createProxyHandlers(proxy, log) {
796
1387
  }
797
1388
  });
798
1389
  }
799
- async function doMusic(req) {
800
- if (req.method !== "POST") return json({ error: "Method Not Allowed" }, 405);
801
- const raw = await readJson(req);
802
- const parsed = parseMusicBody(raw);
803
- if ("error" in parsed) return json({ error: parsed.error }, 400);
1390
+ async function doOp(req, opId) {
1391
+ const id = resolveOpId(req, opId);
1392
+ const op = getVoiceOp(id);
1393
+ if (!op) {
1394
+ return json(
1395
+ { error: "unknown_op", detail: `Unknown voice op '${id ?? ""}'`, allowed: VOICE_OP_IDS },
1396
+ 404
1397
+ );
1398
+ }
1399
+ if (req.method !== op.method) return json({ error: "Method Not Allowed" }, 405);
1400
+ const parsed = await readVoiceOpBody(op, req);
1401
+ if (parsed instanceof Response) return parsed;
1402
+ const base = resolveApiBase();
1403
+ const forward = {};
1404
+ let incomingUrl = null;
804
1405
  try {
805
- const upstream = await fetchImpl(proxyUrl("/api/voice/music", {}), {
806
- method: "POST",
807
- headers: {
808
- "x-runtime-token": proxy.runtimeToken,
809
- "content-type": "application/json",
810
- accept: "audio/mpeg"
811
- },
812
- body: JSON.stringify(parsed.params),
1406
+ incomingUrl = new URL(req.url);
1407
+ } catch {
1408
+ }
1409
+ if (incomingUrl) {
1410
+ for (const key of [...op.pathParams ?? [], ...op.queryForward ?? []]) {
1411
+ const value = incomingUrl.searchParams.get(key);
1412
+ if (value != null) forward[key] = value;
1413
+ }
1414
+ }
1415
+ if (parsed.kind === "form") {
1416
+ for (const name of op.pathParams ?? []) {
1417
+ const value = parsed.fields[name];
1418
+ if (typeof value === "string" && value.length > 0) forward[name] = value;
1419
+ }
1420
+ }
1421
+ const hostedPath = `/api${voiceOpForwardPath(op)}`;
1422
+ const headers = { "x-runtime-token": proxy.runtimeToken };
1423
+ let body;
1424
+ if (parsed.kind === "json") {
1425
+ headers["content-type"] = "application/json";
1426
+ body = JSON.stringify(parsed.fields);
1427
+ } else if (parsed.kind === "form") {
1428
+ body = parsed.form;
1429
+ }
1430
+ if (op.accept) headers.accept = op.accept;
1431
+ try {
1432
+ const upstream = await fetchImpl(proxyUrl(base, hostedPath, forward), {
1433
+ method: op.method,
1434
+ headers,
1435
+ ...body !== void 0 ? { body } : {},
813
1436
  credentials: "omit"
814
1437
  });
1438
+ if (upstream.status === 404) {
1439
+ return json(
1440
+ {
1441
+ error: "Not Implemented",
1442
+ detail: `this Shogo API has no voice routes (desktop without ELEVENLABS_API_KEY?) \u2014 ${hostedPath} returned 404 upstream`
1443
+ },
1444
+ 501
1445
+ );
1446
+ }
815
1447
  const buf = await upstream.arrayBuffer();
816
- const headers = {};
1448
+ const responseHeaders = {};
817
1449
  const ct = upstream.headers.get("content-type");
818
- if (ct) headers["content-type"] = ct;
819
- return new Response(buf, { status: upstream.status, headers });
1450
+ if (ct) responseHeaders["content-type"] = ct;
1451
+ for (const name of op.responseHeaders ?? []) {
1452
+ const value = upstream.headers.get(name);
1453
+ if (value) responseHeaders[name] = value;
1454
+ }
1455
+ return new Response(buf, { status: upstream.status, headers: responseHeaders });
820
1456
  } catch (err) {
821
- log("error", "proxy music failed", {
1457
+ log("error", `proxy ${op.id} failed`, {
822
1458
  error: err instanceof Error ? err.message : String(err)
823
1459
  });
824
- return json({ error: "music proxy failed" }, 502);
1460
+ return json({ error: `${op.id} proxy failed` }, 502);
825
1461
  }
826
1462
  }
1463
+ const doMusic = (req) => doOp(req, "music");
827
1464
  function notImplemented(label) {
828
1465
  return async () => json(
829
1466
  {
@@ -833,9 +1470,204 @@ function createProxyHandlers(proxy, log) {
833
1470
  501
834
1471
  );
835
1472
  }
1473
+ async function doTts(req) {
1474
+ if (req.method === "POST") {
1475
+ let raw = null;
1476
+ try {
1477
+ const parsed = await req.clone().json();
1478
+ if (parsed && typeof parsed === "object" && !Array.isArray(parsed)) {
1479
+ raw = parsed;
1480
+ }
1481
+ } catch {
1482
+ }
1483
+ if (raw && (typeof raw.text !== "string" || raw.text.trim().length === 0)) {
1484
+ const sentTags = Array.isArray(raw.audioTags) && raw.audioTags.length > 0;
1485
+ if (sentTags) {
1486
+ const tags = normalizeAudioTags(raw.audioTags) ?? [];
1487
+ const characterName = typeof raw.characterName === "string" ? raw.characterName : void 0;
1488
+ const text = buildPreviewLine(tags, characterName ?? "your companion");
1489
+ return doOp(
1490
+ new Request(req.url, {
1491
+ method: "POST",
1492
+ headers: { "content-type": "application/json" },
1493
+ body: JSON.stringify({ ...raw, text })
1494
+ }),
1495
+ "text-to-speech"
1496
+ );
1497
+ }
1498
+ }
1499
+ }
1500
+ return doOp(req, "text-to-speech");
1501
+ }
1502
+ function createProxyElevenLabs() {
1503
+ const unsupported = (prop) => {
1504
+ throw new Error(
1505
+ `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`
1506
+ );
1507
+ };
1508
+ const textToSpeech = async (params) => {
1509
+ const upstream = await fetchImpl(proxyUrl(resolveApiBase(), "/api/voice/tts", {}), {
1510
+ method: "POST",
1511
+ headers: {
1512
+ "x-runtime-token": proxy.runtimeToken,
1513
+ "content-type": "application/json",
1514
+ accept: params.accept ?? "audio/mpeg"
1515
+ },
1516
+ body: JSON.stringify({
1517
+ text: params.text,
1518
+ voiceId: params.voiceId,
1519
+ ...params.modelId ? { modelId: params.modelId } : {},
1520
+ ...params.voiceSettings ? { voiceSettings: params.voiceSettings } : {}
1521
+ }),
1522
+ credentials: "omit"
1523
+ });
1524
+ if (upstream.status === 404) {
1525
+ throw new Error(
1526
+ "this Shogo API has no voice routes (desktop without ELEVENLABS_API_KEY?) \u2014 /api/voice/tts returned 404 upstream"
1527
+ );
1528
+ }
1529
+ if (!upstream.ok) {
1530
+ throw new ElevenLabsApiError(
1531
+ `textToSpeech failed: ${upstream.status}`,
1532
+ upstream.status,
1533
+ await upstream.text()
1534
+ );
1535
+ }
1536
+ const requestedModel = params.modelId ?? DEFAULT_TTS_MODEL;
1537
+ const usedModel = upstream.headers.get("x-tts-model-used") ?? requestedModel;
1538
+ const requestedHeader = upstream.headers.get("x-tts-model-requested") ?? requestedModel;
1539
+ return {
1540
+ audio: await upstream.arrayBuffer(),
1541
+ modelId: usedModel,
1542
+ requestedModel: requestedHeader,
1543
+ fellBack: usedModel !== requestedHeader,
1544
+ contentType: upstream.headers.get("content-type") ?? params.accept ?? "audio/mpeg"
1545
+ };
1546
+ };
1547
+ const composeMusic = async (params) => {
1548
+ const upstream = await fetchImpl(proxyUrl(resolveApiBase(), "/api/voice/music", {}), {
1549
+ method: "POST",
1550
+ headers: {
1551
+ "x-runtime-token": proxy.runtimeToken,
1552
+ "content-type": "application/json",
1553
+ accept: "audio/mpeg"
1554
+ },
1555
+ body: JSON.stringify(params),
1556
+ credentials: "omit"
1557
+ });
1558
+ if (upstream.status === 404) {
1559
+ throw new Error(
1560
+ "this Shogo API has no voice routes (desktop without ELEVENLABS_API_KEY?) \u2014 /api/voice/music returned 404 upstream"
1561
+ );
1562
+ }
1563
+ if (!upstream.ok) {
1564
+ throw new ElevenLabsApiError(
1565
+ `composeMusic failed: ${upstream.status}`,
1566
+ upstream.status,
1567
+ await upstream.text()
1568
+ );
1569
+ }
1570
+ return {
1571
+ audio: await upstream.arrayBuffer(),
1572
+ contentType: upstream.headers.get("content-type") ?? "audio/mpeg"
1573
+ };
1574
+ };
1575
+ const opResponse = async (opId, req) => {
1576
+ const op = getVoiceOp(opId);
1577
+ const res = await doOp(req, opId);
1578
+ if (res.status === 404) {
1579
+ throw new Error(
1580
+ `this Shogo API has no voice routes (desktop without ELEVENLABS_API_KEY?) \u2014 /api${voiceOpForwardPath(op)} returned 404 upstream`
1581
+ );
1582
+ }
1583
+ if (!res.ok) {
1584
+ throw new ElevenLabsApiError(
1585
+ `${opId} failed: ${res.status}`,
1586
+ res.status,
1587
+ await res.text()
1588
+ );
1589
+ }
1590
+ return res;
1591
+ };
1592
+ const opAudio = async (opId, req) => {
1593
+ const res = await opResponse(opId, req);
1594
+ return {
1595
+ audio: await res.arrayBuffer(),
1596
+ contentType: res.headers.get("content-type") ?? "audio/mpeg"
1597
+ };
1598
+ };
1599
+ const speechToSpeech = (params) => {
1600
+ const form = new FormData();
1601
+ form.set("audio", params.audio, params.fileName ?? "audio");
1602
+ if (params.modelId) form.set("modelId", params.modelId);
1603
+ if (params.voiceSettings) form.set("voiceSettings", JSON.stringify(params.voiceSettings));
1604
+ if (params.outputFormat) form.set("outputFormat", params.outputFormat);
1605
+ if (params.fileFormat) form.set("fileFormat", params.fileFormat);
1606
+ if (params.seed !== void 0) form.set("seed", String(params.seed));
1607
+ if (params.removeBackgroundNoise !== void 0) {
1608
+ form.set("removeBackgroundNoise", String(params.removeBackgroundNoise));
1609
+ }
1610
+ const query = `?voiceId=${encodeURIComponent(params.voiceId)}`;
1611
+ return opAudio(
1612
+ "speech-to-speech",
1613
+ new Request(`http://voice.invalid/voice/op/speech-to-speech${query}`, {
1614
+ method: "POST",
1615
+ body: form
1616
+ })
1617
+ );
1618
+ };
1619
+ const soundEffects = (params) => opAudio(
1620
+ "sound-generation",
1621
+ new Request(
1622
+ // `output_format` is a query param on this endpoint (see the row's
1623
+ // `queryForward`); sending it in the body would be dropped at EL.
1624
+ `http://voice.invalid/voice/op/sound-generation${params.outputFormat ? `?output_format=${encodeURIComponent(params.outputFormat)}` : ""}`,
1625
+ {
1626
+ method: "POST",
1627
+ headers: { "content-type": "application/json" },
1628
+ body: JSON.stringify({
1629
+ text: params.text,
1630
+ ...params.durationSeconds !== void 0 ? { durationSeconds: params.durationSeconds } : {},
1631
+ ...params.promptInfluence !== void 0 ? { promptInfluence: params.promptInfluence } : {},
1632
+ ...params.loop !== void 0 ? { loop: params.loop } : {},
1633
+ ...params.modelId ? { modelId: params.modelId } : {}
1634
+ })
1635
+ }
1636
+ )
1637
+ );
1638
+ const transcribe = async (params) => {
1639
+ const form = new FormData();
1640
+ form.set("file", params.file, params.fileName ?? "audio");
1641
+ if (params.modelId) form.set("modelId", params.modelId);
1642
+ if (params.languageCode) form.set("languageCode", params.languageCode);
1643
+ if (params.diarize !== void 0) form.set("diarize", String(params.diarize));
1644
+ if (params.tagAudioEvents !== void 0) {
1645
+ form.set("tagAudioEvents", String(params.tagAudioEvents));
1646
+ }
1647
+ if (params.numSpeakers !== void 0) form.set("numSpeakers", String(params.numSpeakers));
1648
+ const res = await opResponse(
1649
+ "speech-to-text",
1650
+ new Request("http://voice.invalid/voice/op/speech-to-text", {
1651
+ method: "POST",
1652
+ body: form
1653
+ })
1654
+ );
1655
+ return await res.json();
1656
+ };
1657
+ return new Proxy({}, {
1658
+ get(_t, prop) {
1659
+ if (prop === "textToSpeech") return textToSpeech;
1660
+ if (prop === "composeMusic") return composeMusic;
1661
+ if (prop === "speechToSpeech") return speechToSpeech;
1662
+ if (prop === "soundEffects") return soundEffects;
1663
+ if (prop === "transcribe") return transcribe;
1664
+ return unsupported(String(prop));
1665
+ }
1666
+ });
1667
+ }
836
1668
  return {
837
1669
  signedUrl: doSignedUrl,
838
- tts: notImplemented("tts"),
1670
+ tts: doTts,
839
1671
  music: doMusic,
840
1672
  agent: {
841
1673
  create: notImplemented("agent.create"),
@@ -843,30 +1675,23 @@ function createProxyHandlers(proxy, log) {
843
1675
  delete: notImplemented("agent.delete")
844
1676
  },
845
1677
  audioTags: doAudioTags,
846
- // In proxy mode we don't own an EL client. Expose a throwing stub so
847
- // accidental use is loud instead of silently passing around a
848
- // half-configured client.
849
- elevenLabs: new Proxy({}, {
850
- get(_t, prop) {
851
- throw new Error(
852
- `createVoiceHandlers: elevenLabs.${String(prop)} is not available in runtime-token proxy mode`
853
- );
854
- }
855
- })
1678
+ op: doOp,
1679
+ // In proxy mode we don't own an EL client: media calls go through the
1680
+ // Shogo API, anything else is a loud error.
1681
+ elevenLabs: createProxyElevenLabs()
856
1682
  };
857
1683
  }
858
1684
  function createVoiceHandlers(config) {
859
1685
  const log = config.logger ?? NOOP_LOGGER;
860
1686
  const proxy = resolveProxyOptions(config);
861
1687
  if (proxy) {
862
- if (config.apiKey) {
863
- log("warn", "createVoiceHandlers: apiKey provided but runtime-token proxy mode is active; apiKey is ignored");
864
- }
865
1688
  return createProxyHandlers(proxy, log);
866
1689
  }
867
- if (!config.apiKey) throw new Error("createVoiceHandlers: apiKey is required");
868
- if (!config.getUser) throw new Error("createVoiceHandlers: getUser is required");
869
- if (!config.companionStore) throw new Error("createVoiceHandlers: companionStore is required");
1690
+ if (!config.apiKey) {
1691
+ throw new Error(
1692
+ 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)"
1693
+ );
1694
+ }
870
1695
  const getUser = config.getUser;
871
1696
  const companionStore = config.companionStore;
872
1697
  const includeMemoryTools = config.includeMemoryTools ?? true;
@@ -878,10 +1703,28 @@ function createVoiceHandlers(config) {
878
1703
  };
879
1704
  const el = new ElevenLabsClient(elConfig);
880
1705
  async function resolveUser(req) {
1706
+ if (!getUser) {
1707
+ return json(
1708
+ {
1709
+ error: "Voice handler misconfigured",
1710
+ detail: "signedUrl / agent.* need getUser (and companionStore); tts and music do not."
1711
+ },
1712
+ 500
1713
+ );
1714
+ }
881
1715
  const u = await getUser(req);
882
1716
  if (!u) return json({ error: "Unauthorized" }, 401);
883
1717
  return u;
884
1718
  }
1719
+ function missingCompanionStore() {
1720
+ return json(
1721
+ {
1722
+ error: "Voice handler misconfigured",
1723
+ detail: "companionStore is required for signedUrl / agent.*; tts and music do not need it."
1724
+ },
1725
+ 500
1726
+ );
1727
+ }
885
1728
  function handleElError(e, fallbackLabel) {
886
1729
  if (e instanceof ElevenLabsApiError) {
887
1730
  log("warn", `${fallbackLabel}: 11Labs ${e.status}`, { body: e.body });
@@ -895,6 +1738,7 @@ function createVoiceHandlers(config) {
895
1738
  if (req.method !== "GET") return json({ error: "Method Not Allowed" }, 405);
896
1739
  const u = await resolveUser(req);
897
1740
  if (u instanceof Response) return u;
1741
+ if (!companionStore) return missingCompanionStore();
898
1742
  const companion = await companionStore.findByUserId(u.id);
899
1743
  if (!companion || !companion.agentId) return json({ error: "No companion" }, 404);
900
1744
  const basePrompt = extractBasePrompt(companion.systemPrompt || "");
@@ -944,8 +1788,10 @@ function createVoiceHandlers(config) {
944
1788
  }
945
1789
  async function doTts(req) {
946
1790
  if (req.method !== "POST") return json({ error: "Method Not Allowed" }, 405);
947
- const u = await resolveUser(req);
948
- if (u instanceof Response) return u;
1791
+ if (getUser) {
1792
+ const u = await resolveUser(req);
1793
+ if (u instanceof Response) return u;
1794
+ }
949
1795
  const raw = await readJson(req);
950
1796
  if (raw === null || typeof raw !== "object") return json({ error: "Invalid JSON body" }, 400);
951
1797
  const body = raw;
@@ -960,27 +1806,37 @@ function createVoiceHandlers(config) {
960
1806
  text = buildPreviewLine(tags, body.characterName ?? "your companion").slice(0, 400);
961
1807
  }
962
1808
  try {
963
- const { audio, modelId, contentType } = await el.textToSpeech({
1809
+ const result = await el.textToSpeech({
964
1810
  voiceId,
965
1811
  text,
966
1812
  ...body.modelId ? { modelId: body.modelId } : {},
967
1813
  voiceSettings
968
1814
  });
969
- return new Response(audio, {
970
- headers: {
971
- "content-type": contentType,
972
- "cache-control": "private, max-age=3600",
973
- "x-tts-model-used": modelId
974
- }
975
- });
1815
+ const headers = {
1816
+ "content-type": result.contentType,
1817
+ "cache-control": "private, max-age=3600",
1818
+ "x-tts-model-used": result.modelId,
1819
+ "x-tts-model-requested": result.requestedModel
1820
+ };
1821
+ if (result.fellBack) {
1822
+ headers.warning = `199 - "model ${result.requestedModel} not available, used ${result.modelId}"`;
1823
+ log("warn", "tts fell back to another model", {
1824
+ requested: result.requestedModel,
1825
+ used: result.modelId,
1826
+ reason: result.fallbackReason
1827
+ });
1828
+ }
1829
+ return new Response(result.audio, { headers });
976
1830
  } catch (e) {
977
1831
  return handleElError(e, "TTS failed");
978
1832
  }
979
1833
  }
980
1834
  async function doMusic(req) {
981
1835
  if (req.method !== "POST") return json({ error: "Method Not Allowed" }, 405);
982
- const u = await resolveUser(req);
983
- if (u instanceof Response) return u;
1836
+ if (getUser) {
1837
+ const u = await resolveUser(req);
1838
+ if (u instanceof Response) return u;
1839
+ }
984
1840
  const raw = await readJson(req);
985
1841
  const parsed = parseMusicBody(raw);
986
1842
  if ("error" in parsed) return json({ error: parsed.error }, 400);
@@ -996,10 +1852,104 @@ function createVoiceHandlers(config) {
996
1852
  return handleElError(e, "Music generation failed");
997
1853
  }
998
1854
  }
1855
+ async function doOp(req, opId) {
1856
+ const id = resolveOpId(req, opId);
1857
+ const op = getVoiceOp(id);
1858
+ if (!op) {
1859
+ return json(
1860
+ { error: "unknown_op", detail: `Unknown voice op '${id ?? ""}'`, allowed: VOICE_OP_IDS },
1861
+ 404
1862
+ );
1863
+ }
1864
+ if (req.method !== op.method) return json({ error: "Method Not Allowed" }, 405);
1865
+ const parsed = await readVoiceOpBody(op, req);
1866
+ if (parsed instanceof Response) return parsed;
1867
+ const fields = parsed.kind === "none" ? {} : parsed.fields;
1868
+ let query;
1869
+ try {
1870
+ query = new URL(req.url).searchParams;
1871
+ } catch {
1872
+ query = new URLSearchParams();
1873
+ }
1874
+ const pathParams = voiceOpPathParams(op, fields, query);
1875
+ const upstream = voiceOpUpstreamPath(op, pathParams);
1876
+ if (typeof upstream !== "string") {
1877
+ return json({ error: upstream.error, detail: `set it in the body or as ?${op.pathParams?.[0]}=` }, 400);
1878
+ }
1879
+ const forwardedQuery = {};
1880
+ for (const key of op.queryForward ?? []) {
1881
+ const value = query.get(key);
1882
+ if (value) forwardedQuery[key] = value;
1883
+ }
1884
+ if (op.defaultVoiceId && !pathParams.voiceId) {
1885
+ return json(
1886
+ {
1887
+ error: "Missing `voiceId`",
1888
+ detail: `BYO mode has no project default voice \u2014 pass voiceId (or ?voiceId=)`
1889
+ },
1890
+ 400
1891
+ );
1892
+ }
1893
+ try {
1894
+ if (op.call === "textToSpeech") {
1895
+ const result = await el.textToSpeech({
1896
+ voiceId: pathParams.voiceId ?? String(fields.voiceId ?? ""),
1897
+ text: String(fields.text ?? ""),
1898
+ ...typeof fields.modelId === "string" ? { modelId: fields.modelId } : {},
1899
+ ...fields.voiceSettings ? { voiceSettings: fields.voiceSettings } : {},
1900
+ ...op.accept ? { accept: op.accept } : {}
1901
+ });
1902
+ const headers2 = {
1903
+ "content-type": result.contentType,
1904
+ "cache-control": "private, max-age=3600",
1905
+ "x-tts-model-used": result.modelId,
1906
+ "x-tts-model-requested": result.requestedModel
1907
+ };
1908
+ if (result.fellBack) {
1909
+ headers2.warning = `199 - "model ${result.requestedModel} not available, used ${result.modelId}"`;
1910
+ }
1911
+ return new Response(result.audio, { headers: headers2 });
1912
+ }
1913
+ if (op.call === "composeMusic") {
1914
+ const { audio, contentType } = await el.composeMusic({
1915
+ ...typeof fields.prompt === "string" ? { prompt: fields.prompt } : {},
1916
+ ...fields.compositionPlan ? { compositionPlan: fields.compositionPlan } : {},
1917
+ ...typeof fields.musicLengthMs === "number" ? { musicLengthMs: fields.musicLengthMs } : {},
1918
+ ...typeof fields.modelId === "string" ? { modelId: fields.modelId } : {},
1919
+ ...typeof fields.forceInstrumental === "boolean" ? { forceInstrumental: fields.forceInstrumental } : {},
1920
+ ...typeof fields.outputFormat === "string" ? { outputFormat: fields.outputFormat } : {}
1921
+ });
1922
+ return new Response(audio, {
1923
+ headers: {
1924
+ "content-type": contentType,
1925
+ "cache-control": "private, max-age=3600"
1926
+ }
1927
+ });
1928
+ }
1929
+ const upstreamBody = voiceOpUpstreamBody(op, fields);
1930
+ if (op.defaultModel && upstreamBody.model_id === void 0) {
1931
+ upstreamBody.model_id = op.defaultModel;
1932
+ }
1933
+ const response = await el.request({
1934
+ method: op.method,
1935
+ path: upstream,
1936
+ ...parsed.kind === "form" ? { body: parsed.form } : parsed.kind === "json" ? { body: upstreamBody } : {},
1937
+ ...Object.keys(forwardedQuery).length ? { query: forwardedQuery } : {},
1938
+ ...op.accept ? { accept: op.accept } : {}
1939
+ });
1940
+ const headers = { "content-type": response.contentType };
1941
+ if (voiceOpReturnsAudio(op)) headers["cache-control"] = "private, max-age=3600";
1942
+ const body = response.audio ?? JSON.stringify(response.json ?? {});
1943
+ return new Response(body, { status: response.status, headers });
1944
+ } catch (e) {
1945
+ return handleElError(e, `${op.id} failed`);
1946
+ }
1947
+ }
999
1948
  async function doAgentCreate(req) {
1000
1949
  if (req.method !== "POST") return json({ error: "Method Not Allowed" }, 405);
1001
1950
  const u = await resolveUser(req);
1002
1951
  if (u instanceof Response) return u;
1952
+ if (!companionStore) return missingCompanionStore();
1003
1953
  const existing = await companionStore.findByUserId(u.id);
1004
1954
  if (existing) return json({ error: "Companion already exists" }, 409);
1005
1955
  const raw = await readJson(req);
@@ -1050,6 +2000,7 @@ function createVoiceHandlers(config) {
1050
2000
  if (req.method !== "PATCH") return json({ error: "Method Not Allowed" }, 405);
1051
2001
  const u = await resolveUser(req);
1052
2002
  if (u instanceof Response) return u;
2003
+ if (!companionStore) return missingCompanionStore();
1053
2004
  const existing = await companionStore.findByUserId(u.id);
1054
2005
  if (!existing) return json({ error: "No companion" }, 404);
1055
2006
  const raw = await readJson(req);
@@ -1104,6 +2055,7 @@ function createVoiceHandlers(config) {
1104
2055
  if (req.method !== "DELETE") return json({ error: "Method Not Allowed" }, 405);
1105
2056
  const u = await resolveUser(req);
1106
2057
  if (u instanceof Response) return u;
2058
+ if (!companionStore) return missingCompanionStore();
1107
2059
  const existing = await companionStore.findByUserId(u.id);
1108
2060
  if (!existing) return json({ ok: true });
1109
2061
  if (existing.agentId) await el.deleteAgent(existing.agentId);
@@ -1133,6 +2085,7 @@ function createVoiceHandlers(config) {
1133
2085
  delete: doAgentDelete
1134
2086
  },
1135
2087
  audioTags: doAudioTags,
2088
+ op: doOp,
1136
2089
  elevenLabs: el
1137
2090
  };
1138
2091
  }