agentvibes 5.13.1 → 5.15.0

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 (84) hide show
  1. package/.claude/audio/ui/CREDITS.txt +16 -16
  2. package/.claude/commands/agent-vibes-bmad-voices.md +117 -117
  3. package/.claude/commands/agent-vibes-rdp.md +24 -24
  4. package/.claude/config/audio-effects.cfg.sample +52 -52
  5. package/.claude/docs/TERMUX_SETUP.md +408 -408
  6. package/.claude/github-star-reminder.txt +1 -1
  7. package/.claude/hooks/kokoro-server.py +219 -219
  8. package/.claude/hooks/kokoro-tts.py +141 -141
  9. package/.claude/hooks/party-stage-roster.py +328 -328
  10. package/.claude/hooks/play-tts-kokoro.sh +7 -2
  11. package/.claude/hooks/play-tts-ssh-remote.sh +38 -3
  12. package/.claude/hooks/requirements.txt +6 -6
  13. package/.claude/hooks/soprano-gradio-synth.py +139 -139
  14. package/.claude/hooks/translator.py +237 -237
  15. package/.claude/hooks-windows/agentvibes-session-id.ps1 +83 -0
  16. package/.claude/hooks-windows/kokoro-server.py +219 -219
  17. package/.claude/hooks-windows/kokoro-tts.py +107 -107
  18. package/.claude/hooks-windows/play-tts.ps1 +112 -1
  19. package/.claude/hooks-windows/session-start-tts.ps1 +36 -0
  20. package/.claude/hooks-windows/soprano-gradio-synth.py +153 -153
  21. package/.claude/verbosity.txt +1 -1
  22. package/.clawdbot/README.md +105 -105
  23. package/CLAUDE.md +84 -176
  24. package/README.md +35 -2
  25. package/RELEASE_NOTES.md +139 -0
  26. package/WINDOWS-SETUP.md +208 -208
  27. package/bin/agent-vibes +39 -39
  28. package/bin/mcp-server.js +121 -121
  29. package/bin/test-bmad-pr +78 -78
  30. package/mcp-server/QUICK_START.md +203 -203
  31. package/mcp-server/README.md +345 -345
  32. package/mcp-server/examples/claude_desktop_config.json +11 -11
  33. package/mcp-server/examples/claude_desktop_config_piper.json +9 -9
  34. package/mcp-server/examples/custom_instructions.md +169 -169
  35. package/mcp-server/install-deps.js +12 -2
  36. package/mcp-server/server.py +2111 -2085
  37. package/mcp-server/test_mcp_correctness.py +504 -504
  38. package/mcp-server/test_windows_script_parity.py +339 -339
  39. package/package.json +6 -3
  40. package/setup-ssh-receiver.ps1 +259 -0
  41. package/setup-windows.ps1 +39 -29
  42. package/src/cli/list-personalities.js +110 -110
  43. package/src/commands/bmad-voices.js +394 -394
  44. package/src/console/brand-colors.js +13 -13
  45. package/src/console/constants/personalities.js +44 -44
  46. package/src/console/tabs/agents-tab.js +14 -4
  47. package/src/console/tabs/help-tab.js +314 -314
  48. package/src/console/tabs/readme-tab.js +272 -272
  49. package/src/console/tabs/settings-tab.js +31 -6
  50. package/src/console/tabs/setup-tab.js +154 -32
  51. package/src/console/tabs/voices-tab.js +48 -6
  52. package/src/console/widgets/destroy-list.js +25 -25
  53. package/src/console/widgets/notice.js +55 -55
  54. package/src/installer/language-screen.js +31 -31
  55. package/src/installer/music-file-input.js +304 -304
  56. package/src/installer.js +98 -37
  57. package/src/services/language-service.js +47 -47
  58. package/src/services/llm-provider-service.js +4 -1
  59. package/src/services/provider-voice-catalog.js +9 -5
  60. package/src/utils/audio-format-validator.js +277 -277
  61. package/src/utils/dependency-checker.js +469 -469
  62. package/src/utils/file-ownership-verifier.js +358 -358
  63. package/src/utils/music-file-validator.js +285 -285
  64. package/src/utils/preview-list-prompt.js +144 -144
  65. package/src/utils/secure-music-storage.js +412 -412
  66. package/templates/agentvibes-receiver.ps1 +311 -0
  67. package/templates/agentvibes-receiver.sh +297 -297
  68. package/voice-assignments.json +8244 -8244
  69. package/.agentvibes/config.json +0 -17
  70. package/.agentvibes/install-manifest.json +0 -362
  71. package/.claude/config/audio-effects.cfg +0 -7
  72. package/.claude/config/audio-effects.cfg.bak-kokoro +0 -7
  73. package/.claude/config/background-music-enabled.txt +0 -1
  74. package/.claude/config/background-music-position.txt +0 -27
  75. package/.claude/config/background-music-volume.txt +0 -1
  76. package/.claude/config/background-music.cfg +0 -1
  77. package/.claude/config/background-music.txt +0 -1
  78. package/.claude/config/language.txt +0 -1
  79. package/.claude/config/personality.txt +0 -1
  80. package/.claude/config/reverb-level.txt +0 -1
  81. package/.claude/config/tts-speech-rate.txt +0 -1
  82. package/.claude/config/tts-verbosity.txt +0 -1
  83. package/.claude/hooks-windows/audio-cache-utils.ps1.user.bak +0 -119
  84. package/.claude/hooks-windows/soprano-gradio-synth.py.user.bak +0 -153
