install.py 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. """Install the versioned Fmode bridge into a user's configured Hermes data directory."""
  2. from __future__ import annotations
  3. import argparse
  4. from contextlib import contextmanager
  5. from datetime import datetime, timezone
  6. import hashlib
  7. import json
  8. import os
  9. from pathlib import Path, PurePosixPath
  10. import shutil
  11. import shlex
  12. import tempfile
  13. import time
  14. import yaml
  15. ENV_KEYS = ('MATRIX_HOMESERVER', 'MATRIX_USER_ID', 'MATRIX_PASSWORD', 'MATRIX_HOME_ROOM',
  16. 'MATRIX_REACTIONS', 'MATRIX_REQUIRE_MENTION', 'MATRIX_ALLOWED_USERS',
  17. 'MATRIX_MAX_MEDIA_BYTES', 'MATRIX_E2EE_MODE', 'AGENT_STATUS_HEARTBEAT',
  18. 'AGENT_STATUS_JITTER', 'AGENT_ID', 'AGENT_FUNCTION_ID', 'FMODE_SESSION_TOKEN')
  19. DIRECTORIES = ('cache', 'sessions', 'work', 'work/tasks', 'work/uploads', 'work/deliverables',
  20. 'cache/regenerable', 'skills', 'skills/platform', 'skills/custom', 'plugins', 'scripts', 'logs',
  21. '.fmode-media-patch', '.fmode-onboarding')
  22. # Platform skills are root-owned so the hermes user (uid 10000) can read but not rewrite them;
  23. # Hermes writes skills via temp file + rename, so the directory itself must be non-writable too.
  24. # 'skills' itself must stay hermes-owned: mkdir(parents=True) would otherwise leave it root-owned
  25. # on a fresh home, and hermes could no longer create custom skills (实测于方案二 T6, 2026-12-01)。
  26. ROOT_OWNED = ('skills/platform',)
  27. def read_env(path: Path) -> dict:
  28. if not path.is_file():
  29. return {}
  30. return dict(line.split('=', 1) for line in path.read_text(encoding='utf-8').splitlines()
  31. if '=' in line and not line.lstrip().startswith('#'))
  32. def checked_path(root: Path, relative: str) -> Path:
  33. parts = PurePosixPath(relative)
  34. if parts.is_absolute() or '..' in parts.parts or '\\' in relative or not parts.parts:
  35. raise ValueError('接入包路径无效: ' + relative)
  36. target = root.joinpath(*parts.parts)
  37. if not target.resolve().is_relative_to(root.resolve()):
  38. raise ValueError('目标路径越界: ' + relative)
  39. if any(p.is_symlink() for p in [target, *target.parents] if p != root.parent):
  40. raise ValueError('接入目标不支持符号链接: ' + relative)
  41. return target
  42. def merge_config(config: dict, patch: dict) -> dict:
  43. # Copy only bridge-owned settings. Never replace the model, provider, terminal or sessions.
  44. config = json.loads(json.dumps(config))
  45. plugins = config.setdefault('plugins', {})
  46. enabled = plugins.setdefault('enabled', [])
  47. if not isinstance(enabled, list):
  48. raise ValueError('plugins.enabled 应为列表,原配置未改动')
  49. for plugin in patch['plugins']:
  50. if plugin not in enabled:
  51. enabled.append(plugin)
  52. hooks = config.setdefault('hooks', {})
  53. for event, incoming in patch['hooks'].items():
  54. existing = hooks.setdefault(event, [])
  55. if not isinstance(existing, list):
  56. raise ValueError('hooks.' + event + ' 应为列表,原配置未改动')
  57. for item in incoming:
  58. # Upgrade this bridge's command, retaining unrelated user hooks and their order.
  59. existing[:] = [old for old in existing if not isinstance(old, dict) or old.get('command') != item['command']]
  60. existing.append(item)
  61. config.setdefault('platforms', {}).setdefault('matrix', {}).setdefault('typing_indicator', True)
  62. # Hermes 0.21.3 lets an explicit `enabled: false` override MATRIX_* credentials,
  63. # which would leave the App channel silently offline. Other platforms are untouched.
  64. if config['platforms']['matrix'].get('enabled') is False:
  65. del config['platforms']['matrix']['enabled']
  66. # 对话行为对齐(2026-12-03,方案 A / 用户裁决):把忙时输入策略显式写成与平台容器一致的值。
  67. # 标识:FmodeBridgeOwned.busy_input_mode(与线上容器 2026-11-13 实测值 interrupt 一致)。
  68. # 公共配置项(display.busy_input_mode,合法值 interrupt/queue/steer),不是源码修改;
  69. # 显式写入是为了让「本机接入」不依赖各机器上有没有被改过,行为与线上容器对齐。
  70. display = config.setdefault('display', {})
  71. if isinstance(display, dict) and not display.get('busy_input_mode'):
  72. display['busy_input_mode'] = (patch.get('display') or {}).get('busy_input_mode', 'interrupt')
  73. return config
  74. @contextmanager
  75. def installation_lock(home: Path):
  76. home.mkdir(parents=True, exist_ok=True)
  77. lock_path = checked_path(home, '.fmode-onboarding-install.lock')
  78. with lock_path.open('a+b') as stream:
  79. if os.name == 'nt':
  80. import msvcrt
  81. if stream.tell() == 0:
  82. stream.write(b'0')
  83. stream.flush()
  84. stream.seek(0)
  85. msvcrt.locking(stream.fileno(), msvcrt.LK_LOCK, 1)
  86. else:
  87. import fcntl
  88. fcntl.flock(stream.fileno(), fcntl.LOCK_EX)
  89. try:
  90. yield
  91. finally:
  92. if os.name == 'nt':
  93. stream.seek(0)
  94. msvcrt.locking(stream.fileno(), msvcrt.LK_UNLCK, 1)
  95. else:
  96. fcntl.flock(stream.fileno(), fcntl.LOCK_UN)
  97. def install(package: Path, home: Path, environment: dict) -> dict:
  98. with installation_lock(home):
  99. return _install_locked(package, home, environment)
  100. def _install_locked(package: Path, home: Path, environment: dict) -> dict:
  101. manifest = json.loads((package / 'manifest.json').read_text(encoding='utf-8'))
  102. config_path = checked_path(home, 'config.yaml')
  103. config = yaml.safe_load(config_path.read_text(encoding='utf-8')) if config_path.is_file() else {}
  104. if config is None:
  105. config = {}
  106. if not isinstance(config, dict):
  107. raise ValueError('config.yaml 格式不受支持,原配置未改动')
  108. old_env = read_env(checked_path(home, '.env'))
  109. new_env = {key: str(environment.get(key, old_env.get(key, ''))) for key in ENV_KEYS}
  110. for key in ('MATRIX_HOMESERVER', 'MATRIX_USER_ID', 'MATRIX_PASSWORD', 'MATRIX_HOME_ROOM',
  111. 'MATRIX_ALLOWED_USERS', 'AGENT_ID', 'FMODE_SESSION_TOKEN'):
  112. if not new_env[key] or '\n' in new_env[key] or '\r' in new_env[key]:
  113. raise ValueError('缺少或无效的接入参数: ' + key)
  114. if old_env.get('AGENT_ID') and old_env['AGENT_ID'] != new_env['AGENT_ID']:
  115. raise ValueError('现有数据目录属于其他容器身份,请使用独立目录,未覆盖原数据')
  116. model = config.get('model', {})
  117. model = model if isinstance(model, dict) else {}
  118. model_credentials = bool(model.get('api_key') or any(old_env.get(k) or environment.get(k) for k in (
  119. 'OPENAI_API_KEY', 'ANTHROPIC_API_KEY', 'OPENROUTER_API_KEY', 'GLM_API_KEY')))
  120. if not (model_credentials or (home / 'auth.json').is_file() or model.get('provider') in ('ollama', 'lmstudio')):
  121. raise ValueError('请先在自己的 Hermes 中配置可用模型(hermes setup);Fmode 不提供或复制平台模型凭据')
  122. config_version = config.get('_config_version')
  123. if not isinstance(config_version, int) or config_version < 12:
  124. raise ValueError('Hermes 配置版本缺失或过旧,请先使用 hermes setup 完成当前运行时配置,原文件未修改')
  125. allowlist_path = checked_path(home, 'shell-hooks-allowlist.json')
  126. allowlist = json.loads(allowlist_path.read_text(encoding='utf-8')) if allowlist_path.is_file() else {'approvals': []}
  127. if not isinstance(allowlist, dict) or not isinstance(allowlist.get('approvals'), list):
  128. raise ValueError('现有 hooks 许可文件格式无效,原文件未修改')
  129. pending = []
  130. for relative, expected in manifest['files'].items():
  131. source = checked_path(package / 'payload', relative)
  132. target = checked_path(home, relative)
  133. data = source.read_bytes()
  134. if hashlib.sha256(data).hexdigest() != expected:
  135. raise ValueError('接入包文件摘要不匹配: ' + relative)
  136. pending.append((relative, target, data))
  137. updated_config = merge_config(config, manifest['config'])
  138. env_lines = (home / '.env').read_text(encoding='utf-8').splitlines() if (home / '.env').is_file() else []
  139. env_lines = [line for line in env_lines if line.split('=', 1)[0] not in new_env]
  140. env_lines += [key + '=' + value for key, value in new_env.items() if value]
  141. # Validate everything above before changing the user's directory.
  142. home.mkdir(parents=True, exist_ok=True)
  143. for relative in DIRECTORIES:
  144. directory = checked_path(home, relative)
  145. directory.mkdir(parents=True, exist_ok=True)
  146. if hasattr(os, 'geteuid') and os.geteuid() == 0:
  147. if relative in ROOT_OWNED:
  148. os.chown(directory, 0, 0)
  149. os.chmod(directory, 0o755)
  150. else:
  151. os.chown(directory, 10000, 10000)
  152. backup = home / '.fmode-onboarding' / ('backup-' + time.strftime('%Y%m%d%H%M%S') + '-' + str(os.getpid()))
  153. changed = []
  154. def put(relative: str, target: Path, data: bytes, mode: int = 0o644) -> None:
  155. if target.is_file() and target.read_bytes() == data:
  156. return
  157. if target.exists():
  158. saved = backup / relative
  159. saved.parent.mkdir(parents=True, exist_ok=True)
  160. shutil.copy2(target, saved)
  161. target.parent.mkdir(parents=True, exist_ok=True)
  162. fd, temporary = tempfile.mkstemp(prefix='.fmode-install-', dir=target.parent)
  163. try:
  164. with os.fdopen(fd, 'wb') as stream:
  165. stream.write(data)
  166. os.chmod(temporary, mode)
  167. if hasattr(os, 'geteuid') and os.geteuid() == 0:
  168. owner = 0 if any(relative.startswith(root + '/') for root in ROOT_OWNED) else 10000
  169. os.chown(temporary, owner, owner)
  170. os.replace(temporary, target)
  171. finally:
  172. if os.path.exists(temporary):
  173. os.unlink(temporary)
  174. changed.append(relative)
  175. for relative, target, data in pending:
  176. put(relative, target, data, 0o755 if relative.endswith('.sh') else 0o644)
  177. # Hermes 0.21.3 records consent per (event, command). Approve only this package's
  178. # exact commands; do not turn on global hooks_auto_accept or change user approvals.
  179. for event, entries in manifest['config']['hooks'].items():
  180. for item in entries:
  181. command = item['command']
  182. script = next((part for part in shlex.split(command) if part.endswith(('.py', '.sh'))), None)
  183. mtime = None
  184. if script and Path(script).is_file():
  185. mtime = datetime.fromtimestamp(Path(script).stat().st_mtime, timezone.utc).isoformat().replace('+00:00', 'Z')
  186. existing = next((entry for entry in allowlist['approvals'] if isinstance(entry, dict)
  187. and entry.get('event') == event and entry.get('command') == command), None)
  188. if existing and existing.get('script_mtime_at_approval') == mtime:
  189. continue
  190. entry = {'event': event, 'command': command,
  191. 'approved_at': datetime.now(timezone.utc).isoformat().replace('+00:00', 'Z'),
  192. 'script_mtime_at_approval': mtime}
  193. if existing:
  194. allowlist['approvals'].remove(existing)
  195. allowlist['approvals'].append(entry)
  196. put('shell-hooks-allowlist.json', allowlist_path,
  197. (json.dumps(allowlist, ensure_ascii=False, indent=2) + '\n').encode(), 0o600)
  198. put('.env', home / '.env', ('\n'.join(env_lines) + '\n').encode(), 0o600)
  199. put('config.yaml', config_path, yaml.safe_dump(updated_config, allow_unicode=True, sort_keys=False).encode(), 0o600)
  200. receipt = {'version': manifest['version'], 'agentId': new_env['AGENT_ID'], 'files': manifest['files']}
  201. put('.fmode-onboarding/installed.json', home / '.fmode-onboarding/installed.json',
  202. (json.dumps(receipt, ensure_ascii=False, indent=2) + '\n').encode(), 0o600)
  203. return {'version': manifest['version'], 'agentId': new_env['AGENT_ID'], 'changed': changed,
  204. 'backup': str(backup) if backup.exists() else None, 'modelConfigPreserved': True}
  205. def main() -> None:
  206. parser = argparse.ArgumentParser()
  207. parser.add_argument('--home', default='/opt/data')
  208. parser.add_argument('--env-file')
  209. args = parser.parse_args()
  210. environment = dict(os.environ)
  211. if args.env_file:
  212. environment.update(read_env(Path(args.env_file)))
  213. print(json.dumps(install(Path(__file__).resolve().parent, Path(args.home), environment), ensure_ascii=False))
  214. if __name__ == '__main__':
  215. main()