"""Install the versioned Fmode bridge into a user's configured Hermes data directory.""" from __future__ import annotations import argparse from contextlib import contextmanager from datetime import datetime, timezone import hashlib import json import os from pathlib import Path, PurePosixPath import shutil import shlex import tempfile import time import yaml ENV_KEYS = ('MATRIX_HOMESERVER', 'MATRIX_USER_ID', 'MATRIX_PASSWORD', 'MATRIX_HOME_ROOM', 'MATRIX_REACTIONS', 'MATRIX_REQUIRE_MENTION', 'MATRIX_ALLOWED_USERS', 'MATRIX_MAX_MEDIA_BYTES', 'MATRIX_E2EE_MODE', 'AGENT_STATUS_HEARTBEAT', 'AGENT_STATUS_JITTER', 'AGENT_ID', 'AGENT_FUNCTION_ID', 'FMODE_SESSION_TOKEN') DIRECTORIES = ('cache', 'sessions', 'work', 'work/tasks', 'work/uploads', 'work/deliverables', 'cache/regenerable', 'skills', 'skills/platform', 'skills/custom', 'plugins', 'scripts', 'logs', '.fmode-media-patch', '.fmode-onboarding') # Platform skills are root-owned so the hermes user (uid 10000) can read but not rewrite them; # Hermes writes skills via temp file + rename, so the directory itself must be non-writable too. # 'skills' itself must stay hermes-owned: mkdir(parents=True) would otherwise leave it root-owned # on a fresh home, and hermes could no longer create custom skills (实测于方案二 T6, 2026-12-01)。 ROOT_OWNED = ('skills/platform',) def read_env(path: Path) -> dict: if not path.is_file(): return {} return dict(line.split('=', 1) for line in path.read_text(encoding='utf-8').splitlines() if '=' in line and not line.lstrip().startswith('#')) def checked_path(root: Path, relative: str) -> Path: parts = PurePosixPath(relative) if parts.is_absolute() or '..' in parts.parts or '\\' in relative or not parts.parts: raise ValueError('接入包路径无效: ' + relative) target = root.joinpath(*parts.parts) if not target.resolve().is_relative_to(root.resolve()): raise ValueError('目标路径越界: ' + relative) if any(p.is_symlink() for p in [target, *target.parents] if p != root.parent): raise ValueError('接入目标不支持符号链接: ' + relative) return target def merge_config(config: dict, patch: dict) -> dict: # Copy only bridge-owned settings. Never replace the model, provider, terminal or sessions. config = json.loads(json.dumps(config)) plugins = config.setdefault('plugins', {}) enabled = plugins.setdefault('enabled', []) if not isinstance(enabled, list): raise ValueError('plugins.enabled 应为列表,原配置未改动') for plugin in patch['plugins']: if plugin not in enabled: enabled.append(plugin) hooks = config.setdefault('hooks', {}) for event, incoming in patch['hooks'].items(): existing = hooks.setdefault(event, []) if not isinstance(existing, list): raise ValueError('hooks.' + event + ' 应为列表,原配置未改动') for item in incoming: # Upgrade this bridge's command, retaining unrelated user hooks and their order. existing[:] = [old for old in existing if not isinstance(old, dict) or old.get('command') != item['command']] existing.append(item) config.setdefault('platforms', {}).setdefault('matrix', {}).setdefault('typing_indicator', True) # Hermes 0.21.3 lets an explicit `enabled: false` override MATRIX_* credentials, # which would leave the App channel silently offline. Other platforms are untouched. if config['platforms']['matrix'].get('enabled') is False: del config['platforms']['matrix']['enabled'] return config @contextmanager def installation_lock(home: Path): home.mkdir(parents=True, exist_ok=True) lock_path = checked_path(home, '.fmode-onboarding-install.lock') with lock_path.open('a+b') as stream: if os.name == 'nt': import msvcrt if stream.tell() == 0: stream.write(b'0') stream.flush() stream.seek(0) msvcrt.locking(stream.fileno(), msvcrt.LK_LOCK, 1) else: import fcntl fcntl.flock(stream.fileno(), fcntl.LOCK_EX) try: yield finally: if os.name == 'nt': stream.seek(0) msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1) else: fcntl.flock(stream.fileno(), fcntl.LOCK_UN) def install(package: Path, home: Path, environment: dict) -> dict: with installation_lock(home): return _install_locked(package, home, environment) def _install_locked(package: Path, home: Path, environment: dict) -> dict: manifest = json.loads((package / 'manifest.json').read_text(encoding='utf-8')) config_path = checked_path(home, 'config.yaml') config = yaml.safe_load(config_path.read_text(encoding='utf-8')) if config_path.is_file() else {} if config is None: config = {} if not isinstance(config, dict): raise ValueError('config.yaml 格式不受支持,原配置未改动') old_env = read_env(checked_path(home, '.env')) new_env = {key: str(environment.get(key, old_env.get(key, ''))) for key in ENV_KEYS} for key in ('MATRIX_HOMESERVER', 'MATRIX_USER_ID', 'MATRIX_PASSWORD', 'MATRIX_HOME_ROOM', 'MATRIX_ALLOWED_USERS', 'AGENT_ID', 'FMODE_SESSION_TOKEN'): if not new_env[key] or '\n' in new_env[key] or '\r' in new_env[key]: raise ValueError('缺少或无效的接入参数: ' + key) if old_env.get('AGENT_ID') and old_env['AGENT_ID'] != new_env['AGENT_ID']: raise ValueError('现有数据目录属于其他容器身份,请使用独立目录,未覆盖原数据') model = config.get('model', {}) model = model if isinstance(model, dict) else {} model_credentials = bool(model.get('api_key') or any(old_env.get(k) or environment.get(k) for k in ( 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'OPENROUTER_API_KEY', 'GLM_API_KEY'))) if not (model_credentials or (home / 'auth.json').is_file() or model.get('provider') in ('ollama', 'lmstudio')): raise ValueError('请先在自己的 Hermes 中配置可用模型(hermes setup);Fmode 不提供或复制平台模型凭据') config_version = config.get('_config_version') if not isinstance(config_version, int) or config_version < 12: raise ValueError('Hermes 配置版本缺失或过旧,请先使用 hermes setup 完成当前运行时配置,原文件未修改') allowlist_path = checked_path(home, 'shell-hooks-allowlist.json') allowlist = json.loads(allowlist_path.read_text(encoding='utf-8')) if allowlist_path.is_file() else {'approvals': []} if not isinstance(allowlist, dict) or not isinstance(allowlist.get('approvals'), list): raise ValueError('现有 hooks 许可文件格式无效,原文件未修改') pending = [] for relative, expected in manifest['files'].items(): source = checked_path(package / 'payload', relative) target = checked_path(home, relative) data = source.read_bytes() if hashlib.sha256(data).hexdigest() != expected: raise ValueError('接入包文件摘要不匹配: ' + relative) pending.append((relative, target, data)) updated_config = merge_config(config, manifest['config']) env_lines = (home / '.env').read_text(encoding='utf-8').splitlines() if (home / '.env').is_file() else [] env_lines = [line for line in env_lines if line.split('=', 1)[0] not in new_env] env_lines += [key + '=' + value for key, value in new_env.items() if value] # Validate everything above before changing the user's directory. home.mkdir(parents=True, exist_ok=True) for relative in DIRECTORIES: directory = checked_path(home, relative) directory.mkdir(parents=True, exist_ok=True) if hasattr(os, 'geteuid') and os.geteuid() == 0: if relative in ROOT_OWNED: os.chown(directory, 0, 0) os.chmod(directory, 0o755) else: os.chown(directory, 10000, 10000) backup = home / '.fmode-onboarding' / ('backup-' + time.strftime('%Y%m%d%H%M%S') + '-' + str(os.getpid())) changed = [] def put(relative: str, target: Path, data: bytes, mode: int = 0o644) -> None: if target.is_file() and target.read_bytes() == data: return if target.exists(): saved = backup / relative saved.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(target, saved) target.parent.mkdir(parents=True, exist_ok=True) fd, temporary = tempfile.mkstemp(prefix='.fmode-install-', dir=target.parent) try: with os.fdopen(fd, 'wb') as stream: stream.write(data) os.chmod(temporary, mode) if hasattr(os, 'geteuid') and os.geteuid() == 0: owner = 0 if any(relative.startswith(root + '/') for root in ROOT_OWNED) else 10000 os.chown(temporary, owner, owner) os.replace(temporary, target) finally: if os.path.exists(temporary): os.unlink(temporary) changed.append(relative) for relative, target, data in pending: put(relative, target, data, 0o755 if relative.endswith('.sh') else 0o644) # Hermes 0.21.3 records consent per (event, command). Approve only this package's # exact commands; do not turn on global hooks_auto_accept or change user approvals. for event, entries in manifest['config']['hooks'].items(): for item in entries: command = item['command'] script = next((part for part in shlex.split(command) if part.endswith(('.py', '.sh'))), None) mtime = None if script and Path(script).is_file(): mtime = datetime.fromtimestamp(Path(script).stat().st_mtime, timezone.utc).isoformat().replace('+00:00', 'Z') existing = next((entry for entry in allowlist['approvals'] if isinstance(entry, dict) and entry.get('event') == event and entry.get('command') == command), None) if existing and existing.get('script_mtime_at_approval') == mtime: continue entry = {'event': event, 'command': command, 'approved_at': datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'), 'script_mtime_at_approval': mtime} if existing: allowlist['approvals'].remove(existing) allowlist['approvals'].append(entry) put('shell-hooks-allowlist.json', allowlist_path, (json.dumps(allowlist, ensure_ascii=False, indent=2) + '\n').encode(), 0o600) put('.env', home / '.env', ('\n'.join(env_lines) + '\n').encode(), 0o600) put('config.yaml', config_path, yaml.safe_dump(updated_config, allow_unicode=True, sort_keys=False).encode(), 0o600) receipt = {'version': manifest['version'], 'agentId': new_env['AGENT_ID'], 'files': manifest['files']} put('.fmode-onboarding/installed.json', home / '.fmode-onboarding/installed.json', (json.dumps(receipt, ensure_ascii=False, indent=2) + '\n').encode(), 0o600) return {'version': manifest['version'], 'agentId': new_env['AGENT_ID'], 'changed': changed, 'backup': str(backup) if backup.exists() else None, 'modelConfigPreserved': True} def main() -> None: parser = argparse.ArgumentParser() parser.add_argument('--home', default='/opt/data') parser.add_argument('--env-file') args = parser.parse_args() environment = dict(os.environ) if args.env_file: environment.update(read_env(Path(args.env_file))) print(json.dumps(install(Path(__file__).resolve().parent, Path(args.home), environment), ensure_ascii=False)) if __name__ == '__main__': main()