@@ -73,7 +73,8 @@ $HooksDir = "$ClaudeDir\hooks-windows"
73
73
  $ProviderFile = "$ClaudeDir\tts-provider.txt"
74
74
  $MuteFile = "$ClaudeDir\tts-muted.txt"
75
75
 
76
- # Check if TTS is muted
76
+ # Check if TTS is muted (receiver master switch — /agent-vibes:receiver off).
77
+ # Kept as an absolute pre-check so existing behaviour does not regress.
77
78
  if (Test-Path $MuteFile) {
78
79
  $muteStatus = Get-Content $MuteFile -Raw
79
80
  if ($muteStatus.Trim() -eq "true") {
@@ -81,6 +82,35 @@ if (Test-Path $MuteFile) {
81
82
  }
82
83
  }
83
84
 
85
+ # ---------------------------------------------------------------------------
86
+ # MUTE PRECEDENCE (parity with .claude/hooks/play-tts.sh:89-114).
87
+ #
88
+ # Until now this player read ONLY tts-muted.txt above, which /agent-vibes:mute
89
+ # never writes — so `/agent-vibes:mute` did not silence Windows audio at all,
90
+ # and the global `~/.agentvibes-muted` kill-switch was ignored on Windows.
91
+ # Same three levels as bash, in the same order:
92
+ # 1. project agentvibes-unmuted -> speak (overrides a global mute)
93
+ # 2. project agentvibes-muted -> silent
94
+ # 3. global ~/.agentvibes-muted -> silent
95
+ #
96
+ # The project markers live under the REAL project root (CLAUDE_PROJECT_DIR when
97
+ # set), not $ClaudeDir, which falls back to the user profile for global installs.
98
+ # $HOME is preferred over $env:USERPROFILE so markers written by bash under
99
+ # git-bash resolve to the same file here.
100
+ $HomeDir = if ($env:HOME) { $env:HOME } else { $env:USERPROFILE }
101
+ $MuteScopeDir = if ($env:CLAUDE_PROJECT_DIR -and (Test-Path "$env:CLAUDE_PROJECT_DIR\.claude")) {
102
+ "$env:CLAUDE_PROJECT_DIR\.claude"
103
+ } else {
104
+ $ClaudeDir
105
+ }
106
+ if (Test-Path (Join-Path $MuteScopeDir "agentvibes-unmuted")) {
107
+ # explicit per-project enable — wins over the global kill-switch
108
+ } elseif (Test-Path (Join-Path $MuteScopeDir "agentvibes-muted")) {
109
+ exit 0
110
+ } elseif (Test-Path (Join-Path $HomeDir ".agentvibes-muted")) {
111
+ exit 0
112
+ }
113
+
84
114
  # Determine active provider
85
115
  $ActiveProvider = "windows-sapi"
86
116
  if (Test-Path $ProviderFile) {
@@ -453,6 +483,70 @@ elseif (-not $PlanOk -and $_LlmVoice -and -not $VoiceOverride) {
453
483
  $VoiceOverride = $_LlmVoice
454
484
  }
455
485
 
486
+ # --- Dynamic session self-ID ({{session}} token) ------------------------------
487
+ # Parity with play-tts.sh:250-296. A per-LLM PRETEXT containing {{session}}
488
+ # expands to "<LLM> on <Project> in <Terminal>" so multi-session users can tell
489
+ # which window just spoke. Announced ONCE per session; on later utterances the
490
+ # token is dropped rather than prefixing every line. Opt-in — this whole block
491
+ # is inert unless the configured pretext actually contains the token.
492
+ if ($_LlmPretext -like "*{{session}}*") {
493
+ # Session key. There is no true Claude-session id available to a hook, so
494
+ # this is best-effort: a terminal-session id when the emulator exports one
495
+ # (stable for that tab's life), else this process's parent PID. Worst case
496
+ # the self-ID repeats or is skipped — cosmetic, and only when opted in.
497
+ $_SidRaw = if ($env:WT_SESSION) { $env:WT_SESSION }
498
+ elseif ($env:TERM_SESSION_ID) { $env:TERM_SESSION_ID }
499
+ elseif ($env:TMUX) { $env:TMUX }
500
+ else {
501
+ try { (Get-CimInstance Win32_Process -Filter "ProcessId=$PID").ParentProcessId } catch { $PID }
502
+ }
503
+ $_SidProj = ""
504
+ $_SidProjDirRaw = if ($env:CLAUDE_PROJECT_DIR) { $env:CLAUDE_PROJECT_DIR } else { $ClaudeDir }
505
+ try { $_SidProj = Split-Path -Leaf ($_SidProjDirRaw.TrimEnd('\', '/')) } catch { }
506
+ $_SidKey = (("$llm|$_SidProj|$_SidRaw") -replace '[^A-Za-z0-9]', '_')
507
+
508
+ # Announce-marker dir under the per-user temp path (already user-scoped on
509
+ # Windows: %LOCALAPPDATA%\Temp), so no cross-user marker collisions.
510
+ $_AnnDir = Join-Path ([System.IO.Path]::GetTempPath()) "agentvibes-session"
511
+ $_AnnOk = $false
512
+ try { $null = New-Item -ItemType Directory -Path $_AnnDir -Force -ErrorAction Stop; $_AnnOk = $true } catch { }
513
+ $_AnnFile = Join-Path $_AnnDir "announced-$_SidKey"
514
+
515
+ # First utterance -> replacement is the self-ID; later utterances -> empty.
516
+ $_SessionId = ""
517
+ if ($_AnnOk -and (Test-Path $_AnnFile)) {
518
+ $_SessionId = ""
519
+ } else {
520
+ $_SidScript = Join-Path $HooksDir "agentvibes-session-id.ps1"
521
+ if (Test-Path $_SidScript) {
522
+ $_SidProjDir = if ($env:CLAUDE_PROJECT_DIR) { $env:CLAUDE_PROJECT_DIR } else { $ClaudeDir }
523
+ try { $_SessionId = & $_SidScript -LlmKey $llm -ProjectDir $_SidProjDir } catch { $_SessionId = "" }
524
+ }
525
+ if ($_AnnOk) {
526
+ try {
527
+ if (-not (Test-Path $_AnnFile)) { $null = New-Item -ItemType File -Path $_AnnFile -ErrorAction Stop }
528
+ # Bound growth: drop announce-markers older than a day.
529
+ Get-ChildItem -Path $_AnnDir -Filter 'announced-*' -ErrorAction SilentlyContinue |
530
+ Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-1) } |
531
+ Remove-Item -Force -ErrorAction SilentlyContinue
532
+ } catch { }
533
+ }
534
+ }
535
+
536
+ if ($_SessionId) {
537
+ $_LlmPretext = $_LlmPretext -replace [regex]::Escape('{{session}}'), $_SessionId
538
+ } else {
539
+ # Empty replacement: also swallow one adjacent ", " so "Hey {{session}}, ready"
540
+ # becomes "Hey ready", not "Hey , ready"; then drop any bare token.
541
+ $_LlmPretext = $_LlmPretext -replace [regex]::Escape('{{session}}, '), ''
542
+ $_LlmPretext = $_LlmPretext -replace [regex]::Escape(', {{session}}'), ''
543
+ $_LlmPretext = $_LlmPretext -replace [regex]::Escape('{{session}}'), ''
544
+ }
545
+ # Final tidy: collapse doubled/edge commas and runs of whitespace.
546
+ $_LlmPretext = $_LlmPretext -replace ',\s*,', ',' -replace '^\s*,\s*', '' -replace '\s*,\s*$', '' -replace '\s{2,}', ' '
547
+ $_LlmPretext = $_LlmPretext.Trim()
548
+ }
549
+
456
550
  # --- Apply LLM-specific pretext ----------------------------------------------
457
551
  # Prepend the configured pretext (e.g. "Agent Vibes Here") to the speech
458
552
  # text. Guard against double-prefixing on re-entrant or looped calls by
@@ -509,6 +603,23 @@ if ($OverrideEffects -ne "" -and $OverrideEffects -in @("off", "light", "medium"
509
603
  }
510
604
  }
511
605
 
606
+ # Fail loudly when mixing was requested but ffmpeg is unavailable. Without this,
607
+ # background music and reverb are dropped silently and the voice plays "fine" —
608
+ # indistinguishable from a config problem. A long-running tts-watcher.ps1 that
609
+ # started before ffmpeg was installed keeps a stale PATH snapshot and hits this,
610
+ # so the message names the restart explicitly. Mirrors the bash-side warning in
611
+ # audio-processor.sh ("ffmpeg not installed, skipping background mix").
612
+ if (-not $HasFfmpeg -and ($BgEnabled -or $HasReverb)) {
613
+ $_dropped = @()
614
+ if ($BgEnabled) { $_dropped += "background music" }
615
+ if ($HasReverb) { $_dropped += "reverb ($ReverbLevel)" }
616
+ Write-Host ("[WARNING] play-tts.ps1: ffmpeg not found on PATH — dropping " +
617
+ ($_dropped -join " and ") + "; voice will play unmixed.") -ForegroundColor Yellow
618
+ Write-Host ("[WARNING] Install ffmpeg (e.g. 'scoop install ffmpeg'). If it IS " +
619
+ "installed, a background tts-watcher started before it will have a stale " +
620
+ "PATH — restart the watcher.") -ForegroundColor Yellow
621
+ }
622
+
512
623
  # --- Apply LLM-specific engine override --------------------------------------
513
624
  # Allowed local Windows engines: windows-sapi, windows-piper, soprano.
514
625
  # Transport providers (ssh-remote etc.) are not listed because they forward
@@ -33,6 +33,42 @@ if ($env:CLAUDE_PROJECT_DIR -and (Test-Path "$env:CLAUDE_PROJECT_DIR\.claude"))
33
33
  $ProjectClaudeDir = Join-Path (Split-Path -Parent (Split-Path -Parent $ScriptDir)) ".claude"
34
34
  }
35
35
 
36
+ # ---------------------------------------------------------------------------
37
+ # OPT-IN INJECTION GATE (Issue: global-install cacophony).
38
+ #
39
+ # Mirror of the gate in .claude/hooks/session-start-tts.sh — see the long
40
+ # rationale there. Previously this hook injected the ~250-token TTS protocol
41
+ # into EVERY Windows session where AgentVibes was found on disk, so a global
42
+ # install made every open session start speaking at once, and idle sessions
43
+ # still paid the token cost. Injection is now OPT-IN on Windows too.
44
+ #
45
+ # Precedence (identical to bash, so injection and audio agree):
46
+ # 1. project agentvibes-unmuted -> inject (explicit per-project ON)
47
+ # 2. project agentvibes-muted -> silent
48
+ # 3. global ~/.agentvibes-muted -> silent (the global kill-switch)
49
+ # 4. project agentvibes-enabled, OR global opt-in
50
+ # (~/.claude/agentvibes-enabled or ~/.claude/agentvibes-unmuted) -> inject
51
+ # 5. otherwise -> silent (opt-in default; zero tokens)
52
+ #
53
+ # $HOME is honoured ahead of $env:USERPROFILE so the markers resolve the same
54
+ # way under git-bash (where bash writes them) as under native PowerShell.
55
+ $HomeDir = if ($env:HOME) { $env:HOME } else { $env:USERPROFILE }
56
+ if (Test-Path (Join-Path $ProjectClaudeDir "agentvibes-unmuted")) {
57
+ # explicit per-project enable — wins over a global mute, as in play-tts.sh
58
+ } elseif (Test-Path (Join-Path $ProjectClaudeDir "agentvibes-muted")) {
59
+ exit 0
60
+ } elseif (Test-Path (Join-Path $HomeDir ".agentvibes-muted")) {
61
+ exit 0 # global kill-switch, no per-project override
62
+ } elseif ((Test-Path (Join-Path $ProjectClaudeDir "agentvibes-enabled")) -or
63
+ (Test-Path (Join-Path $HomeDir ".claude\agentvibes-enabled")) -or
64
+ (Test-Path (Join-Path $HomeDir ".claude\agentvibes-unmuted"))) {
65
+ # opted in (project install marker, or a deliberate global opt-in)
66
+ } else {
67
+ # Not enabled for this project -> inject nothing (zero tokens).
68
+ # Enable for this project with: /agent-vibes:unmute
69
+ exit 0
70
+ }
71
+
36
72
  # Build the -ProjectDir flag to inject into TTS commands (empty string = omit flag).
37
73
  # Sanitize: strip any embedded quotes that would break PowerShell argument quoting.
38
74
  $ProjectDirFlag = ""
@@ -1,153 +1,153 @@
1
- #!/usr/bin/env python3
2
- #
3
- # File: .claude/hooks-windows/soprano-gradio-synth.py
4
- #
5
- # AgentVibes - Finally, your AI Agents can Talk Back!
6
- # Website: https://agentvibes.org
7
- # Repository: https://github.com/paulpreibisch/AgentVibes
8
- #
9
- # Co-created by Paul Preibisch with Claude AI
10
- # Copyright (c) 2025 Paul Preibisch
11
- #
12
- # Licensed under the Apache License, Version 2.0 (the "License");
13
- # you may not use this file except in compliance with the License.
14
- # You may obtain a copy of the License at
15
- #
16
- # http://www.apache.org/licenses/LICENSE-2.0
17
- #
18
- # Unless required by applicable law or agreed to in writing, software
19
- # distributed under the License is distributed on an "AS IS" BASIS,
20
- # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
- # See the License for the specific language governing permissions and
22
- # limitations under the License.
23
- #
24
- # ---
25
- #
26
- # Soprano Gradio WebUI synthesizer helper.
27
- # Calls the Soprano WebUI's Gradio API and saves the result as a WAV file.
28
- # Uses only Python stdlib (json, sys, urllib) — no extra dependencies.
29
- #
30
- # Usage: python3 soprano-gradio-synth.py "text to speak" output.wav [port]
31
- #
32
- """
33
- Soprano Gradio WebUI synthesizer helper for AgentVibes.
34
-
35
- Calls the Soprano WebUI's Gradio API via the Server-Sent Events (SSE) protocol
36
- and downloads the generated audio as a WAV file.
37
-
38
- Flow:
39
- 1. Submit generation request -> get event_id
40
- 2. Poll SSE stream for audio file URL
41
- 3. Download WAV file to output path
42
-
43
- See: https://github.com/ekwek1/soprano
44
- """
45
- import json
46
- import sys
47
- import urllib.request
48
- import urllib.error
49
-
50
-
51
- def synth(text: str, output_path: str, port: int = 7860) -> None:
52
- base = f"http://127.0.0.1:{port}"
53
-
54
- # Step 1: Submit generation request
55
- # Args: text, temperature, top_p, repetition_penalty, chunk_size, streaming
56
- payload = json.dumps({
57
- "data": [text, 0.0, 0.95, 1.2, 1, False]
58
- }).encode()
59
-
60
- event_id = submit_request(base, payload)
61
-
62
- # Step 2: Poll SSE stream for audio file URL
63
- audio_url = poll_for_result(base, event_id)
64
-
65
- # Step 3: Download the audio file (validate localhost to prevent SSRF)
66
- download_file(audio_url, output_path, port)
67
-
68
-
69
- def submit_request(base: str, payload: bytes) -> str:
70
- """Submit generation request to Gradio API, return event_id."""
71
- for api_base in ["/gradio_api/call", "/call"]:
72
- url = f"{base}{api_base}/generate_speech"
73
- req = urllib.request.Request(
74
- url,
75
- data=payload,
76
- headers={"Content-Type": "application/json"},
77
- )
78
- try:
79
- with urllib.request.urlopen(req, timeout=30) as resp:
80
- return json.loads(resp.read())["event_id"]
81
- except urllib.error.URLError:
82
- continue
83
-
84
- raise RuntimeError("Could not reach Soprano WebUI API")
85
-
86
-
87
- def poll_for_result(base: str, event_id: str) -> str:
88
- """Poll SSE endpoint until audio file URL is returned."""
89
- for api_base in ["/gradio_api/call", "/call"]:
90
- url = f"{base}{api_base}/generate_speech/{event_id}"
91
- req = urllib.request.Request(url)
92
- try:
93
- with urllib.request.urlopen(req, timeout=120) as resp:
94
- for raw_line in resp:
95
- line = raw_line.decode("utf-8", errors="replace").strip()
96
- if not line.startswith("data: "):
97
- continue
98
- try:
99
- parsed = json.loads(line[6:])
100
- except json.JSONDecodeError:
101
- continue
102
- # Response format: [{"path": "...", "url": "...", ...}, "status string"]
103
- if isinstance(parsed, list) and len(parsed) >= 1:
104
- audio = parsed[0]
105
- if isinstance(audio, dict) and "url" in audio:
106
- return audio["url"]
107
- break
108
- except urllib.error.URLError:
109
- continue
110
-
111
- raise RuntimeError("No audio URL in Soprano response")
112
-
113
-
114
- def download_file(url: str, output_path: str, port: int = 7860) -> None:
115
- """Download audio file from Gradio file server.
116
-
117
- Security: Validates URL points to localhost to prevent SSRF.
118
- """
119
- # Validate URL is localhost to prevent SSRF via crafted Gradio responses
120
- allowed_prefixes = [
121
- f"http://127.0.0.1:{port}/",
122
- f"http://localhost:{port}/",
123
- ]
124
- if not any(url.startswith(prefix) for prefix in allowed_prefixes):
125
- raise RuntimeError(f"Refused download from non-localhost URL: {url[:80]}")
126
-
127
- req = urllib.request.Request(url)
128
- with urllib.request.urlopen(req, timeout=30) as resp:
129
- with open(output_path, "wb") as f:
130
- while True:
131
- chunk = resp.read(8192)
132
- if not chunk:
133
- break
134
- f.write(chunk)
135
-
136
-
137
- if __name__ == "__main__":
138
- if len(sys.argv) < 3:
139
- print(f"Usage: {sys.argv[0]} \"text\" output.wav [port]", file=sys.stderr)
140
- sys.exit(1)
141
-
142
- text = sys.argv[1]
143
- output = sys.argv[2]
144
- port = int(sys.argv[3]) if len(sys.argv) > 3 else 7860
145
- if not (1 <= port <= 65535):
146
- print(f"Error: Invalid port number: {port}", file=sys.stderr)
147
- sys.exit(1)
148
-
149
- try:
150
- synth(text, output, port)
151
- except Exception as e:
152
- print(f"Error: {e}", file=sys.stderr)
153
- sys.exit(1)
1
+ #!/usr/bin/env python3
2
+ #
3
+ # File: .claude/hooks-windows/soprano-gradio-synth.py
4
+ #
5
+ # AgentVibes - Finally, your AI Agents can Talk Back!
6
+ # Website: https://agentvibes.org
7
+ # Repository: https://github.com/paulpreibisch/AgentVibes
8
+ #
9
+ # Co-created by Paul Preibisch with Claude AI
10
+ # Copyright (c) 2025 Paul Preibisch
11
+ #
12
+ # Licensed under the Apache License, Version 2.0 (the "License");
13
+ # you may not use this file except in compliance with the License.
14
+ # You may obtain a copy of the License at
15
+ #
16
+ # http://www.apache.org/licenses/LICENSE-2.0
17
+ #
18
+ # Unless required by applicable law or agreed to in writing, software
19
+ # distributed under the License is distributed on an "AS IS" BASIS,
20
+ # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
21
+ # See the License for the specific language governing permissions and
22
+ # limitations under the License.
23
+ #
24
+ # ---
25
+ #
26
+ # Soprano Gradio WebUI synthesizer helper.
27
+ # Calls the Soprano WebUI's Gradio API and saves the result as a WAV file.
28
+ # Uses only Python stdlib (json, sys, urllib) — no extra dependencies.
29
+ #
30
+ # Usage: python3 soprano-gradio-synth.py "text to speak" output.wav [port]
31
+ #
32
+ """
33
+ Soprano Gradio WebUI synthesizer helper for AgentVibes.
34
+
35
+ Calls the Soprano WebUI's Gradio API via the Server-Sent Events (SSE) protocol
36
+ and downloads the generated audio as a WAV file.
37
+
38
+ Flow:
39
+ 1. Submit generation request -> get event_id
40
+ 2. Poll SSE stream for audio file URL
41
+ 3. Download WAV file to output path
42
+
43
+ See: https://github.com/ekwek1/soprano
44
+ """
45
+ import json
46
+ import sys
47
+ import urllib.request
48
+ import urllib.error
49
+
50
+
51
+ def synth(text: str, output_path: str, port: int = 7860) -> None:
52
+ base = f"http://127.0.0.1:{port}"
53
+
54
+ # Step 1: Submit generation request
55
+ # Args: text, temperature, top_p, repetition_penalty, chunk_size, streaming
56
+ payload = json.dumps({
57
+ "data": [text, 0.0, 0.95, 1.2, 1, False]
58
+ }).encode()
59
+
60
+ event_id = submit_request(base, payload)
61
+
62
+ # Step 2: Poll SSE stream for audio file URL
63
+ audio_url = poll_for_result(base, event_id)
64
+
65
+ # Step 3: Download the audio file (validate localhost to prevent SSRF)
66
+ download_file(audio_url, output_path, port)
67
+
68
+
69
+ def submit_request(base: str, payload: bytes) -> str:
70
+ """Submit generation request to Gradio API, return event_id."""
71
+ for api_base in ["/gradio_api/call", "/call"]:
72
+ url = f"{base}{api_base}/generate_speech"
73
+ req = urllib.request.Request(
74
+ url,
75
+ data=payload,
76
+ headers={"Content-Type": "application/json"},
77
+ )
78
+ try:
79
+ with urllib.request.urlopen(req, timeout=30) as resp:
80
+ return json.loads(resp.read())["event_id"]
81
+ except urllib.error.URLError:
82
+ continue
83
+
84
+ raise RuntimeError("Could not reach Soprano WebUI API")
85
+
86
+
87
+ def poll_for_result(base: str, event_id: str) -> str:
88
+ """Poll SSE endpoint until audio file URL is returned."""
89
+ for api_base in ["/gradio_api/call", "/call"]:
90
+ url = f"{base}{api_base}/generate_speech/{event_id}"
91
+ req = urllib.request.Request(url)
92
+ try:
93
+ with urllib.request.urlopen(req, timeout=120) as resp:
94
+ for raw_line in resp:
95
+ line = raw_line.decode("utf-8", errors="replace").strip()
96
+ if not line.startswith("data: "):
97
+ continue
98
+ try:
99
+ parsed = json.loads(line[6:])
100
+ except json.JSONDecodeError:
101
+ continue
102
+ # Response format: [{"path": "...", "url": "...", ...}, "status string"]
103
+ if isinstance(parsed, list) and len(parsed) >= 1:
104
+ audio = parsed[0]
105
+ if isinstance(audio, dict) and "url" in audio:
106
+ return audio["url"]
107
+ break
108
+ except urllib.error.URLError:
109
+ continue
110
+
111
+ raise RuntimeError("No audio URL in Soprano response")
112
+
113
+
114
+ def download_file(url: str, output_path: str, port: int = 7860) -> None:
115
+ """Download audio file from Gradio file server.
116
+
117
+ Security: Validates URL points to localhost to prevent SSRF.
118
+ """
119
+ # Validate URL is localhost to prevent SSRF via crafted Gradio responses
120
+ allowed_prefixes = [
121
+ f"http://127.0.0.1:{port}/",
122
+ f"http://localhost:{port}/",
123
+ ]
124
+ if not any(url.startswith(prefix) for prefix in allowed_prefixes):
125
+ raise RuntimeError(f"Refused download from non-localhost URL: {url[:80]}")
126
+
127
+ req = urllib.request.Request(url)
128
+ with urllib.request.urlopen(req, timeout=30) as resp:
129
+ with open(output_path, "wb") as f:
130
+ while True:
131
+ chunk = resp.read(8192)
132
+ if not chunk:
133
+ break
134
+ f.write(chunk)
135
+
136
+
137
+ if __name__ == "__main__":
138
+ if len(sys.argv) < 3:
139
+ print(f"Usage: {sys.argv[0]} \"text\" output.wav [port]", file=sys.stderr)
140
+ sys.exit(1)
141
+
142
+ text = sys.argv[1]
143
+ output = sys.argv[2]
144
+ port = int(sys.argv[3]) if len(sys.argv) > 3 else 7860
145
+ if not (1 <= port <= 65535):
146
+ print(f"Error: Invalid port number: {port}", file=sys.stderr)
147
+ sys.exit(1)
148
+
149
+ try:
150
+ synth(text, output, port)
151
+ except Exception as e:
152
+ print(f"Error: {e}", file=sys.stderr)
153
+ sys.exit(1)
@@ -1 +1 @@
1
- high
1
+ high