Add native Hermes tool for Athena vocal and instrumental separation

This commit is contained in:
Mikei386 committed 2026-10-18 22:11:00 +02:00
1 parent 55581a0c2d
commit 29783d7b22
6 files changed
+504

No files matched your search

+110
View File
@@ -0,0 +1,110 @@
# Native Hermes audio separation — 18 October 2026
Direct Hermes plugin using the documented `plugin.yaml` / `register(ctx)` tool
interface. This is our integration code, not an upstream Hermes feature or patch.
No MCP server, extra container, custom image, startup script or Python package
installation is involved. Existing Athena Deck performs the separation.
## Use
Start a **new Hermes session** after activation (the running gateway reports that
new toolsets take effect on the next session). Attach an MP3 and ask:
> Trenne diese MP3 in Gesang und Instrumental. Gib mir beide Dateien einzeln zurück.
The tool `athena_separate_audio` receives the gateway-local attachment path. It
starts `/api/v1/separator-chat/start`, checks the same job through
`/api/v1/separator-tests`, then downloads the two WAVs through
`/api/v1/separator-tests/audio`. It uses the same BS-RoFormer checkpoint as the
existing OpenWebUI integration. Inputs may be MP3/WAV/FLAC/M4A/OGG/OPUS/AAC/AIFF/
WebM, up to 256 MiB and 20 minutes. Existing FFmpeg normalizes them to stereo
44.1-kHz PCM16; temporary converted input is deleted.
Long jobs return a job ID after about 15 seconds of polling. Hermes must poll
that ID until completion instead of starting the input again. Per-session
locking and input fingerprints prevent simultaneous/retried duplicate starts.
An unconfirmed POST is not automatically retried. Athena errors and replaced
remote jobs fail closed; no other user's result is adopted.
Two durable files, `Vocals.wav` and `Instrumental.wav`, are saved under
`$HERMES_HOME/audio-separation/<session-hash>/<job-id>/`. The result instructs
Hermes to put both native `MEDIA:<path>` lines in its final reply. These are
ordinary downloadable audio attachments, not a ZIP, voice message or temporary
Athena URL. Attachment rendering is the client's responsibility.
**Delivery limitation:** Hermes' upstream automatic media-repair allowlist only
contains its own TTS/image tools. This custom tool therefore relies on the model
including the two supplied MEDIA lines in its final response; it does not patch
that allowlist. Desktop/Conduit support the native media notation. The live
technical test below verifies generated files and the download policy, not an
actual user's Desktop/iOS rendering or LLM tool selection. Those remain a user
acceptance check. Do not claim a UI roundtrip was tested until it is observed.
Deck retains ownership of GPU arbitration. Existing requests finish before its
exclusive audio reservation; the plugin never kills GPU workers, changes the
operating mode, enables disabled profiles or downloads model weights. The next
chat request reloads its chat profile through the regular Deck path.
## Installed instance
Only `Hermes-Agent-Desktop` is changed:
- Host: `/mnt/nvme-storage/appdata/Hermes-Agent-Desktop/plugins/athena-audio`.
- Container: `/opt/data/plugins/athena-audio`, inside the existing persistent home.
- Private settings: `plugins.entries.athena-audio.settings.base_url` and `api_key`
in that instance's private `config.yaml`; no credentials in this repository.
- Base URL: `http://192.168.1.212:8108` (existing Deck management API).
- An existing Athena service credential was reused internally, without printing it.
- Official `hermes plugins doctor` passed; `hermes plugins enable athena-audio`
reloaded the gateway's plugins without container restart. Tools apply to new
sessions. Retained old Hermes/WebUI containers are unchanged.
## Install / update / restore
For any supported native Linux Hermes installation, place `plugin.yaml`,
`__init__.py` and `separator.py` in the **active profile's**
`$HERMES_HOME/plugins/athena-audio/`, owned by its service user. Requirements:
Hermes with native plugin support, Python 3.11+, FFmpeg/FFprobe, and network
access to an installed/enabled Athena separator profile. Only the Python
standard library is used by this plugin. Install FFmpeg on fresh Debian with
the system package manager; the current official desktop image already has it.
Use Hermes' native Plugins settings to set the Deck base URL and existing
service token privately, then run as the service user:
```sh
hermes plugins doctor "$HERMES_HOME/plugins/athena-audio"
hermes plugins enable athena-audio
```
Updates replace these plugin files, followed by the official plugin reload /
disable-enable workflow when no tool call is running. No image rebuild needed.
Remove with `hermes plugins disable athena-audio` before removing its directory;
result files remain independent of code removal.
Encrypted backups must cover the entire own Hermes home: plugin code, private
config/credentials, enabled toolset selection, uploaded originals and
`audio-separation/` results/records. Preserve service-user ownership on restore.
Git reproduces the public code and this recipe, not private credentials or user
audio. This integration does not establish a full fresh-host restore drill.
## Verification
- `python3 test_separator.py`: real local HTTP multipart upload plus two WAV
downloads against a synthetic API, FFmpeg conversion, retry idempotency,
cross-session rejection and remote-job replacement rejection passed.
- Official installed Hermes Plugin Doctor: discovery/manifest/import/registration
passed with one native tool and no hooks.
- Fresh native plugin manager found `athena_separate_audio` in its scoped registry.
- Real Athena run from the Hermes container: synthetic 3-second MP3 completed,
producing `Vocals.wav` (529244 bytes) and `Instrumental.wav` (529278 bytes).
Both passed WAV parsing and the native `/opt/data` managed-download policy.
- Athena reported zero active requests before the GPU test. No LLM test, Athena
restart, OpenCode restart or Hermes container restart was performed.
- This is a transport/functionality test with synthetic audio, **not** a music
separation quality assessment or client UI acceptance test.
Official interfaces:
- https://hermes-agent.nousresearch.com/docs/developer-guide/plugins
- https://github.com/NousResearch/hermes-agent/blob/main/hermes_cli/web_routers/files.py
- https://github.com/NousResearch/hermes-agent/blob/main/gateway/platforms/base.py
@@ -0,0 +1,12 @@
"""Native Hermes tool; no MCP, additional service, or core patches."""
from .separator import SCHEMA, separate
def register(ctx):
def handler(args, **kwargs):
return separate(args, base_url=ctx.get_config('base_url', 'http://192.168.1.212:8108'),
api_key=ctx.get_config('api_key', ''), **kwargs)
ctx.register_tool(name='athena_separate_audio', toolset='athena_audio',
schema=SCHEMA, handler=handler,
description='Gesang und Instrumental als einzelne WAV-Dateien zurückgeben', emoji='🎵')
@@ -0,0 +1,14 @@
name: athena-audio
version: 1.0.0
description: Separate uploaded audio on Athena and return individual WAV files.
author: Athena Deck
provides_tools:
- athena_separate_audio
config_schema:
base_url:
type: str
default: http://192.168.1.212:8108
description: Athena Deck management URL serving the existing separator API.
api_key:
type: secret
description: Existing Athena service token; never include it in chat.
@@ -0,0 +1,266 @@
"""Athena's existing separation API, exposed through the native Hermes plugin API.
Each call waits at most 15 seconds for processing. Repeat with the returned job_id
until complete; no detached daemon, long-running tool timeout or duplicate starts.
"""
import hashlib
import http.client
import json
import fcntl
from pathlib import Path
import re
import subprocess
import tempfile
import time
from urllib.parse import urlencode, urlsplit
import uuid
import wave
MAX_BYTES = 256 * 1024**2
MAX_OUTPUT = 512 * 1024**2
EXTENSIONS = {'.wav', '.mp3', '.flac', '.ogg', '.m4a', '.aac', '.opus', '.aiff', '.aif', '.webm'}
MODEL = 'model_bs_roformer_ep_317_sdr_12.9755.ckpt'
SCHEMA = {
'name': 'athena_separate_audio',
'description': (
'Trenne eine hochgeladene MP3/Audiodatei in Gesang (Vocals.wav) und Instrumental.wav. '
'Use the real gateway-local path from the user attachment, never a path on the phone/Mac. '
'Start with file_path; while state=running repeat with ONLY the returned job_id until complete. '
'Processing may wait for Athena GPU availability; never unload models yourself. '
'On success include BOTH returned MEDIA: lines verbatim on separate lines in your final reply '
'so the chat offers both WAV files as attachments. Do not claim success before state=complete. '
'Maximum 20 minutes / 256 MiB; no ZIP.'),
'parameters': {'type': 'object', 'properties': {
'file_path': {'type': 'string', 'description': 'Uploaded audio path; only for starting a new separation.'},
'job_id': {'type': 'string', 'description': 'Returned local job ID; poll this instead of starting again.'}},
'additionalProperties': False},
}
class AudioError(Exception):
pass
class Client:
def __init__(self, base_url, api_key):
self.url = urlsplit(base_url.rstrip('/'))
if self.url.scheme not in ('http', 'https') or not self.url.hostname or self.url.username or self.url.password or self.url.query or self.url.fragment:
raise AudioError('Ungültige Athena-Adresse in den Plugin-Einstellungen.')
if not api_key:
raise AudioError('Athena-Dienstschlüssel fehlt in den Plugin-Einstellungen.')
self.headers = {'Authorization': 'Bearer ' + api_key}
def connection(self):
cls = http.client.HTTPSConnection if self.url.scheme == 'https' else http.client.HTTPConnection
return cls(self.url.hostname, self.url.port, timeout=120)
def request(self, path, *, upload=None):
conn = self.connection()
try:
full_path = self.url.path.rstrip('/') + path
if upload is None:
conn.request('GET', full_path, headers=self.headers)
else:
boundary = 'athena-' + uuid.uuid4().hex
prefix = (f'--{boundary}\r\nContent-Disposition: form-data; name="model"\r\n\r\n{MODEL}\r\n'
f'--{boundary}\r\nContent-Disposition: form-data; name="target"\r\n\r\nvocals\r\n'
f'--{boundary}\r\nContent-Disposition: form-data; name="file"; filename="input.wav"\r\n'
'Content-Type: audio/wav\r\n\r\n').encode()
suffix = f'\r\n--{boundary}--\r\n'.encode()
conn.putrequest('POST', full_path)
for key, val in self.headers.items():
conn.putheader(key, val)
conn.putheader('Content-Type', 'multipart/form-data; boundary=' + boundary)
conn.putheader('Content-Length', str(len(prefix) + upload.stat().st_size + len(suffix)))
conn.endheaders()
conn.send(prefix)
with upload.open('rb') as source:
while block := source.read(1024**2):
conn.send(block)
conn.send(suffix)
response = conn.getresponse()
if response.status != 200:
# Never reflect arbitrary remote bodies, request headers or credentials.
raise AudioError(f'Athena meldet HTTP {response.status}. Endpunktfreigabe und Trennprofil prüfen.')
payload = response.read(2 * 1024**2 + 1)
if len(payload) > 2 * 1024**2:
raise AudioError('Athena-Statusantwort ist zu groß.')
return json.loads(payload)
finally:
conn.close()
def download(self, remote_id, index, destination):
conn = self.connection()
partial = destination.with_suffix('.part')
try:
conn.request('GET', self.url.path.rstrip('/') + '/api/v1/separator-tests/audio?' +
urlencode({'id': remote_id, 'index': index}), headers=self.headers)
response = conn.getresponse()
if response.status != 200:
raise AudioError(f'WAV-Download fehlgeschlagen (HTTP {response.status}).')
size = 0
with partial.open('wb') as output:
while block := response.read(1024**2):
size += len(block)
if size > MAX_OUTPUT:
raise AudioError('Ergebnisspur überschreitet 512 MiB.')
output.write(block)
with wave.open(str(partial)) as audio:
if not audio.getnframes():
raise AudioError('Athena lieferte eine leere WAV-Datei.')
partial.replace(destination)
finally:
partial.unlink(missing_ok=True)
conn.close()
def home():
from hermes_constants import get_hermes_home
return Path(get_hermes_home()).resolve()
def cwd():
from agent.runtime_cwd import resolve_agent_cwd
return Path(resolve_agent_cwd()).resolve()
def scope(kwargs):
# Separate records for sessions even when they share a workspace.
session = kwargs.get('session_id') or kwargs.get('task_id')
if not session:
from gateway.session_context import get_session_env
session = get_session_env('HERMES_SESSION_ID')
if not session:
raise AudioError('Hermes-Sitzung fehlt; Werkzeug aus einem Chat aufrufen.')
return hashlib.sha256(str(session).encode()).hexdigest()[:24]
def source_path(raw):
path = Path(raw).expanduser()
path = (cwd() / path).resolve() if not path.is_absolute() else path.resolve()
allowed = [cwd(), home() / 'attachments']
if not any(path.is_relative_to(root.resolve()) for root in allowed):
raise AudioError('Audiodatei muss aus dem Workspace oder den Hermes-Chat-Anhängen stammen.')
if path.suffix.lower() not in EXTENSIONS or not path.is_file() or not 0 < path.stat().st_size <= MAX_BYTES:
raise AudioError('Audiodatei fehlt, ist leer, hat ein unbekanntes Format oder überschreitet 256 MiB.')
return path
def decode(source, destination):
# Probe BEFORE decoding: reject long/compressed inputs without expanding hours of PCM.
result = subprocess.run(['ffprobe', '-v', 'error', '-show_entries', 'format=duration',
'-of', 'json', str(source)], capture_output=True, timeout=30)
try:
duration = float(json.loads(result.stdout)['format']['duration'])
except (ValueError, KeyError, TypeError):
raise AudioError('Audiodauer konnte nicht bestimmt werden.') from None
if result.returncode or not 0 < duration <= 1200:
raise AudioError('Audiodatei muss zwischen 0 und 20 Minuten lang sein.')
result = subprocess.run(['ffmpeg', '-nostdin', '-v', 'error', '-y', '-i', str(source),
'-vn', '-ac', '2', '-ar', '44100', '-c:a', 'pcm_s16le', str(destination)],
capture_output=True, timeout=180)
if result.returncode or not destination.is_file() or destination.stat().st_size > MAX_BYTES:
raise AudioError('Audio konnte nicht in Stereo-WAV umgewandelt werden.')
def save(record_path, record):
temp = record_path.with_suffix('.tmp')
temp.write_text(json.dumps(record))
temp.chmod(0o600)
temp.replace(record_path)
def separate(args, *, base_url, api_key, **kwargs):
"""Serialize requests per chat so parallel calls cannot launch the same input twice."""
try:
root = home() / 'audio-separation' / scope(kwargs)
root.mkdir(parents=True, exist_ok=True, mode=0o700)
with (root / '.lock').open('a') as lock:
try:
fcntl.flock(lock.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
except BlockingIOError:
return json.dumps({'state': 'busy', 'next': 'Another separation call in this chat is still running. Wait for it; do not start another job.'})
return _separate(args, base_url=base_url, api_key=api_key, **kwargs)
except AudioError as exc:
return json.dumps({'state': 'error', 'error': str(exc)}, ensure_ascii=False)
except Exception:
return json.dumps({'state': 'error', 'error': 'Sitzungsablage nicht verfügbar.'})
def _separate(args, *, base_url, api_key, **kwargs):
try:
owner = scope(kwargs)
root = home() / 'audio-separation' / owner
root.mkdir(parents=True, exist_ok=True, mode=0o700)
client = Client(base_url, api_key)
job_id = args.get('job_id', '')
if job_id and args.get('file_path'):
raise AudioError('Entweder file_path zum Starten oder job_id zum Abfragen angeben.')
if job_id:
if not re.fullmatch(r'[a-f0-9]{32}', job_id):
raise AudioError('Ungültige Auftrags-ID.')
folder = root / job_id
record_path = folder / 'job.json'
if not record_path.is_file():
raise AudioError('Auftrag gehört nicht zu dieser Sitzung oder wurde nicht gefunden.')
record = json.loads(record_path.read_text())
if record.get('result'):
return json.dumps(record['result'], ensure_ascii=False)
else:
if not args.get('file_path'):
raise AudioError('Bitte den Pfad der hochgeladenen MP3/Audiodatei angeben.')
source = source_path(args['file_path'])
# Resume same session/input after retries instead of launching duplicate GPU work.
stamp = source.stat()
fingerprint = hashlib.sha256(f'{source}:{stamp.st_size}:{stamp.st_mtime_ns}'.encode()).hexdigest()
for existing in root.glob('*/job.json'):
previous = json.loads(existing.read_text())
if previous.get('fingerprint') == fingerprint:
return _separate({'job_id': existing.parent.name}, base_url=base_url, api_key=api_key, **kwargs)
job_id = uuid.uuid4().hex
folder = root / job_id
folder.mkdir(mode=0o700)
record_path = folder / 'job.json'
record = {'fingerprint': fingerprint, 'remote_id': None, 'state': 'submitting'}
save(record_path, record)
with tempfile.TemporaryDirectory(prefix='athena-audio-') as temp:
converted = Path(temp) / 'input.wav'
decode(source, converted)
job = client.request('/api/v1/separator-chat/start', upload=converted)
record.update(remote_id=job['id'], state=job['state'])
save(record_path, record)
if not record.get('remote_id'):
raise AudioError('Ein früherer Start ist unbestätigt. Athena prüfen, bevor erneut gestartet wird.')
deadline = time.monotonic() + 15
while True:
job = client.request('/api/v1/separator-tests').get('job')
if not job or job.get('id') != record['remote_id']:
raise AudioError('Athena-Auftrag wurde ersetzt oder ist nicht mehr verfügbar. Keine fremden Ergebnisse werden übernommen.')
if job['state'] != 'running' or time.monotonic() >= deadline:
break
time.sleep(2)
if job['state'] == 'running':
return json.dumps({'state': 'running', 'job_id': job_id,
'next': 'Call athena_separate_audio again with this job_id; do not restart.'})
if job['state'] != 'complete':
raise AudioError('Athena konnte die Audiotrennung nicht abschließen. Trennprofil und GPU-Verfügbarkeit prüfen.')
files = job.get('files', [])
if len(files) != 2 or sum(f.get('name') == 'rest.wav' for f in files) != 1:
raise AudioError('Athena lieferte nicht die erwarteten zwei Spuren.')
outputs = []
for item in files:
destination = folder / ('Instrumental.wav' if item['name'] == 'rest.wav' else 'Vocals.wav')
client.download(record['remote_id'], item['index'], destination)
outputs.append({'name': destination.name, 'path': str(destination)})
result = {'state': 'complete', 'job_id': job_id, 'files': outputs,
'delivery': '\n'.join('MEDIA:' + f['path'] for f in outputs),
'instruction': 'Include both MEDIA: lines verbatim, each on its own line, in the final chat answer.'}
record.update(state='complete', result=result)
save(record_path, record)
return json.dumps(result, ensure_ascii=False)
except AudioError as exc:
return json.dumps({'state': 'error', 'error': str(exc)}, ensure_ascii=False)
except subprocess.TimeoutExpired:
return json.dumps({'state': 'error', 'error': 'Audio-Vorbereitung hat das Zeitlimit überschritten.'})
except Exception:
return json.dumps({'state': 'error', 'error': 'Dateizugriff oder Verbindung fehlgeschlagen; Athena und den Upload prüfen. Ein unbestätigter Start wird nicht automatisch wiederholt.'})
@@ -0,0 +1,98 @@
"""Exercise real HTTP uploads/downloads against a synthetic Athena API; no LLM/GPU."""
import importlib.util
import io
import json
from pathlib import Path
import tempfile
import threading
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
import unittest
from unittest.mock import patch
import wave
spec = importlib.util.spec_from_file_location('audio_separator_plugin', Path(__file__).with_name('separator.py'))
plugin = importlib.util.module_from_spec(spec)
spec.loader.exec_module(plugin)
def wav():
stream = io.BytesIO()
with wave.open(stream, 'wb') as w:
w.setnchannels(2)
w.setsampwidth(2)
w.setframerate(44100)
w.writeframes(b'\x00' * 17640)
return stream.getvalue()
class Server(BaseHTTPRequestHandler):
starts = 0
downloads = 0
wrong_job = False
def log_message(self, *args):
pass
def send(self, body):
self.send_response(200)
self.end_headers()
self.wfile.write(body)
def do_POST(self):
assert self.headers['Authorization'] == 'Bearer test-only'
body = self.rfile.read(int(self.headers['Content-Length']))
assert b'RIFF' in body and plugin.MODEL.encode() in body and b'vocals' in body
type(self).starts += 1
self.send(json.dumps({'id': 'a' * 32, 'state': 'running'}).encode())
def do_GET(self):
assert self.headers['Authorization'] == 'Bearer test-only'
if 'audio?' in self.path:
type(self).downloads += 1
self.send(wav())
else:
self.send(json.dumps({'job': {'id': ('b' if self.wrong_job else 'a') * 32,
'state': 'complete', 'files': [
{'index': 0, 'name': 'input_(Vocals).wav'},
{'index': 1, 'name': 'rest.wav'}]}}).encode())
class SeparationTests(unittest.TestCase):
def test_upload_decode_download_idempotency_and_session_boundaries(self):
with tempfile.TemporaryDirectory() as temp:
root = Path(temp)
(root / 'workspace').mkdir()
source = root / 'workspace' / 'test.wav'
source.write_bytes(wav())
http = ThreadingHTTPServer(('127.0.0.1', 0), Server)
thread = threading.Thread(target=http.serve_forever, daemon=True)
thread.start()
try:
with patch.object(plugin, 'home', return_value=root), patch.object(plugin, 'cwd', return_value=root / 'workspace'):
settings = dict(base_url=f'http://127.0.0.1:{http.server_port}', api_key='test-only', session_id='own-test')
result = json.loads(plugin.separate({'file_path': str(source)}, **settings))
self.assertEqual(result['state'], 'complete', result)
self.assertEqual({f['name'] for f in result['files']}, {'Vocals.wav', 'Instrumental.wav'})
self.assertEqual(result['delivery'].count('MEDIA:'), 2)
self.assertTrue(all(Path(f['path']).read_bytes() == wav() for f in result['files']))
self.assertEqual(json.loads(plugin.separate({'file_path': str(source)}, **settings)), result)
self.assertEqual(Server.starts, 1)
self.assertEqual(Server.downloads, 2)
foreign = dict(settings, session_id='another-session')
self.assertEqual(json.loads(plugin.separate({'job_id': result['job_id']}, **foreign))['state'], 'error')
self.assertEqual(json.loads(plugin.separate({'file_path': '/etc/shadow'}, **settings))['state'], 'error')
# Force a status refresh and verify a replaced remote job is never downloaded.
record_path = next((root / 'audio-separation').glob('*/*/job.json'))
record = json.loads(record_path.read_text())
record.pop('result')
record_path.write_text(json.dumps(record))
Server.wrong_job = True
self.assertEqual(json.loads(plugin.separate({'job_id': result['job_id']}, **settings))['state'], 'error')
self.assertEqual(Server.downloads, 2)
finally:
http.shutdown()
http.server_close()
if __name__ == '__main__':
unittest.main()
@@ -52,6 +52,10 @@ old `Hermes-Agent` is stopped; `Hermes-Workspace` and its files are not removed.
## Connecting
Native audio separation is now installed in this instance's own persistent
home: [setup, usage and verification](../audio/README.md). It uses Athena's
existing separator service without another container or MCP.
In the existing Hermes Desktop app, add a Remote Gateway using
`http://192.168.1.2:9120` and sign in normally using the existing Hermes login.
Open this connection's bot and its Screen pane. The direct address is for the