| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238 |
- """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',
- # 凭证(2026-12-04):容器用 FMODE_ACCESS_TOKEN;FMODE_SESSION_TOKEN 为旧容器兼容,可缺
- 'FMODE_ACCESS_TOKEN', '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']
- # 对话行为对齐(2026-12-03,方案 A / 用户裁决):把忙时输入策略显式写成与平台容器一致的值。
- # 标识:FmodeBridgeOwned.busy_input_mode(与线上容器 2026-11-13 实测值 interrupt 一致)。
- # 公共配置项(display.busy_input_mode,合法值 interrupt/queue/steer),不是源码修改;
- # 显式写入是为了让「本机接入」不依赖各机器上有没有被改过,行为与线上容器对齐。
- display = config.setdefault('display', {})
- if isinstance(display, dict) and not display.get('busy_input_mode'):
- display['busy_input_mode'] = (patch.get('display') or {}).get('busy_input_mode', 'interrupt')
- 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_ACCESS_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()
|