Centralize Hermes Athena provider and credential across profiles

This commit is contained in:
Mikei386 committed 2026-10-26 14:52:33 +01:00
1 parent 67d2580e13
commit d911b877b6
2 files changed
+327

No files matched your search

@@ -0,0 +1,116 @@
# Shared Athena provider for the NAS Hermes gateway
Applied on 26 October 2026 at Michael's request. Hermes Desktop on the Mac
continues to use the NAS backend; no Mac software was changed.
## Result
Athena's provider definition and existing credential are now stored once:
```text
/opt/data/managed/
├── config.yaml # providers.athena, endpoint, transport and model catalog
└── .env # existing Athena credential; never include this file in Git
```
The host path is
`/mnt/nvme-storage/appdata/Hermes-Agent-Desktop/managed/`.
`config.yaml` is mode `0640`, `.env` mode `0600`, and their parent directory
mode `0750`, owned by the existing Hermes data owner (`99:100`).
All 13 existing profiles retain their previous `model.default`, currently
`flash-next-strata-iq3-dual`, with `model.provider: custom:athena`.
Their Athena entries under `providers`/legacy `custom_providers`, redundant
model connection fields, and copies of the single Athena dotenv variable
were removed. Other providers, credentials, tools, memories, workspaces,
voice settings, and session records were not migrated or modified.
HORIZON Dev and Prüfungs VDI Dev previously cached only one Athena model;
they now share the existing twelve-model catalog with the other profiles.
The managed files use Hermes' official managed-scope loader. A named provider
entry has this shape (the catalog is taken from the existing configuration):
```yaml
providers:
athena:
name: Athena
api: http://192.168.1.212:8120/v1
key_env: HERMES_CUSTOM_192_168_1_212_8120_API_KEY
transport: chat_completions
default_model: flash-next-strata-iq3-dual
models: {} # actual existing model catalog belongs here
models_discovered: true
```
The managed layer pins these provider values for every profile. It does not
pin the profile's default model or unrelated provider entries. New profiles
inherit the Athena provider and its credential through the managed layer.
This is shared configuration, not a filesystem or agent access sandbox.
## Persistence without restarting active work
The existing Unraid template already references the persistent
`container.env` using Docker's `--env-file`. That file now contains
`HERMES_MANAGED_DIR=/opt/data/managed`, so a container recreated from the
template loads the persistent directory directly.
The already-running container was created before that variable existed.
For it, `/etc/hermes/config.yaml` and `/etc/hermes/.env` are symbolic links
to the persistent files. This uses the loader's existing `/etc/hermes`
default immediately; no service, host, container, or model restart was needed.
An ordinary restart keeps the links. A recreated container reads the
persisted environment variable instead of depending on its old overlay.
## Verification
- The migration dry-run validated all 13 profile configurations before writes.
- Each default model was compared with its original value after migration.
- Each raw profile has zero local Athena provider entries and zero copies
of its credential variable; its effective configuration has one Athena
provider and twelve catalog models.
- Hermes' real `resolve_runtime_provider` passed in all 13 profile home and
secret-scope contexts; the resolved URL and credential were checked internally.
Neither credentials nor private prompts were emitted.
- An authenticated read of Athena `/v1/models` returned HTTP 200 and twelve
models, including `flash-next-strata-iq3-dual`. No inference was requested.
- A nonexistent profile path inherited both provider and credential in a
read-only check; no extra profile or session was created.
- The running dashboard (v0.22.5), scoped to HORIZON Dev, showed the unchanged
main model and Athena with all twelve models in its picker, without restart.
- A separate process using the future container's `HERMES_MANAGED_DIR` resolved
the provider and credential successfully. An actual container recreation was
deliberately not performed. The packaged image has no `/opt/hermes/.git`;
an exact source commit could not be read there.
Native Mac-app interaction and an inference turn were not separately tested.
Existing sessions may retain their own saved model selection. No session was
rewritten, no task interrupted, and no additional service installed.
## Reproduction and recovery
`centralize-athena.py` is a guarded, one-time operator migration. Its default
is a dry-run; `--apply` is required to write. It expects the original duplicated
configuration and refuses an existing managed destination or policy. Do not
rerun it against this already migrated installation.
Run it with the installed Hermes Python, `PYTHONPATH` pointing at the Hermes
source/package directory, and an account able to preserve the existing file
owners. The native-host equivalents are the same `HERMES_MANAGED_DIR`, managed
files and per-profile configuration; Docker is only the current transport.
The script retains original bytes in memory and restores them if its own
verification fails. It creates no durable credential/configuration backups.
For recovery on a new host/container, restore **both** managed files from the
operator's protected data backup, restore their ownership and modes, and set
`HERMES_MANAGED_DIR` in the service/container launch environment before starting
Hermes. Restore `container.env` for the current Unraid integration. The credential
cannot be reconstructed from Git. Keep it out of repositories and plaintext
exports. Full backup/restore and real container recreation were not exercised
by this maintenance action.
Operator NAS access for this task used the existing Mac SSH identity
`~/.ssh/ha_agent` to `root@192.168.1.2`, not the Athena-host identity. The SSH
private key is not part of this repository.
References: [managed scope](https://github.com/NousResearch/hermes-agent/blob/main/website/docs/user-guide/managed-scope.md),
[named custom providers](https://github.com/NousResearch/hermes-agent/blob/main/website/docs/integrations/providers.md#named-custom-providers).
@@ -0,0 +1,211 @@
#!/usr/bin/env python3
"""Move the existing Athena route to Hermes managed scope; dry-run by default.
Run with Hermes' Python and source on PYTHONPATH. Never prints secret values.
Only the one Athena provider/credential is migrated. No services are restarted.
"""
import argparse
import copy
import json
import os
from pathlib import Path
import re
import tempfile
from unittest.mock import patch
import hermes_yaml as yaml
from agent.secret_scope import build_profile_secret_scope, invalidate_env_file_cache, load_env_file
from hermes_cli import managed_scope
from hermes_cli.config_effective import load_user_config_effective
from hermes_cli.config_providers import get_compatible_custom_providers
KEY = 'HERMES_CUSTOM_192_168_1_212_8120_API_KEY'
URL = 'http://192.168.1.212:8120/v1'
def read_yaml(path):
value = yaml.safe_load(path.read_text()) or {}
if not isinstance(value, dict):
raise RuntimeError('Expected a YAML mapping: ' + str(path))
return value
def strip_env_line(raw, name):
pattern = re.compile(r'^\s*(?:export\s+)?' + re.escape(name) + r'\s*=')
return ''.join(line for line in raw.decode().splitlines(keepends=True)
if not pattern.match(line)).encode()
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument('--root', type=Path, default=Path('/opt/data'))
parser.add_argument('--managed', type=Path, default=Path('/opt/data/managed'))
parser.add_argument('--bootstrap-dir', type=Path, default=Path('/etc/hermes'))
parser.add_argument('--apply', action='store_true')
args = parser.parse_args()
root, managed, bootstrap = args.root, args.managed, args.bootstrap_dir
if managed.exists():
raise RuntimeError('Managed destination already exists; inspect instead of overwriting it.')
if any((bootstrap / name).exists() or (bootstrap / name).is_symlink()
for name in ('config.yaml', '.env')):
raise RuntimeError('Bootstrap managed files already exist; refusing to replace policy.')
if managed_scope.load_managed_config() or managed_scope.load_managed_env():
raise RuntimeError('Existing managed policy requires an explicit merge.')
homes = [root] + sorted(p for p in (root / 'profiles').iterdir()
if (p / 'config.yaml').is_file())
configs = {home: read_yaml(home / 'config.yaml') for home in homes}
normalized = get_compatible_custom_providers(configs[root])
canonical = [row for row in normalized if row.get('name', '').lower() == 'athena']
if len(canonical) != 1:
raise RuntimeError('Expected one canonical Athena route in default.')
canonical = canonical[0]
assert canonical['base_url'] == URL and canonical['key_env'] == KEY
assert canonical['api_mode'] == 'chat_completions'
secret = load_env_file(root / '.env').get(KEY)
if not secret or not re.fullmatch(r'[\x21-\x7e]+', secret) or any(c in secret for c in "'\"\\#"):
raise RuntimeError('Credential is missing or needs a different dotenv encoding.')
central = {'providers': {'athena': {
'name': 'Athena', 'api': URL, 'key_env': KEY,
'transport': 'chat_completions', 'default_model': canonical['model'],
'models': copy.deepcopy(canonical['models']),
'models_discovered': bool(canonical.get('models_discovered')),
}}}
originals, proposed, defaults = {}, {}, {}
for home, cfg in configs.items():
for row in get_compatible_custom_providers(cfg):
if row.get('name', '').lower() != 'athena':
continue
for field in ('base_url', 'key_env', 'api_mode', 'model'):
if row.get(field) != canonical.get(field):
raise RuntimeError('Different Athena routing in ' + home.name + ': ' + field)
model_ids = set(row.get('models') or {})
if not model_ids <= set(canonical['models']):
raise RuntimeError('Canonical catalog would lose models in ' + home.name)
if build_profile_secret_scope(home).get(KEY) != secret:
raise RuntimeError('Profile uses a different credential: ' + home.name)
new = copy.deepcopy(cfg)
model = new.get('model')
if not isinstance(model, dict) or model.get('provider') not in ('custom', 'custom:athena'):
raise RuntimeError('Unexpected default route in ' + home.name)
if model.get('base_url') != URL:
raise RuntimeError('Unexpected model URL in ' + home.name)
if model.get('api_key') not in (None, '', secret, '${' + KEY + '}'):
raise RuntimeError('Different inline model credential in ' + home.name)
defaults[home] = model['default']
model['provider'] = 'custom:athena'
for field in ('base_url', 'api_mode', 'api_key', 'key_env'):
model.pop(field, None)
if 'providers' in new:
new['providers'] = {k: v for k, v in new['providers'].items() if k.lower() != 'athena'}
if not new['providers']:
del new['providers']
if 'custom_providers' in new:
new['custom_providers'] = [v for v in new['custom_providers']
if str(v.get('name', '')).lower() != 'athena']
if not new['custom_providers']:
del new['custom_providers']
# All changes are limited to the three intentionally migrated sections.
assert {k: v for k, v in cfg.items() if k not in ('model', 'providers', 'custom_providers')} == {
k: v for k, v in new.items() if k not in ('model', 'providers', 'custom_providers')}
with patch.object(managed_scope, 'load_managed_config', return_value=central):
effective = managed_scope.apply_managed_overlay(copy.deepcopy(new))
routes = [v for v in get_compatible_custom_providers(effective)
if v.get('name', '').lower() == 'athena']
assert len(routes) == 1 and routes[0]['base_url'] == URL
assert routes[0]['models'] == canonical['models']
config_path, env_path = home / 'config.yaml', home / '.env'
originals[config_path] = config_path.read_bytes()
proposed[config_path] = yaml.safe_dump(new, sort_keys=False, allow_unicode=True).encode()
assert yaml.safe_load(proposed[config_path].decode()) == new
if env_path.is_file():
originals[env_path] = env_path.read_bytes()
proposed[env_path] = strip_env_line(originals[env_path], KEY)
before_env = load_env_file(env_path)
assert before_env.get(KEY, secret) == secret
env_file = root / 'container.env'
originals[env_file] = env_file.read_bytes()
env = strip_env_line(originals[env_file], 'HERMES_MANAGED_DIR').rstrip(b'\n')
proposed[env_file] = env + b'\nHERMES_MANAGED_DIR=' + str(managed).encode() + b'\n'
result = dict(profiles=len(homes), model_count=len(canonical['models']),
central_directory=str(managed), default_models_preserved=True,
dry_run=not args.apply)
if not args.apply:
print(json.dumps(result))
return
metadata = {p: p.stat() for p in originals}
owner = (root / '.env').stat()
written, created = {}, []
def atomic(path, data, mode, uid, gid):
fd, tmp = tempfile.mkstemp(prefix='.' + path.name + '.centralize-', dir=path.parent)
try:
with os.fdopen(fd, 'wb') as stream:
os.fchmod(stream.fileno(), mode)
os.fchown(stream.fileno(), uid, gid)
stream.write(data)
stream.flush()
os.fsync(stream.fileno())
os.replace(tmp, path)
finally:
if os.path.exists(tmp):
os.unlink(tmp)
try:
managed.mkdir(mode=0o750)
os.chown(managed, owner.st_uid, owner.st_gid)
central_files = {
'config.yaml': (yaml.safe_dump(central, sort_keys=False, allow_unicode=True).encode(), 0o640),
'.env': ((KEY + '=' + secret + '\n').encode(), 0o600),
}
for name, (data, mode) in central_files.items():
atomic(managed / name, data, mode, owner.st_uid, owner.st_gid)
created.append(managed / name)
# Existing running processes use /etc/hermes; next container recreation
# uses the persistent HERMES_MANAGED_DIR from the existing env-file.
for name in central_files:
(bootstrap / name).symlink_to(managed / name)
created.append(bootstrap / name)
managed_scope.invalidate_managed_cache()
for path, data in proposed.items():
if path.read_bytes() != originals[path]:
raise RuntimeError('Concurrent edit detected: ' + str(path))
st = metadata[path]
atomic(path, data, st.st_mode & 0o777, st.st_uid, st.st_gid)
written[path] = data
if path.name == '.env':
invalidate_env_file_cache(path)
managed_scope.invalidate_managed_cache()
for home in homes:
raw = read_yaml(home / 'config.yaml')
assert not [v for v in get_compatible_custom_providers(raw)
if v.get('name', '').lower() == 'athena']
assert raw['model'] == {'provider': 'custom:athena', 'default': defaults[home]}
effective = load_user_config_effective(home / 'config.yaml')
routes = [v for v in get_compatible_custom_providers(effective)
if v.get('name', '').lower() == 'athena']
assert len(routes) == 1 and routes[0]['base_url'] == URL
assert routes[0]['models'] == canonical['models']
assert build_profile_secret_scope(home).get(KEY) == secret
assert KEY not in load_env_file(home / '.env')
result.update(dry_run=False, applied=True, local_provider_copies=0,
local_credential_copies=0, services_restarted=0)
print(json.dumps(result))
except BaseException:
# Exact original bytes and permissions are retained only in this process.
# Never leave backup copies of private configs or credentials on disk.
for path in reversed(list(written)):
if path.read_bytes() != written[path]:
raise RuntimeError('Concurrent edit blocks automatic rollback: ' + str(path)) from None
st = metadata[path]
atomic(path, originals[path], st.st_mode & 0o777, st.st_uid, st.st_gid)
for path in reversed(created):
path.unlink()
if managed.exists():
managed.rmdir()
managed_scope.invalidate_managed_cache()
invalidate_env_file_cache()
raise
if __name__ == '__main__':
main()