amangs commited on
Commit
5dfb831
·
verified ·
1 Parent(s): fee644f

Deploy Hermes Agent with Web UI from openlaw/hermes

Browse files
Files changed (8) hide show
  1. Dockerfile +102 -40
  2. README.md +4 -5
  3. backup_manager.py +0 -293
  4. config/config.yaml +99 -0
  5. entrypoint.sh +725 -16
  6. requirements.txt +36 -0
  7. src/__init__.py +0 -0
  8. src/data_sync.py +397 -0
Dockerfile CHANGED
@@ -1,51 +1,113 @@
1
- FROM node:26.3.0-alpine
2
 
3
- # Install Python 3, build tools, sqlite3 CLI, and py3-virtualenv
4
- RUN apk add --no-cache \
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
  git \
6
- python3 \
7
- py3-pip \
8
- py3-virtualenv \
9
- make \
10
- g++ \
11
- sqlite
12
 
13
- WORKDIR /app
 
 
 
 
 
 
 
 
 
 
14
 
15
- # Download FreeLLMAPI release (latest)
16
- ARG FREELLMAPI_VERSION="v0.9.2"
17
- RUN apk add --no-cache curl && \
18
- curl -L "https://github.com/tashfeenahmed/freellmapi/archive/refs/tags/${FREELLMAPI_VERSION}.tar.gz" | \
19
- tar xz --strip-components=1
20
 
21
- # Install Node dependencies and build
22
- RUN npm install && npm run build
23
 
24
- # Ensure data directory exists
25
- RUN mkdir -p /app/server/data
 
26
 
27
- # Create Python virtual environment and install huggingface-hub
28
- RUN python3 -m venv /opt/venv && \
29
- /opt/venv/bin/pip install --upgrade pip && \
30
- /opt/venv/bin/pip install huggingface-hub
 
 
 
 
 
31
 
32
- # Copy backup manager and entrypoint
33
- COPY backup_manager.py /app/backup_manager.py
34
- COPY entrypoint.sh /entrypoint.sh
35
- RUN chmod +x /entrypoint.sh
36
 
37
- EXPOSE 7860
 
 
 
 
 
 
 
 
 
 
 
38
 
39
- # Default environment variables
40
- ENV PORT=7860
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
41
  ENV NODE_ENV=production
42
- ENV DB_PATH=/app/server/data/freeapi.db
43
- ENV BACKUP_MODE=scheduled
44
- ENV BACKUP_INTERVAL=300
45
- ENV REALTIME_CHECK_INTERVAL=30
46
- ENV MIN_BACKUP_INTERVAL=60
47
- ENV KEEP_BACKUPS=10
48
- # Add venv to PATH so entrypoint can use python3/pip directly
49
- ENV PATH="/opt/venv/bin:$PATH"
50
-
51
- ENTRYPOINT ["/entrypoint.sh"]
 
1
+ FROM python:3.11-slim
2
 
3
+ LABEL maintainer="Hermes Agent Community"
4
+ LABEL version="0.10.0"
5
+ LABEL description="Hermes Agent v0.10.0 with Web UI on Hugging Face Spaces"
6
+
7
+ # ==================== 环境变量 ====================
8
+ ENV PYTHONUNBUFFERED=1
9
+ ENV DEBIAN_FRONTEND=noninteractive
10
+ ENV HERMES_HOME=/data/.hermes
11
+ ENV PYTHONPATH=/app
12
+
13
+ # BFF Server 环境变量(构建阶段)
14
+ ENV PORT=7860
15
+ ENV UPSTREAM=http://127.0.0.1:8642
16
+ ENV HERMES_BIN=/usr/local/bin/hermes
17
+ # 注意:NODE_ENV=production 不能在此设置!
18
+ # npm install 在 NODE_ENV=production 时会跳过 devDependencies,
19
+ # 导致 vue-tsc 等构建工具缺失。NODE_ENV 在运行时阶段再设置。
20
+
21
+ # ==================== 系统依赖 ====================
22
+ RUN apt-get update && apt-get install -y \
23
+ make gcc g++ \
24
+ ffmpeg \
25
  git \
26
+ curl \
27
+ unzip \
28
+ ca-certificates \
29
+ && rm -rf /var/lib/apt/lists/*
 
 
30
 
31
+ # ==================== Node.js v23 ====================
32
+ # hermes-web-ui 要求 Node >= 23.0.0
33
+ RUN ARCH=$(dpkg --print-architecture) \
34
+ && if [ "$ARCH" = "amd64" ]; then NODE_ARCH="x64"; else NODE_ARCH="$ARCH"; fi \
35
+ && echo "Installing Node.js v23.11.0 for ${NODE_ARCH}" \
36
+ && curl -fsSL "https://nodejs.org/dist/v23.11.0/node-v23.11.0-linux-${NODE_ARCH}.tar.gz" \
37
+ -o /tmp/node.tar.gz \
38
+ && tar -xzf /tmp/node.tar.gz -C /usr/local --strip-components=1 \
39
+ && rm -f /tmp/node.tar.gz \
40
+ && node --version \
41
+ && npm --version
42
 
43
+ # ==================== 工具安装 ====================
44
+ # yq: 运行时修改 config.yaml
45
+ RUN curl -sL https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 -o /usr/bin/yq && \
46
+ chmod +x /usr/bin/yq
 
47
 
48
+ # ==================== Code Server ====================
49
+ RUN curl -fsSL https://code-server.dev/install.sh | sh
50
 
51
+ # ==================== Python 依赖 ====================
52
+ COPY requirements.txt /tmp/
53
+ RUN pip install --no-cache-dir --prefer-binary -r /tmp/requirements.txt
54
 
55
+ # ==================== Hermes Agent ====================
56
+ # 克隆并安装 Hermes Agent(不再构建内置 Dashboard 前端,由 hermes-web-ui 替代)
57
+ # 注意:必须保留源码到 /usr/local/lib/hermes-agent,不能删除!
58
+ # hermes-web-ui 的桥接程序 (hermes_bridge.py) 需要 run_agent.py 来创建 Unix Socket
59
+ RUN git clone --depth 1 https://github.com/NousResearch/hermes-agent.git /usr/local/lib/hermes-agent && \
60
+ pip install uv && \
61
+ cd /usr/local/lib/hermes-agent && \
62
+ uv pip install --system -e .[all] && \
63
+ rm -rf /root/.cache/pip
64
 
65
+ # Playwright 浏览器(Hermes Agent 工具调用需要)
66
+ RUN npx playwright install chromium --with-deps --only-shell && \
67
+ rm -rf /var/lib/apt/lists/* /var/cache/apt/archives/*
 
68
 
69
+ # ==================== Hermes Web UI ====================
70
+ # 直接安装 npm 预构建包(已包含编译好的 dist/ 目录),跳过源码编译节省 3-8 分钟
71
+ # 默认版本 0.6.3,可通过 --build-arg HERMES_WEB_UI_VERSION=新版本 覆盖
72
+ # HF Spaces: 在 Settings -> Repository secrets 添加同名变量即可注入
73
+ # ARG HERMES_WEB_UI_VERSION=0.6.47
74
+ ARG HERMES_WEB_UI_VERSION=0.7.12
75
+ RUN mkdir -p /opt/hermes-web-ui && cd /opt/hermes-web-ui && \
76
+ npm init -y && \
77
+ npm install hermes-web-ui@${HERMES_WEB_UI_VERSION} && \
78
+ ln -sf node_modules/hermes-web-ui/dist dist && \
79
+ ln -sf node_modules/hermes-web-ui/package.json package.json && \
80
+ rm -rf /root/.npm
81
 
82
+ # ==================== 应用代码 ====================
83
+ WORKDIR /app
84
+
85
+ COPY src/ /app/src/
86
+ COPY entrypoint.sh /app/
87
+ COPY config/config.yaml /data/.hermes/config.yaml
88
+
89
+ # 创建数据目录
90
+ RUN mkdir -p /data/.hermes /data/.hermes-web-ui /app/logs && \
91
+ chmod +x /app/entrypoint.sh
92
+
93
+ # 设置非 root 用户(Hugging Face Spaces 要求)
94
+ RUN useradd -m -u 1000 appuser && \
95
+ ln -sf /data/.hermes /home/appuser/.hermes && \
96
+ chown -R appuser:appuser /data /opt/hermes-web-ui /app
97
+
98
+ USER appuser
99
+
100
+ # ==================== 运行时环境变量 ====================
101
+ # 构建阶段不设 NODE_ENV=production(��导致 npm install 跳过 devDependencies)
102
+ # 此处设置,仅影响运行时行为
103
  ENV NODE_ENV=production
104
+
105
+ # 7860: BFF Server (Web UI 入口,HF Spaces 要求)
106
+ # 8642: Gateway API Server (BFF 的上游代理目标,仅容器内部)
107
+ # 8443: Code Server (容器内部访问)
108
+ EXPOSE 7860 8443
109
+
110
+ HEALTHCHECK --interval=30s --timeout=10s --start-period=90s --retries=3 \
111
+ CMD curl -f http://localhost:7860/health || exit 1
112
+
113
+ ENTRYPOINT ["/app/entrypoint.sh"]
README.md CHANGED
@@ -1,11 +1,10 @@
1
  ---
2
- title: Api
3
- emoji: 📈
4
- colorFrom: green
5
- colorTo: indigo
6
  sdk: docker
7
  pinned: false
8
- license: apache-2.0
9
  ---
10
 
11
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
 
1
  ---
2
+ title: Hermes
3
+ emoji: 🐢
4
+ colorFrom: yellow
5
+ colorTo: gray
6
  sdk: docker
7
  pinned: false
 
8
  ---
9
 
10
  Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference
backup_manager.py DELETED
@@ -1,293 +0,0 @@
1
- #!/usr/bin/env python3
2
- import os
3
- import sys
4
- import time
5
- import hashlib
6
- import subprocess
7
- import tempfile
8
- from datetime import datetime
9
- from huggingface_hub import HfApi, hf_hub_download
10
- from huggingface_hub.utils import EntryNotFoundError
11
-
12
- # ==================== Environment Configuration ====================
13
- REPO_ID = os.environ.get("HF_DATASET_REPO")
14
- TOKEN = os.environ.get("HF_TOKEN")
15
- DB_PATH = os.environ.get("DB_PATH", "/app/server/data/freeapi.db")
16
- BACKUP_MODE = os.environ.get("BACKUP_MODE", "scheduled").lower()
17
- BACKUP_INTERVAL = int(os.environ.get("BACKUP_INTERVAL", "300"))
18
- CHECK_INTERVAL = int(os.environ.get("REALTIME_CHECK_INTERVAL", "30"))
19
- MIN_INTERVAL = int(os.environ.get("MIN_BACKUP_INTERVAL", "60"))
20
- KEEP_BACKUPS = int(os.environ.get("KEEP_BACKUPS", "10"))
21
-
22
- DB_FILENAME = os.path.basename(DB_PATH) # "freeapi.db"
23
-
24
- api = HfApi(token=TOKEN) if TOKEN else None
25
-
26
-
27
- def log(msg: str):
28
- print(f"[BackupManager] {msg}", flush=True)
29
-
30
-
31
- def find_db_file():
32
- """
33
- Detect actual database file path.
34
- """
35
- candidates = [
36
- DB_PATH,
37
- f"/app/server/data/{DB_FILENAME}",
38
- f"/app/data/{DB_FILENAME}",
39
- f"/app/server/dist/data/{DB_FILENAME}",
40
- os.path.join(os.getcwd(), "server", "data", DB_FILENAME),
41
- os.path.join(os.getcwd(), "data", DB_FILENAME),
42
- os.path.join(os.getcwd(), DB_FILENAME),
43
- ]
44
-
45
- for path in candidates:
46
- if path and os.path.isfile(path):
47
- log(f"Found database at: {path}")
48
- return path
49
-
50
- # Directory scan
51
- for root_dir in ["/app", "/app/server", os.getcwd()]:
52
- if os.path.isdir(root_dir):
53
- for root, dirs, files in os.walk(root_dir):
54
- if DB_FILENAME in files:
55
- path = os.path.join(root, DB_FILENAME)
56
- log(f"Found database by scan at: {path}")
57
- return path
58
-
59
- return None
60
-
61
-
62
- def get_file_stat(path: str):
63
- if not os.path.exists(path):
64
- return None
65
- st = os.stat(path)
66
- return (st.st_size, st.st_mtime)
67
-
68
-
69
- def create_consistent_snapshot(src: str, dst: str) -> bool:
70
- """
71
- Use sqlite3 .backup to create a consistent snapshot avoiding concurrency locks.
72
- """
73
- try:
74
- result = subprocess.run(
75
- ["sqlite3", src, f".backup {dst}"],
76
- capture_output=True, text=True, timeout=30, check=True
77
- )
78
- if result.returncode == 0:
79
- return True
80
- except FileNotFoundError:
81
- log("sqlite3 CLI not found, falling back to file copy")
82
- except Exception as e:
83
- log(f"sqlite3 .backup warning: {e}, falling back to file copy")
84
-
85
- try:
86
- import shutil
87
- shutil.copy2(src, dst)
88
- return True
89
- except Exception as e:
90
- log(f"File copy failed: {e}")
91
- return False
92
-
93
-
94
- def restore() -> bool:
95
- """
96
- Restore database from Hugging Face Dataset:
97
- 1. List historical backups freeapi.db.YYYYMMDD_HHMMSS
98
- 2. Sort by timestamp, select the latest
99
- 3. Download and replace freeapi.db
100
- """
101
- if not REPO_ID or not TOKEN:
102
- log("HF_DATASET_REPO or HF_TOKEN not set, skipping restore")
103
- return False
104
-
105
- data_dir = os.path.dirname(DB_PATH)
106
- os.makedirs(data_dir, exist_ok=True)
107
-
108
- try:
109
- files = api.list_repo_files(repo_id=REPO_ID, repo_type="dataset")
110
- backups = [f for f in files if f.startswith(f"{DB_FILENAME}.") and len(f) > len(DB_FILENAME)]
111
-
112
- if not backups:
113
- log("No existing backup found in dataset, starting fresh")
114
- return False
115
-
116
- backups.sort()
117
- latest_backup = backups[-1]
118
- log(f"Found latest backup: {latest_backup}")
119
-
120
- # Download to data_dir
121
- downloaded = hf_hub_download(
122
- repo_id=REPO_ID,
123
- filename=latest_backup,
124
- repo_type="dataset",
125
- local_dir=data_dir,
126
- token=TOKEN,
127
- local_dir_use_symlinks=False
128
- )
129
-
130
- # Atomic replace to freeapi.db
131
- target = os.path.join(data_dir, DB_FILENAME)
132
- os.replace(downloaded, target)
133
- log(f"Restored database from {latest_backup} to {target}")
134
- return True
135
-
136
- except Exception as e:
137
- log(f"Restore failed: {e}")
138
- return False
139
-
140
-
141
- def upload_file(local_path: str, remote_name: str) -> bool:
142
- if not api or not REPO_ID:
143
- return False
144
- try:
145
- api.upload_file(
146
- path_or_fileobj=local_path,
147
- path_in_repo=remote_name,
148
- repo_id=REPO_ID,
149
- repo_type="dataset",
150
- commit_message=f"Backup {remote_name} @ {datetime.now().isoformat()}"
151
- )
152
- return True
153
- except Exception as e:
154
- log(f"Upload failed for {remote_name}: {e}")
155
- return False
156
-
157
-
158
- def cleanup_old_backups():
159
- """
160
- Clean up old backups:
161
- - Remove legacy main file freeapi.db if present
162
- - Retain latest KEEP_BACKUPS historical versions
163
- """
164
- if not api or not REPO_ID or KEEP_BACKUPS <= 0:
165
- return
166
-
167
- try:
168
- files = api.list_repo_files(repo_id=REPO_ID, repo_type="dataset")
169
-
170
- # Delete old main file if present
171
- if DB_FILENAME in files:
172
- try:
173
- api.delete_file(
174
- path_in_repo=DB_FILENAME,
175
- repo_id=REPO_ID,
176
- repo_type="dataset",
177
- commit_message="Remove legacy main db file"
178
- )
179
- log(f"Removed legacy main file: {DB_FILENAME}")
180
- except Exception as e:
181
- log(f"Failed to remove legacy file: {e}")
182
-
183
- # Clean up historical versions
184
- backups = [f for f in files if f.startswith(f"{DB_FILENAME}.") and len(f) > len(DB_FILENAME)]
185
- backups.sort()
186
-
187
- if len(backups) <= KEEP_BACKUPS:
188
- return
189
-
190
- to_delete = backups[:-KEEP_BACKUPS]
191
- for f in to_delete:
192
- try:
193
- api.delete_file(
194
- path_in_repo=f,
195
- repo_id=REPO_ID,
196
- repo_type="dataset",
197
- commit_message=f"Auto cleanup: remove {f}"
198
- )
199
- log(f"Cleaned up old backup: {f}")
200
- except Exception as e:
201
- log(f"Failed to delete {f}: {e}")
202
- except Exception as e:
203
- log(f"Cleanup scan failed: {e}")
204
-
205
-
206
- def do_backup() -> bool:
207
- """
208
- Execute backup: upload timestamped snapshot to dataset
209
- """
210
- actual_db = find_db_file()
211
- if not actual_db:
212
- log("Database file not found, skipping backup")
213
- return False
214
-
215
- # Create consistent snapshot
216
- fd, snapshot = tempfile.mkstemp(suffix=".db", prefix="freellmapi_")
217
- os.close(fd)
218
-
219
- try:
220
- if not create_consistent_snapshot(actual_db, snapshot):
221
- return False
222
-
223
- # Generate timestamped filename and upload
224
- ts = datetime.now().strftime("%Y%m%d_%H%M%S")
225
- hist_name = f"{DB_FILENAME}.{ts}"
226
-
227
- if upload_file(snapshot, hist_name):
228
- log(f"Uploaded backup: {hist_name}")
229
- cleanup_old_backups()
230
- return True
231
- return False
232
-
233
- finally:
234
- try:
235
- os.unlink(snapshot)
236
- except Exception:
237
- pass
238
-
239
-
240
- def scheduled_daemon():
241
- log(f"Scheduled mode started (interval: {BACKUP_INTERVAL}s)")
242
- while True:
243
- time.sleep(BACKUP_INTERVAL)
244
- log("Scheduled backup triggered")
245
- do_backup()
246
-
247
-
248
- def realtime_daemon():
249
- log(f"Realtime mode started (check: {CHECK_INTERVAL}s, min interval: {MIN_INTERVAL}s)")
250
- last_stat = None
251
- last_backup_time = 0
252
-
253
- while True:
254
- time.sleep(CHECK_INTERVAL)
255
-
256
- actual_db = find_db_file()
257
- if not actual_db:
258
- continue
259
-
260
- curr_stat = get_file_stat(actual_db)
261
- if curr_stat is None:
262
- continue
263
-
264
- if last_stat is not None and curr_stat != last_stat:
265
- now = time.time()
266
- if now - last_backup_time >= MIN_INTERVAL:
267
- log("Database change detected, triggering backup...")
268
- if do_backup():
269
- last_backup_time = now
270
- else:
271
- log("Change detected but within min interval, skipped")
272
-
273
- last_stat = curr_stat
274
-
275
-
276
- def main():
277
- cmd = sys.argv[1] if len(sys.argv) > 1 else "daemon"
278
-
279
- if cmd == "restore":
280
- restore()
281
- elif cmd == "backup":
282
- do_backup()
283
- elif cmd == "daemon":
284
- if BACKUP_MODE == "realtime":
285
- realtime_daemon()
286
- else:
287
- scheduled_daemon()
288
- else:
289
- log(f"Unknown command: {cmd}")
290
-
291
-
292
- if __name__ == "__main__":
293
- main()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
config/config.yaml ADDED
@@ -0,0 +1,99 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hermes Agent Configuration
2
+ # 默认配置 for Hugging Face Spaces deployment
3
+ # 格式来源: cli-config.yaml.example + hermes_cli/config.py
4
+
5
+ # 主模型配置
6
+ model:
7
+ # default: "moonshotai/kimi-k2-thinking"
8
+ default: "deepseek-ai/deepseek-v4-flash"
9
+ provider: "nvidia"
10
+ base_url: "https://integrate.api.nvidia.com/v1"
11
+
12
+ # 辅助模型配置 (per-task overrides)
13
+ auxiliary:
14
+ vision:
15
+ provider: "auto"
16
+ model: ""
17
+ timeout: 120
18
+ download_timeout: 30
19
+ web_extract:
20
+ provider: "auto"
21
+ model: ""
22
+ timeout: 360
23
+ compression:
24
+ provider: "auto"
25
+ model: ""
26
+ timeout: 120
27
+ title_generation:
28
+ provider: "auto"
29
+ model: ""
30
+ timeout: 30
31
+ session_search:
32
+ provider: "auto"
33
+ model: ""
34
+ timeout: 30
35
+ skills_hub:
36
+ provider: "auto"
37
+ model: ""
38
+ timeout: 30
39
+ approval:
40
+ provider: "auto"
41
+ model: ""
42
+ timeout: 30
43
+ mcp:
44
+ provider: "auto"
45
+ model: ""
46
+ timeout: 30
47
+ flush_memories:
48
+ provider: "auto"
49
+ model: ""
50
+ timeout: 30
51
+
52
+ # 子代理 (Delegation) 配置
53
+ delegation:
54
+ model: ""
55
+ provider: ""
56
+ max_iterations: 50
57
+ reasoning_effort: "medium"
58
+
59
+ # API Server 配置 (Web UI BFF 的上游代理目标)
60
+ api_server:
61
+ enabled: true
62
+ port: 8642
63
+ host: "127.0.0.1"
64
+
65
+ # 终端配置
66
+ terminal:
67
+ backend: local
68
+ timeout: 300
69
+ shell: /bin/bash
70
+
71
+ # 显示配置
72
+ display:
73
+ skin: default
74
+ show_tool_progress: true
75
+ show_resume: true
76
+ spinner: dots
77
+
78
+ # Agent 配置
79
+ agent:
80
+ max_iterations: 50
81
+ approval_mode: ask
82
+ dangerous_command_approval: ask
83
+ gateway_timeout: 300
84
+
85
+ # 记忆配置
86
+ memory:
87
+ enabled: true
88
+ provider: local
89
+
90
+ # 压缩配置
91
+ # threshold 是比率(0-1),不是 token 数。0.50 = 当上下文使用到模型 context 50% 时触发压缩
92
+ compression:
93
+ enabled: true
94
+ threshold: 0.50
95
+
96
+ # 定时任务
97
+ cron:
98
+ enabled: true
99
+ tick_interval: 60
entrypoint.sh CHANGED
@@ -1,26 +1,735 @@
1
- #!/bin/sh
 
 
 
 
 
 
 
 
 
2
  set -e
3
 
4
- echo "=== FreeLLMAPI Dataset Persistence Manager ==="
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5
 
6
- # 1. On startup: restore database from Hugging Face Dataset
7
- python3 /app/backup_manager.py restore
8
 
9
- # 2. Start background backup daemon
10
- python3 /app/backup_manager.py daemon &
11
- BACKUP_PID=
12
- echo "Backup daemon started (PID: , mode: scheduled)"
13
 
14
- # 3. Trap termination signals for graceful shutdown and final backup
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
15
  cleanup() {
16
- echo "Shutdown signal received, running final backup..."
17
- python3 /app/backup_manager.py backup || true
18
- kill 2>/dev/null || true
19
- wait 2>/dev/null || true
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
20
  exit 0
21
  }
 
22
  trap cleanup SIGTERM SIGINT
23
 
24
- # 4. Start FreeLLMAPI (foreground process)
25
- echo "Starting FreeLLMAPI..."
26
- exec node server/dist/index.js
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/bin/bash
2
+ # Entrypoint script for Hermes Agent on Hugging Face Spaces
3
+ # 基于 Hermes Agent 真实 config.yaml 格式(source: cli-config.yaml.example + hermes_cli/config.py)
4
+ #
5
+ # 启动架构:
6
+ # entrypoint.sh
7
+ # ├── data_sync daemon (后台, 数据持久化)
8
+ # ├── hermes gateway run (后台, API Server :8642 + 消息平台)
9
+ # └── node /opt/hermes-web-ui/dist/server/index.js (前台, BFF :7860, 替代 hermes dashboard)
10
+
11
  set -e
12
 
13
+ echo "🚀 Hermes Agent v0.10.0 - Hugging Face Spaces"
14
+ echo "=============================================="
15
+
16
+ # 检查必要的环境变量
17
+ if [ -z "$HF_DATASET_REPO" ]; then
18
+ echo "⚠️ 警告: HF_DATASET_REPO 未设置,数据将不会持久化到 Dataset"
19
+ fi
20
+
21
+ # ==================== 初始化目录 ====================
22
+ echo "📁 初始化目录结构..."
23
+ mkdir -p /data/.hermes/{cron,sessions,logs,memories,skills,pairing,hooks,image_cache,audio_cache,whatsapp/session,script}
24
+ mkdir -p /data/.hermes-web-ui
25
+ mkdir -p /app/logs
26
+
27
+ # ==================== 数据恢复 ====================
28
+ # 跳过从 Dataset 恢复 config.yaml(由本脚本根据环境变量重新生成)
29
+ export SKIP_CONFIG_RESTORE=true
30
+
31
+ if [ -n "$HF_DATASET_REPO" ]; then
32
+ echo "📥 从 Dataset 恢复数据..."
33
+ python -m src.data_sync restore || {
34
+ echo "⚠️ 数据恢复失败,使用空配置启动"
35
+ }
36
+ fi
37
+
38
+ # ==================== 模型配置系统 ====================
39
+ echo "🤖 配置模型系统..."
40
+
41
+ # ---- 供应商定义 ----
42
+ declare -A PROVIDER_MODELS=(
43
+ # ["nvidia"]="moonshotai/kimi-k2-thinking"
44
+ ["nvidia"]="deepseek-ai/deepseek-v4-flash"
45
+ ["siliconflow"]="Pro/moonshotai/Kimi-K2.5"
46
+ ["openai"]="gpt-4o"
47
+ ["anthropic"]="claude-3-5-sonnet-20241022"
48
+ ["google"]="gemini-2.0-flash"
49
+ ["gemini"]="gemini-2.5-flash"
50
+ ["openrouter"]="meta-llama/llama-3.1-8b-instruct:free"
51
+ ["longcat"]="LongCat-Flash-Thinking-2601"
52
+ )
53
+
54
+ declare -A PROVIDER_API_KEYS=(
55
+ ["nvidia"]="NVIDIA_API_KEY"
56
+ ["siliconflow"]="SILICONFLOW_API_KEY"
57
+ ["openai"]="OPENAI_API_KEY"
58
+ ["anthropic"]="ANTHROPIC_API_KEY"
59
+ ["google"]="GOOGLE_API_KEY"
60
+ ["gemini"]="GEMINI_API_KEY"
61
+ ["openrouter"]="OPENROUTER_API_KEY"
62
+ ["longcat"]="LONGCAT_API_KEY"
63
+ )
64
+
65
+ declare -A PROVIDER_BASE_URLS=(
66
+ ["nvidia"]="https://integrate.api.nvidia.com/v1"
67
+ ["siliconflow"]="https://api.siliconflow.cn/v1"
68
+ ["openai"]="https://api.openai.com/v1"
69
+ ["anthropic"]="https://api.anthropic.com/v1"
70
+ ["google"]="https://generativelanguage.googleapis.com"
71
+ ["gemini"]="https://generativelanguage.googleapis.com"
72
+ ["openrouter"]="https://openrouter.ai/api/v1"
73
+ ["longcat"]="https://api.longcat.chat/openai"
74
+ )
75
+
76
+ # ---- 检测主模型 ----
77
+ detect_main_model() {
78
+ if [ -n "$MODEL_PROVIDER" ] && [ -n "$MODEL_NAME" ]; then
79
+ echo "manual:$MODEL_PROVIDER:$MODEL_NAME"
80
+ return
81
+ fi
82
+ for provider in nvidia siliconflow openai anthropic google openrouter longcat; do
83
+ api_key_var="${PROVIDER_API_KEYS[$provider]}"
84
+ if [ -n "${!api_key_var}" ]; then
85
+ if [ -n "$MODEL_NAME" ]; then
86
+ echo "auto:$provider:$MODEL_NAME"
87
+ else
88
+ echo "auto:$provider:${PROVIDER_MODELS[$provider]}"
89
+ fi
90
+ return
91
+ fi
92
+ done
93
+ if [ -n "$GEMINI_API_KEY" ]; then
94
+ echo "auto:gemini:${PROVIDER_MODELS[gemini]}"
95
+ return
96
+ fi
97
+ echo "default:nvidia:${PROVIDER_MODELS[nvidia]}"
98
+ }
99
+
100
+ # ---- 检测辅助模型 ----
101
+ detect_vision_model() {
102
+ if [ -n "$VISION_MODEL" ]; then echo "$VISION_MODEL"; return; fi
103
+ if [ -n "$GEMINI_API_KEY" ] || [ -n "$GOOGLE_API_KEY" ]; then echo "google/gemini-2.5-flash"; return; fi
104
+ echo ""
105
+ }
106
+
107
+ detect_aux_model() {
108
+ if [ -n "$AUX_MODEL" ]; then echo "$AUX_MODEL"; return; fi
109
+ if [ -n "$OPENROUTER_API_KEY" ]; then echo "google/gemini-3-flash-preview"; return; fi
110
+ if [ -n "$GEMINI_API_KEY" ] || [ -n "$GOOGLE_API_KEY" ]; then echo "google/gemini-2.0-flash"; return; fi
111
+ echo ""
112
+ }
113
+
114
+ detect_delegation_model() {
115
+ if [ -n "$DELEGATION_MODEL" ]; then echo "$DELEGATION_MODEL"; return; fi
116
+ if [ -n "$SILICONFLOW_API_KEY" ]; then echo "Pro/moonshotai/Kimi-K2.5"; return; fi
117
+ echo ""
118
+ }
119
+
120
+ # ---- 执行检测 ----
121
+ echo ""
122
+ echo "📋 模型配置检测:"
123
+ echo "────────────────────────────────────────"
124
+
125
+ MAIN_DETECTED=$(detect_main_model)
126
+ IFS=':' read -r MAIN_MODE MAIN_PROVIDER MAIN_MODEL <<< "$MAIN_DETECTED"
127
+ echo "🎯 Main Model: $MAIN_PROVIDER/$MAIN_MODEL (模式: $MAIN_MODE)"
128
+
129
+ VISION_MODEL_VAL=$(detect_vision_model)
130
+ echo "👁️ Vision Model: ${VISION_MODEL_VAL:-auto-detect}"
131
+
132
+ AUX_MODEL_VAL=$(detect_aux_model)
133
+ echo "⚡ Aux Model: ${AUX_MODEL_VAL:-auto-detect}"
134
+
135
+ DELEGATION_MODEL_VAL=$(detect_delegation_model)
136
+ echo "💻 Delegation Model: ${DELEGATION_MODEL_VAL:-inherit-main}"
137
+
138
+ MAIN_BASE_URL="${PROVIDER_BASE_URLS[$MAIN_PROVIDER]}"
139
+ echo " Base URL: $MAIN_BASE_URL"
140
+
141
+ echo "────────────────────────────────────────"
142
+
143
+ # ==================== 生成 config.yaml ====================
144
+ CONFIG_FILE="/data/.hermes/config.yaml"
145
+ echo "📝 生成 config.yaml (Hermes 真实格式)..."
146
+
147
+ # 推断辅助模型供应商
148
+ infer_provider() {
149
+ local model_id="$1"
150
+ if [[ "$model_id" == google/* ]]; then echo "google"
151
+ elif [[ "$model_id" == openrouter/* ]]; then echo "openrouter"
152
+ elif [[ "$model_id" == Pro/* ]]; then echo "siliconflow"
153
+ else echo "$MAIN_PROVIDER"; fi
154
+ }
155
+
156
+ VISION_PROVIDER_VAL=$(infer_provider "$VISION_MODEL_VAL")
157
+ AUX_PROVIDER_VAL=$(infer_provider "$AUX_MODEL_VAL")
158
+ DELEGATION_PROVIDER_VAL=$(infer_provider "$DELEGATION_MODEL_VAL")
159
+
160
+ cat > "$CONFIG_FILE" << EOF
161
+ # Hermes Agent Configuration
162
+ # Generated by entrypoint.sh at $(date -Iseconds)
163
+
164
+ # 主模型配置
165
+ model:
166
+ default: "$MAIN_MODEL"
167
+ provider: "$MAIN_PROVIDER"
168
+ base_url: "$MAIN_BASE_URL"
169
+
170
+ # 辅助模型配置 (per-task overrides)
171
+ auxiliary:
172
+ vision:
173
+ provider: "${VISION_PROVIDER_VAL:-auto}"
174
+ model: "${VISION_MODEL_VAL}"
175
+ timeout: 120
176
+ download_timeout: 30
177
+ web_extract:
178
+ provider: "${AUX_PROVIDER_VAL:-auto}"
179
+ model: "${AUX_MODEL_VAL}"
180
+ timeout: 360
181
+ compression:
182
+ provider: "${AUX_PROVIDER_VAL:-auto}"
183
+ model: "${AUX_MODEL_VAL}"
184
+ timeout: 120
185
+ title_generation:
186
+ provider: "${AUX_PROVIDER_VAL:-auto}"
187
+ model: "${AUX_MODEL_VAL}"
188
+ timeout: 30
189
+ session_search:
190
+ provider: "auto"
191
+ model: ""
192
+ timeout: 30
193
+ skills_hub:
194
+ provider: "auto"
195
+ model: ""
196
+ timeout: 30
197
+ approval:
198
+ provider: "auto"
199
+ model: ""
200
+ timeout: 30
201
+ mcp:
202
+ provider: "auto"
203
+ model: ""
204
+ timeout: 30
205
+ flush_memories:
206
+ provider: "auto"
207
+ model: ""
208
+ timeout: 30
209
+
210
+ # 子代理 (Delegation) 配置
211
+ delegation:
212
+ model: "${DELEGATION_MODEL_VAL}"
213
+ provider: "${DELEGATION_PROVIDER_VAL}"
214
+ max_iterations: 50
215
+ reasoning_effort: "medium"
216
+
217
+ # API Server 配置 (Web UI BFF 的上游代理目标)
218
+ api_server:
219
+ enabled: true
220
+ port: 8642
221
+ host: "127.0.0.1"
222
+
223
+ # 终端配置
224
+ terminal:
225
+ backend: local
226
+ timeout: 300
227
+ shell: /bin/bash
228
+
229
+ # 显示配置
230
+ display:
231
+ skin: default
232
+ show_tool_progress: true
233
+ show_resume: true
234
+ spinner: dots
235
+
236
+ # Agent 配置
237
+ agent:
238
+ max_iterations: 50
239
+ approval_mode: ask
240
+ dangerous_command_approval: ask
241
+ gateway_timeout: 300
242
+
243
+ # 记忆配置
244
+ memory:
245
+ enabled: true
246
+ provider: local
247
+
248
+ # 压缩配置
249
+ compression:
250
+ enabled: true
251
+ threshold: 0.50
252
+
253
+ # 定时任务
254
+ cron:
255
+ enabled: true
256
+ tick_interval: 60
257
+ EOF
258
+
259
+ echo " ✅ 配置文件已生成"
260
+
261
+ # ==================== 合并用户配置(平台/channel 设置等) ====================
262
+ # 如果存在从 Dataset 恢复的 config.yaml.restored,将其中的用户修改区块合并到新生成的 config.yaml
263
+ # 合并策略:
264
+ # - entrypoint.sh 控制的区块(model, auxiliary, delegation, api_server):新生成的优先
265
+ # (这些由 HF Spaces 环境变量决定,必须权威)
266
+ # - 用户在 Web UI 中修改的区块(platforms, display, agent, memory, compression, cron, terminal):
267
+ # 恢复的优先(保留用户的个性化设置,如 channel 行为、显示偏好等)
268
+ RESTORED_CONFIG="/data/.hermes/config.yaml.restored"
269
+ if [ -f "$RESTORED_CONFIG" ]; then
270
+ echo "🔄 合并用户配置 (platforms, display, agent 等)..."
271
+ python3 << 'MERGE_SCRIPT'
272
+ import yaml
273
+ import sys
274
+
275
+ GENERATED = '/data/.hermes/config.yaml'
276
+ RESTORED = '/data/.hermes/config.yaml.restored'
277
+
278
+ # 区块优先级定义:
279
+ # ENTRYPOINT_PRIORITY → entrypoint.sh 生成的值优先(由 HF Spaces 环境变量控制)
280
+ # USER_PRIORITY → 恢复的用户值优先(Web UI 中用户修改的偏好)
281
+ ENTRYPOINT_PRIORITY = {'model', 'auxiliary', 'delegation', 'api_server'}
282
+ USER_PRIORITY = {'platforms', 'display', 'agent', 'memory', 'compression', 'cron', 'terminal'}
283
+
284
+ try:
285
+ with open(GENERATED) as f:
286
+ generated = yaml.safe_load(f) or {}
287
+ with open(RESTORED) as f:
288
+ restored = yaml.safe_load(f) or {}
289
+
290
+ merged = {}
291
+
292
+ # 遍历所有出现在任一配置中的顶层键
293
+ all_keys = set(list(generated.keys()) + list(restored.keys()))
294
+
295
+ for key in all_keys:
296
+ if key in ENTRYPOINT_PRIORITY:
297
+ # 环境变量控制的区块:始终用新生成的值
298
+ if key in generated:
299
+ merged[key] = generated[key]
300
+ elif key in USER_PRIORITY:
301
+ # 用户偏好区块:优先用恢复的值,没有则用生成的默认值
302
+ if key in restored:
303
+ merged[key] = restored[key]
304
+ elif key in generated:
305
+ merged[key] = generated[key]
306
+ else:
307
+ # 未明确分类的区块:优先用恢复的值(保留用户可能做的修改)
308
+ if key in restored:
309
+ merged[key] = restored[key]
310
+ elif key in generated:
311
+ merged[key] = generated[key]
312
 
313
+ with open(GENERATED, 'w') as f:
314
+ yaml.dump(merged, f, default_flow_style=False, allow_unicode=True, sort_keys=False)
315
 
316
+ # 统计合并了哪些区块
317
+ merged_user_keys = [k for k in USER_PRIORITY if k in restored]
318
+ merged_other_keys = [k for k in all_keys - ENTRYPOINT_PRIORITY - USER_PRIORITY if k in restored and k not in generated]
319
+ print(f" ✅ 已合并用户区块: {', '.join(merged_user_keys) if merged_user_keys else '无'}")
320
 
321
+ except Exception as e:
322
+ print(f" ⚠️ 合并配置失败: {e},使用生成的默认配置")
323
+ sys.exit(0) # 不阻止启动
324
+ MERGE_SCRIPT
325
+ # 合并完成后删除临时文件,避免被后续备份重复保存
326
+ rm -f "$RESTORED_CONFIG"
327
+ else
328
+ echo " ℹ️ 无需合并(无恢复的用户配置)"
329
+ fi
330
+
331
+ # ==================== 导出供应商 Base URL 环境变量 ====================
332
+ echo "🌐 设置供应商 Base URL 环境变量..."
333
+
334
+ if [ -n "$NVIDIA_API_KEY" ]; then
335
+ export NVIDIA_BASE_URL="${NVIDIA_BASE_URL:-https://integrate.api.nvidia.com/v1}"
336
+ fi
337
+ if [ -n "$SILICONFLOW_API_KEY" ]; then
338
+ export SILICONFLOW_BASE_URL="${SILICONFLOW_BASE_URL:-https://api.siliconflow.cn/v1}"
339
+ fi
340
+ if [ -n "$GEMINI_API_KEY" ]; then
341
+ export GEMINI_BASE_URL="${GEMINI_BASE_URL:-https://generativelanguage.googleapis.com}"
342
+ fi
343
+ if [ -n "$OPENROUTER_API_KEY" ]; then
344
+ export OPENROUTER_BASE_URL="${OPENROUTER_BASE_URL:-https://openrouter.ai/api/v1}"
345
+ fi
346
+ if [ -n "$LONGCAT_API_KEY" ]; then
347
+ export LONGCAT_BASE_URL="${LONGCAT_BASE_URL:-https://api.longcat.chat/openai}"
348
+ fi
349
+
350
+ # 导出 API Server 环境变量(确保 Gateway 以 API Server 模式启动)
351
+ export API_SERVER_ENABLED=true
352
+ export API_SERVER_PORT=8642
353
+ export API_SERVER_HOST=127.0.0.1
354
+
355
+ # 默认允许所有用户(Hugging Face Spaces 单用户场景,否则 Gateway 拒绝所有消息)
356
+ export GATEWAY_ALLOW_ALL_USERS="${GATEWAY_ALLOW_ALL_USERS:-true}"
357
+
358
+ # 导出 HERMES_MODEL 环境变量(进程级覆盖,影响 cron 等调度任务的模型选择)
359
+ export HERMES_MODEL="$MAIN_MODEL"
360
+
361
+ echo " ✅ Base URL 环境变量已设置"
362
+ echo " ✅ API Server 环境变量已设置 (端口: 8642)"
363
+ echo " ✅ HERMES_MODEL=$HERMES_MODEL (进程级模型覆盖)"
364
+
365
+ # ==================== 环境变量注入 ====================
366
+ echo "⚙️ 注入环境变量到 .env..."
367
+ ENV_FILE="/data/.hermes/.env"
368
+ mkdir -p /data/.hermes
369
+
370
+ PERSISTENT_VARS=(
371
+ "MODEL_PROVIDER" "MODEL_NAME" "HERMES_MODEL"
372
+ "VISION_MODEL" "AUX_MODEL" "DELEGATION_MODEL"
373
+ "NVIDIA_API_KEY" "NVIDIA_BASE_URL"
374
+ "SILICONFLOW_API_KEY" "SILICONFLOW_BASE_URL"
375
+ "OPENAI_API_KEY"
376
+ "ANTHROPIC_API_KEY"
377
+ "GOOGLE_API_KEY" "GEMINI_API_KEY" "GEMINI_BASE_URL"
378
+ "OPENROUTER_API_KEY" "OPENROUTER_BASE_URL"
379
+ "LONGCAT_API_KEY" "LONGCAT_BASE_URL"
380
+ "API_SERVER_ENABLED" "API_SERVER_PORT" "API_SERVER_HOST"
381
+ "TELEGRAM_BOT_TOKEN" "TELEGRAM_ALLOWED_USERS" "TELEGRAM_PROXY"
382
+ "DISCORD_BOT_TOKEN" "DISCORD_CLIENT_ID"
383
+ "SLACK_BOT_TOKEN" "SLACK_APP_TOKEN" "SLACK_SIGNING_SECRET"
384
+ "WHATSAPP_BUSINESS_ID" "WHATSAPP_PHONE_NUMBER" "WHATSAPP_ACCESS_TOKEN"
385
+ "WEIXIN_ACCOUNT_ID" "WEIXIN_TOKEN" "WEIXIN_BASE_URL"
386
+ "GATEWAY_ALLOW_ALL_USERS"
387
+ "AUTH_TOKEN"
388
+ )
389
+
390
+ # 合并策略:保留恢复的 .env 中由 BFF 等写入的变量(如 WEIXIN_ACCOUNT_ID/WEIXIN_TOKEN),
391
+ # 同时用进程环境变量覆盖同名键(进程环境变量优先级更高)。
392
+ # 这避免了 "先恢复再清空" 导致 BFF 写入的凭据丢失的问题。
393
+
394
+ # 第1步:读取恢复的 .env 中所有现有键值对(跳过注释和空行)
395
+ declare -A env_entries=()
396
+ if [ -f "$ENV_FILE" ]; then
397
+ while IFS= read -r line; do
398
+ # 跳过注释和空行
399
+ [[ "$line" =~ ^[[:space:]]*# ]] && continue
400
+ [[ -z "${line// }" ]] && continue
401
+ # 提取 KEY=VALUE
402
+ eq_idx="${line%%=*}"
403
+ if [ -n "$eq_idx" ] && [ "$eq_idx" != "$line" ]; then
404
+ env_entries["$eq_idx"]="$line"
405
+ fi
406
+ done < "$ENV_FILE"
407
+ fi
408
+
409
+ # 第2步:用进程环境变量覆盖/新增 PERSISTENT_VARS 中的键
410
+ for var in "${PERSISTENT_VARS[@]}"; do
411
+ if [ -n "${!var}" ]; then
412
+ env_entries["$var"]="${var}=${!var}"
413
+ else
414
+ # 进程环境中没有该变量,但恢复的 .env 中可能有 → 保留恢复的值
415
+ # 如果恢复的 .env 中也没有,则不写入
416
+ :
417
+ fi
418
+ done
419
+
420
+ # 第3步:写入合并后的 .env
421
+ {
422
+ for key in "${!env_entries[@]}"; do
423
+ echo "${env_entries[$key]}"
424
+ done
425
+ } | sort > "$ENV_FILE"
426
+
427
+ RESTORED_COUNT=$(grep -c '=' "$ENV_FILE")
428
+ echo " ✅ 已写入 ${RESTORED_COUNT} 个环境变量(���恢复的持久化变量)"
429
+
430
+ # ==================== 启动数据同步服务 ====================
431
+ SYNC_INTERVAL=${SYNC_INTERVAL:-60}
432
+ echo "🔄 数据同步间隔: ${SYNC_INTERVAL}秒"
433
+
434
+ echo "🔄 启动数据同步服务..."
435
+ python -m src.data_sync daemon &
436
+ SYNC_PID=$!
437
+ echo " 同步服务 PID: $SYNC_PID"
438
+
439
+ # ==================== 配置检查 + 模型锁定 ====================
440
+ echo "🔄 检查配置..."
441
+ hermes config check 2>/dev/null || echo " 配置检查完成"
442
+
443
+ echo "🔒 强制写入模型配置(防止 Hermes 启动时被覆盖)..."
444
+ hermes config set model.default "$MAIN_MODEL" 2>/dev/null || {
445
+ echo " ⚠️ hermes config set 不可用,使用直接写入方式"
446
+ if command -v yq &>/dev/null; then
447
+ yq -i ".model.default = \"$MAIN_MODEL\"" "$CONFIG_FILE"
448
+ fi
449
+ }
450
+ hermes config set model.provider "$MAIN_PROVIDER" 2>/dev/null || true
451
+ hermes config set model.base_url "$MAIN_BASE_URL" 2>/dev/null || true
452
+
453
+ # 验证 config.yaml 中模型是否正确
454
+ if command -v yq &>/dev/null; then
455
+ ACTUAL_MODEL=$(yq '.model.default' "$CONFIG_FILE" 2>/dev/null)
456
+ if [ "$ACTUAL_MODEL" != "$MAIN_MODEL" ]; then
457
+ echo " ⚠️ 模型被覆盖! 期望: $MAIN_MODEL, 实际: $ACTUAL_MODEL"
458
+ echo " 🔄 重新写入模型配置..."
459
+ yq -i ".model.default = \"$MAIN_MODEL\"" "$CONFIG_FILE"
460
+ yq -i ".model.provider = \"$MAIN_PROVIDER\"" "$CONFIG_FILE"
461
+ yq -i ".model.base_url = \"$MAIN_BASE_URL\"" "$CONFIG_FILE"
462
+ fi
463
+ fi
464
+
465
+ echo " ✅ 模型配置已锁定: $MAIN_PROVIDER/$MAIN_MODEL"
466
+
467
+ # ==================== Socket 桥接路径检测(防止 AI 对话失联) ====================
468
+ # hermes-web-ui 通过 Unix Socket (/tmp/hermes-agent-bridge.sock) 与 agent 通信,
469
+ # 桥接程序需要 hermes-agent 源码中的 run_agent.py。如果源码被删除,桥接失败。
470
+ echo "🔌 检测 Hermes Agent Socket 桥接..."
471
+ HERMES_PKG_PATH=""
472
+
473
+ # 优先使用 HERMES_AGENT_ROOT 环境变量(用户自定义覆盖)
474
+ if [ -n "$HERMES_AGENT_ROOT" ] && [ -d "$HERMES_AGENT_ROOT" ]; then
475
+ HERMES_PKG_PATH="$HERMES_AGENT_ROOT"
476
+ echo " ✅ 使用 HERMES_AGENT_ROOT: $HERMES_PKG_PATH"
477
+ # 其次使用保留的默认源码包
478
+ elif [ -d "/usr/local/lib/hermes-agent" ]; then
479
+ HERMES_PKG_PATH="/usr/local/lib/hermes-agent"
480
+ echo " ✅ 找到保留的 hermes-agent 源码包: $HERMES_PKG_PATH"
481
+ fi
482
+
483
+ if [ -n "$HERMES_PKG_PATH" ]; then
484
+ # 导出环境变量供桥接程序使用
485
+ export HERMES_AGENT_ROOT="$HERMES_PKG_PATH"
486
+ # 创建符号链接供桥接程序定位
487
+ ln -sf "$HERMES_PKG_PATH" "$HOME/.hermes/hermes-agent" 2>/dev/null || true
488
+ echo " 🔗 已创建符号链接: $HOME/.hermes/hermes-agent → $HERMES_PKG_PATH"
489
+
490
+ # 查找桥接脚本并验证
491
+ BRIDGE_SCRIPT=""
492
+ BRIDGE_PATHS=(
493
+ "$HERMES_PKG_PATH/hermes_bridge.py"
494
+ "/usr/local/lib/python3.11/site-packages/hermes_web_ui/hermes_bridge.py"
495
+ "/opt/hermes-web-ui/node_modules/hermes-web-ui/dist/server/hermes_bridge.py"
496
+ )
497
+ for bridge_path in "${BRIDGE_PATHS[@]}"; do
498
+ if [ -f "$bridge_path" ]; then
499
+ chmod +x "$bridge_path" 2>/dev/null || true
500
+ BRIDGE_SCRIPT="$bridge_path"
501
+ echo " ✅ 找到桥接脚本: $BRIDGE_SCRIPT"
502
+ break
503
+ fi
504
+ done
505
+
506
+ if [ -n "$BRIDGE_SCRIPT" ]; then
507
+ echo " 🔍 验证桥接脚本..."
508
+ python3 "$BRIDGE_SCRIPT" --help 2>/dev/null && echo " ✅ 桥接脚本验证通过" || echo " ⚠️ 桥接脚本验证超时(不影响启动)"
509
+ fi
510
+ else
511
+ echo " ⚠️ 未找到 hermes-agent 源码包,桥接可能失败"
512
+ echo " 💡 如果遇到 ENOENT /tmp/hermes-agent-bridge.sock 错误,请确保 Dockerfile 中保留了 hermes-agent 源码"
513
+ fi
514
+
515
+ # ==================== 启动 Gateway (API Server + 消息平台) ====================
516
+ echo "📡 启动 Hermes Gateway + API Server..."
517
+
518
+ # Gateway PID 文件(用于追踪当前运行的 gateway 进程)
519
+ GATEWAY_PIDFILE="/data/.hermes/gateway.pid"
520
+
521
+ # Gateway 包装器:自动重启 + 崩溃恢复
522
+ # 使用 --replace 避免端口冲突(BFF 偶尔也通过 hermes-cli.ts 调用 restartGateway)
523
+ # 崩溃后等待 30 秒重启;正常退出不重启
524
+ # BFF 保存 weixin 凭据后会调用 restartGateway(),该函数在 Docker 模式下
525
+ # 会 kill 旧进程然后 spawn "hermes gateway run",与本包装器可能竞争。
526
+ # --replace 让 gateway 在检测到端口占用时自动替换旧进程,避免冲突。
527
+ (
528
+ while true; do
529
+ hermes gateway run --replace 2>&1 | while IFS= read -r line; do
530
+ echo "$line"
531
+ case "$line" in
532
+ *"Gateway failed to connect"*)
533
+ echo " ⚠️ 网关消息平台连接失败,API Server 仍可使用,30 秒后重试..."
534
+ ;;
535
+ esac
536
+ done
537
+ EXIT_CODE=${PIPESTATUS[0]}
538
+ if [ "$EXIT_CODE" -ne 0 ]; then
539
+ echo " ⚠️ 网关进程退出 (code=$EXIT_CODE),30 秒后重启..."
540
+ sleep 30
541
+ else
542
+ echo " 🛑 网关正常退出(可能被 BFF restartGateway 替换)"
543
+ # 检查是否有新 gateway 进程在运行(BFF 可能已启动新进程)
544
+ sleep 5
545
+ if [ -f "$GATEWAY_PIDFILE" ]; then
546
+ NEW_PID=$(python3 -c "import json; print(json.load(open('$GATEWAY_PIDFILE')).get('pid',0))" 2>/dev/null || echo 0)
547
+ if [ "$NEW_PID" -gt 0 ] && kill -0 "$NEW_PID" 2>/dev/null; then
548
+ echo " 🔄 检测到新网关进程 (PID: $NEW_PID),等待其退出..."
549
+ # 等待新进程退出后再继续循环
550
+ while kill -0 "$NEW_PID" 2>/dev/null; do sleep 5; done
551
+ echo " ⚠️ 新网关进程已退出,30 秒后重启包装器..."
552
+ sleep 30
553
+ continue
554
+ fi
555
+ fi
556
+ echo " 🛑 无新网关进程,不再重启"
557
+ break
558
+ fi
559
+ done
560
+ ) &
561
+ GATEWAY_PID=$!
562
+
563
+ # 等待 API Server 就绪
564
+ echo " ⏳ 等待 API Server 就绪 (:8642)..."
565
+ API_READY=false
566
+ for i in $(seq 1 30); do
567
+ if curl -sf http://127.0.0.1:8642/health > /dev/null 2>&1; then
568
+ API_READY=true
569
+ break
570
+ fi
571
+ sleep 1
572
+ done
573
+
574
+ if [ "$API_READY" = true ]; then
575
+ echo " ✅ API Server 已就绪 (http://127.0.0.1:8642)"
576
+ # Gateway PID 文件由 Hermes 自己在 gateway run 启动时写入(gateway/run.py:write_pid_file)
577
+ # 通过 symlink /home/appuser/.hermes → /data/.hermes,BFF GatewayManager 可正确读取
578
+ else
579
+ echo " ⚠️ API Server 未在 30 秒内就绪,继续启动 Web UI(API Server 可能稍后可用)"
580
+ fi
581
+
582
+ if kill -0 $GATEWAY_PID 2>/dev/null; then
583
+ echo " ✅ 网关进程运行中 (PID: $GATEWAY_PID)"
584
+ else
585
+ echo " ⚠️ 网关进程已退出,仅 Web UI 可用"
586
+ fi
587
+
588
+ echo ""
589
+ echo "💡 提示:"
590
+ echo " - Channels 页面可配置微信/飞书/企业微信等平台"
591
+ echo " - Models 页面可管理模型供应商"
592
+ echo " - Jobs 页面可管理定时任务"
593
+ echo ""
594
+
595
+ # ==================== Auth Token 处理 ====================
596
+ echo "🔑 配置 Web UI 认证..."
597
+ if [ -z "$AUTH_TOKEN" ]; then
598
+ # 尝试从持久化文件恢复
599
+ AUTH_TOKEN_FILE="/data/.hermes-web-ui/.token"
600
+ if [ -f "$AUTH_TOKEN_FILE" ]; then
601
+ AUTH_TOKEN=$(cat "$AUTH_TOKEN_FILE")
602
+ echo " ✅ 已恢复 Web UI 认证 Token"
603
+ else
604
+ # 自动生成新 Token
605
+ AUTH_TOKEN=$(openssl rand -hex 16 2>/dev/null || head -c 32 /dev/urandom | xxd -p | head -c 32)
606
+ mkdir -p /data/.hermes-web-ui
607
+ echo "$AUTH_TOKEN" > "$AUTH_TOKEN_FILE"
608
+ echo ""
609
+ echo " ╔══════════════════════════════════════════════════╗"
610
+ echo " ║ 🔑 Web UI 认证 Token (请保存!) ║"
611
+ echo " ║ $AUTH_TOKEN"
612
+ echo " ║ ║"
613
+ echo " ║ 在 Web UI 登录页面输入此 Token ║"
614
+ echo " ║ 也可在 HF Spaces Settings 设置 AUTH_TOKEN 覆盖 ║"
615
+ echo " ╚══════════════════════════════════════════════════╝"
616
+ echo ""
617
+ fi
618
+ else
619
+ echo " ✅ 使用环境变量中的 AUTH_TOKEN"
620
+ fi
621
+ export AUTH_TOKEN
622
+
623
+ # ==================== 启动 Code Server ====================
624
+ echo "📝 启动 Code Server..."
625
+ export CODE_SERVER_PORT=8443
626
+ export CODE_SERVER_PASSWORD="${CODE_SERVER_PASSWORD:-${AUTH_TOKEN}}"
627
+ export CODE_SERVER_DATA_DIR=/data/.hermes/code-server
628
+ mkdir -p "$CODE_SERVER_DATA_DIR"
629
+
630
+ code-server --port 8443 \
631
+ --auth password \
632
+ --password "$CODE_SERVER_PASSWORD" \
633
+ --data "$CODE_SERVER_DATA_DIR" \
634
+ /data/.hermes &
635
+ CODER_PID=$!
636
+ echo " Code Server PID: $CODER_PID"
637
+
638
+ # ==================== 启动 Web UI (BFF Server) ====================
639
+ echo "🌐 启动 Hermes Web UI..."
640
+ echo " BFF Server: http://0.0.0.0:7860"
641
+ echo " Upstream: http://127.0.0.1:8642"
642
+ echo ""
643
+
644
+ # 确保运行时环境变量设置完毕
645
+ export PORT=7860
646
+ export UPSTREAM=http://127.0.0.1:8642
647
+ export HERMES_BIN=/usr/local/bin/hermes
648
+ export HERMES_HOME=/data/.hermes
649
+
650
+ # 优雅关闭
651
  cleanup() {
652
+ echo ""
653
+ echo "🛑 执行清理..."
654
+
655
+ # 备份数据
656
+ if [ -n "$HF_DATASET_REPO" ]; then
657
+ echo " 💾 执行最终数据备份..."
658
+ python -m src.data_sync backup --force 2>/dev/null || echo " ⚠️ 备份失败"
659
+ fi
660
+
661
+ # 停止各进程(顺序:BFF → Code Server → Gateway → Sync)
662
+ if [ -n "$BFF_PID" ] && kill -0 $BFF_PID 2>/dev/null; then
663
+ echo " 🛑 停止 Web UI..."
664
+ kill $BFF_PID 2>/dev/null || true
665
+ wait $BFF_PID 2>/dev/null || true
666
+ fi
667
+ if [ -n "$CODER_PID" ] && kill -0 $CODER_PID 2>/dev/null; then
668
+ echo " 🛑 停止 Code Server..."
669
+ kill $CODER_PID 2>/dev/null || true
670
+ wait $CODER_PID 2>/dev/null || true
671
+ fi
672
+ if [ -n "$GATEWAY_PID" ] && kill -0 $GATEWAY_PID 2>/dev/null; then
673
+ echo " 🛑 停止 Gateway..."
674
+ kill $GATEWAY_PID 2>/dev/null || true
675
+ wait $GATEWAY_PID 2>/dev/null || true
676
+ fi
677
+ if kill -0 $SYNC_PID 2>/dev/null; then
678
+ echo " 🛑 停止数据同步..."
679
+ kill $SYNC_PID 2>/dev/null || true
680
+ wait $SYNC_PID 2>/dev/null || true
681
+ fi
682
+
683
+ echo "👋 再见!"
684
  exit 0
685
  }
686
+
687
  trap cleanup SIGTERM SIGINT
688
 
689
+ # 启动 BFF Server (替代 hermes dashboard)
690
+ node /opt/hermes-web-ui/dist/server/index.js &
691
+ BFF_PID=$!
692
+
693
+ # 等待 BFF 就绪
694
+ echo " ⏳ 等待 Web UI 就绪..."
695
+ BFF_READY=false
696
+ for i in $(seq 1 20); do
697
+ if curl -sf http://localhost:7860/health > /dev/null 2>&1; then
698
+ BFF_READY=true
699
+ break
700
+ fi
701
+ sleep 1
702
+ done
703
+
704
+ if [ "$BFF_READY" = true ]; then
705
+ echo " ✅ Web UI 已就绪 → http://localhost:7860"
706
+ else
707
+ echo " ⚠️ Web UI 未在 20 秒内就绪,请查看日志"
708
+ fi
709
+
710
+ # 再次验证模型配置(BFF 启动可能修改 config.yaml)
711
+ if [ -f "$CONFIG_FILE" ]; then
712
+ if command -v yq &>/dev/null; then
713
+ ACTUAL_MODEL=$(yq '.model.default' "$CONFIG_FILE" 2>/dev/null)
714
+ if [ -n "$ACTUAL_MODEL" ] && [ "$ACTUAL_MODEL" != "$MAIN_MODEL" ] && [ "$ACTUAL_MODEL" != "null" ]; then
715
+ echo " ⚠️ 检测到模型被 BFF 启动流程覆盖!"
716
+ echo " 📋 期望: $MAIN_MODEL, 实际: $ACTUAL_MODEL"
717
+ echo " 🔒 重新写入正确的模型配置..."
718
+ yq -i ".model.default = \"$MAIN_MODEL\"" "$CONFIG_FILE"
719
+ yq -i ".model.provider = \"$MAIN_PROVIDER\"" "$CONFIG_FILE"
720
+ yq -i ".model.base_url = \"$MAIN_BASE_URL\"" "$CONFIG_FILE"
721
+ echo " ✅ 模型已修正: $MAIN_PROVIDER/$MAIN_MODEL"
722
+ elif [ -z "$ACTUAL_MODEL" ] || [ "$ACTUAL_MODEL" = "null" ]; then
723
+ echo " ⚠️ 检测到模型字段为空! 重新写入..."
724
+ yq -i ".model.default = \"$MAIN_MODEL\"" "$CONFIG_FILE"
725
+ yq -i ".model.provider = \"$MAIN_PROVIDER\"" "$CONFIG_FILE"
726
+ yq -i ".model.base_url = \"$MAIN_BASE_URL\"" "$CONFIG_FILE"
727
+ echo " ✅ 模型已修正: $MAIN_PROVIDER/$MAIN_MODEL"
728
+ else
729
+ echo " ✅ 模型配置验证通过: $MAIN_PROVIDER/$MAIN_MODEL"
730
+ fi
731
+ fi
732
+ fi
733
+
734
+ # 等待 BFF 主进程(前台阻塞,容器生命周期由 BFF 控制)
735
+ wait $BFF_PID
requirements.txt ADDED
@@ -0,0 +1,36 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Hermes Agent on Hugging Face Spaces
2
+ # Python 依赖
3
+
4
+ # 核心依赖
5
+ huggingface-hub>=0.20.0
6
+ datasets>=2.14.0
7
+ requests>=2.31.0
8
+ pydantic>=2.0.0
9
+ python-dotenv>=1.0.0
10
+ PyYAML>=6.0
11
+
12
+ # 数据处理和加密
13
+ cryptography>=41.0.0
14
+
15
+ # 日志和监控
16
+ loguru>=0.7.0
17
+ psutil>=5.9.0
18
+
19
+ # 异步支持
20
+ aiohttp>=3.9.0
21
+ aiocron>=1.8
22
+
23
+ # 工具
24
+ click>=8.1.0
25
+ rich>=13.0.0
26
+
27
+ # 文件监控(实时同步配置变更)
28
+ watchdog>=3.0.0
29
+
30
+ # script/ 模块依赖
31
+ pandas>=2.0.0
32
+ numpy>=1.24.0
33
+ plotly>=5.18.0
34
+ fake-useragent
35
+ lxml
36
+ colorama
src/__init__.py ADDED
File without changes
src/data_sync.py ADDED
@@ -0,0 +1,397 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python3
2
+ """
3
+ Hermes Agent Data Sync Service
4
+ Handles data persistence to/from Hugging Face Dataset
5
+ """
6
+
7
+ import os
8
+ import sys
9
+ import time
10
+ import json
11
+ import shutil
12
+ import argparse
13
+ from pathlib import Path
14
+ from datetime import datetime
15
+ from typing import Optional, Dict, List
16
+
17
+ from huggingface_hub import HfApi, hf_hub_download, upload_folder
18
+ from loguru import logger
19
+
20
+ # 文件监控(可选)
21
+ try:
22
+ from watchdog.observers import Observer
23
+ from watchdog.events import FileSystemEventHandler
24
+ WATCHDOG_AVAILABLE = True
25
+ except ImportError:
26
+ WATCHDOG_AVAILABLE = False
27
+ logger.warning("watchdog not installed, file change detection disabled")
28
+
29
+
30
+ class DatasetManager:
31
+ """Manages data synchronization with Hugging Face Dataset"""
32
+
33
+ def __init__(self, dataset_repo: Optional[str] = None, token: Optional[str] = None):
34
+ self.dataset_repo = dataset_repo or os.environ.get('HF_DATASET_REPO')
35
+ self.token = token or os.environ.get('HF_TOKEN') or os.environ.get('HUGGING_FACE_HUB_TOKEN')
36
+ self.api = HfApi(token=self.token)
37
+ self.hermes_home = Path(os.environ.get('HERMES_HOME', '/data/.hermes'))
38
+ self.temp_dir = Path('/tmp/hermes_sync')
39
+
40
+ # 备份目录列表(会自动创建并复制整个目录)
41
+ self.backup_dirs = [
42
+ 'memories',
43
+ 'skills',
44
+ 'sessions',
45
+ 'logs',
46
+ 'cron',
47
+ 'script',
48
+ 'plugins',
49
+ 'extensions',
50
+ 'hooks',
51
+ 'prompts',
52
+ 'tools',
53
+ 'knowledge',
54
+ 'audio_cache',
55
+ 'image_cache',
56
+ 'pairing',
57
+ 'weixin',
58
+ 'whatsapp',
59
+ ]
60
+
61
+ # 备份文件列表
62
+ self.backup_files = [
63
+ 'config.yaml',
64
+ '.env',
65
+ 'auth.json',
66
+ 'SOUL.md',
67
+ 'state.db',
68
+ '.token',
69
+ 'channel_directory.json',
70
+ 'gateway_state.json',
71
+ 'gateway.lock',
72
+ 'gateway.pid',
73
+ 'kanban.db',
74
+ 'models_dev_cache.json',
75
+ 'processes.json',
76
+ 'response_store.db',
77
+ ]
78
+
79
+ # 文件 -> 子目录 映射(用于恢复时定位)
80
+ self._file_subdir = {
81
+ 'config.yaml': 'config',
82
+ '.env': 'config',
83
+ 'auth.json': 'config',
84
+ 'SOUL.md': 'root',
85
+ 'state.db': 'root',
86
+ '.token': 'webui',
87
+ 'channel_directory.json': 'root',
88
+ 'gateway_state.json': 'root',
89
+ 'gateway.lock': 'root',
90
+ 'gateway.pid': 'root',
91
+ 'kanban.db': 'root',
92
+ 'models_dev_cache.json': 'root',
93
+ 'processes.json': 'root',
94
+ 'response_store.db': 'root',
95
+ }
96
+
97
+ # 备份时排除的目录/文件模式
98
+ self.exclude_patterns = {'__pycache__', '.git', 'node_modules', '.cache', 'tmp', 'reports', 'src'}
99
+
100
+ def validate(self) -> bool:
101
+ """验证配置是否正确"""
102
+ if not self.dataset_repo:
103
+ logger.error("HF_DATASET_REPO not set")
104
+ return False
105
+
106
+ if not self.token:
107
+ logger.warning("HF_TOKEN not set, will try public dataset")
108
+
109
+ return True
110
+
111
+ def prepare_backup_data(self) -> Path:
112
+ """准备备份数据到临时目录"""
113
+ logger.info("Preparing backup data...")
114
+
115
+ # 清理并创建临时目录
116
+ if self.temp_dir.exists():
117
+ shutil.rmtree(self.temp_dir)
118
+ self.temp_dir.mkdir(parents=True)
119
+
120
+ # 动态创建目录结构
121
+ subdirs = set(self._file_subdir.values())
122
+ for dirname in self.backup_dirs:
123
+ (self.temp_dir / dirname).mkdir()
124
+ for subdir in subdirs:
125
+ (self.temp_dir / subdir).mkdir()
126
+
127
+ # 排除模式过滤函数 (shutil.copytree 要求 src, names 两个参数)
128
+ def should_exclude(src: str, names: list) -> bool:
129
+ return [n for n in names if n in self.exclude_patterns]
130
+
131
+ # 复制文件
132
+ try:
133
+ # 复制目录
134
+ for dirname in self.backup_dirs:
135
+ src_dir = self.hermes_home / dirname
136
+ if src_dir.exists():
137
+ shutil.copytree(src_dir, self.temp_dir / dirname, dirs_exist_ok=True, ignore=should_exclude)
138
+
139
+ # 复制文件
140
+ for filename in self.backup_files:
141
+ src_file = self.hermes_home / filename
142
+ if src_file.exists():
143
+ shutil.copy2(src_file, self.temp_dir / filename)
144
+
145
+ # 添加元数据
146
+ metadata = {
147
+ 'timestamp': datetime.now().isoformat(),
148
+ 'version': '0.11.0',
149
+ 'hermes_home': str(self.hermes_home)
150
+ }
151
+ with open(self.temp_dir / 'metadata.json', 'w') as f:
152
+ json.dump(metadata, f, indent=2)
153
+
154
+ logger.success(f"Backup prepared at {self.temp_dir}")
155
+ return self.temp_dir
156
+
157
+ except Exception as e:
158
+ logger.error(f"Failed to prepare backup: {e}")
159
+ raise
160
+
161
+ def upload_to_dataset(self, force: bool = False) -> bool:
162
+ """上传数据到 Hugging Face Dataset"""
163
+ try:
164
+ backup_dir = self.prepare_backup_data()
165
+
166
+ logger.info(f"Uploading to dataset: {self.dataset_repo}")
167
+
168
+ # 上传文件夹到 dataset
169
+ self.api.upload_folder(
170
+ folder_path=str(backup_dir),
171
+ repo_id=self.dataset_repo,
172
+ repo_type="dataset",
173
+ commit_message=f"Hermes Agent backup - {datetime.now().strftime('%Y-%m-%d %H:%M:%S')}"
174
+ )
175
+
176
+ logger.success("Backup uploaded successfully")
177
+ return True
178
+
179
+ except Exception as e:
180
+ logger.error(f"Failed to upload to dataset: {e}")
181
+ return False
182
+
183
+ def download_from_dataset(self) -> bool:
184
+ """从 Hugging Face Dataset 下载数据"""
185
+ try:
186
+ logger.info(f"Downloading from dataset: {self.dataset_repo}")
187
+
188
+ # 创建临时下载目录
189
+ download_dir = Path('/tmp/hermes_download')
190
+ if download_dir.exists():
191
+ shutil.rmtree(download_dir)
192
+ download_dir.mkdir(parents=True)
193
+
194
+ # 下载所有文件
195
+ self.api.snapshot_download(
196
+ repo_id=self.dataset_repo,
197
+ repo_type="dataset",
198
+ local_dir=str(download_dir)
199
+ )
200
+
201
+ logger.success("Download completed")
202
+
203
+ # 恢复数据到 Hermes 目录
204
+ self.restore_from_download(download_dir)
205
+ return True
206
+
207
+ except Exception as e:
208
+ logger.error(f"Failed to download from dataset: {e}")
209
+ return False
210
+
211
+ def restore_from_download(self, download_dir: Path):
212
+ """从下载的目录恢复数据
213
+
214
+ 注意: config.yaml 在恢复时被跳过,因为 entrypoint.sh 会根据环境变量
215
+ 重新生成正确的 config.yaml。如果恢复旧的 config.yaml,会导致模型
216
+ 配置被覆盖(例如 minimaxai/minimax-m2.7 被替换为旧模型)。
217
+ """
218
+ logger.info("Restoring data to Hermes home...")
219
+
220
+ # 确保目标目录存在
221
+ self.hermes_home.mkdir(parents=True, exist_ok=True)
222
+
223
+ # 动态恢复数据
224
+ skip_restore = os.environ.get('SKIP_CONFIG_RESTORE', 'true').lower() in ('true', '1', 'yes')
225
+
226
+ restore_list = []
227
+
228
+ # 恢复目录
229
+ for dirname in self.backup_dirs:
230
+ restore_list.append((dirname, self.hermes_home / dirname))
231
+
232
+ # 恢复文件
233
+ for filename in self.backup_files:
234
+ restore_list.append((filename, self.hermes_home / filename))
235
+
236
+ # config.yaml 恢复策略
237
+ if not skip_restore:
238
+ restore_list.append(('config.yaml', self.hermes_home / 'config.yaml'))
239
+ else:
240
+ logger.info("Skipping config.yaml direct restore (will be regenerated by entrypoint.sh)")
241
+ restored_path = self.hermes_home / 'config.yaml.restored'
242
+ src = download_dir / 'config.yaml'
243
+ if src.exists():
244
+ shutil.copy2(src, restored_path)
245
+ logger.info("Restored config.yaml to config.yaml.restored for merge")
246
+
247
+ for src_rel, dst in restore_list:
248
+ src = download_dir / src_rel
249
+ if src.exists():
250
+ try:
251
+ if src.is_file():
252
+ dst.parent.mkdir(parents=True, exist_ok=True)
253
+ shutil.copy2(src, dst)
254
+ logger.info(f"Restored: {src_rel}")
255
+ elif src.is_dir():
256
+ if dst.exists():
257
+ shutil.rmtree(dst)
258
+ shutil.copytree(src, dst)
259
+ logger.info(f"Restored directory: {src_rel}")
260
+ except Exception as e:
261
+ logger.error(f"Failed to restore {src_rel}: {e}")
262
+ else:
263
+ logger.warning(f"Not found in backup: {src_rel}")
264
+
265
+ logger.success("Data restoration completed")
266
+
267
+
268
+ class ConfigFileHandler(FileSystemEventHandler):
269
+ """配置文件变化处理器 - 实时同步到 Dataset 并触发重载"""
270
+
271
+ # 启动静默期(秒):在此期间内的文件变更不予备份,避免启动阶段冗余上传
272
+ STARTUP_GRACE_PERIOD = 30
273
+
274
+ def __init__(self, manager: DatasetManager):
275
+ self.manager = manager
276
+ self.last_backup_time = 0
277
+ self.backup_cooldown = 5 # 5秒内不重复备份
278
+ self.start_time = time.time() # 记录处理器创建时间
279
+ self._startup_logged = False
280
+
281
+ def on_modified(self, event):
282
+ """文件被修改时触发"""
283
+ if event.is_directory:
284
+ return
285
+
286
+ # 启动静默期:跳过启动阶段的配置变更备份
287
+ elapsed = time.time() - self.start_time
288
+ if elapsed < self.STARTUP_GRACE_PERIOD:
289
+ if not self._startup_logged:
290
+ logger.info(f"In startup grace period ({int(self.STARTUP_GRACE_PERIOD - elapsed)}s remaining), skipping backup for: {event.src_path}")
291
+ self._startup_logged = True
292
+ return
293
+
294
+ # 只关注关键配置文件
295
+ watched_files = ['config.yaml', '.env', 'auth.json']
296
+ if any(event.src_path.endswith(f) for f in watched_files):
297
+ current_time = time.time()
298
+ if current_time - self.last_backup_time > self.backup_cooldown:
299
+ logger.info(f"Config file changed: {event.src_path}")
300
+ logger.info("Triggering immediate backup...")
301
+ try:
302
+ self.manager.upload_to_dataset()
303
+ self.last_backup_time = current_time
304
+ logger.success("Immediate backup completed")
305
+
306
+ # 尝试触发 Hermes 配置重载
307
+ self._trigger_reload()
308
+
309
+ except Exception as e:
310
+ logger.error(f"Immediate backup failed: {e}")
311
+
312
+ def _trigger_reload(self):
313
+ """尝试触发 Hermes 配置重载"""
314
+ # 注意:Hermes 目前没有 config reload 命令
315
+ # 配置将在下次 Space 重启时自动生效
316
+ logger.info("Configuration saved. Please restart Space to apply changes immediately.")
317
+
318
+
319
+ def run_daemon():
320
+ """后台守护进程模式 - 定期同步 + 实时文件监听"""
321
+ logger.info("Starting data sync daemon...")
322
+
323
+ sync_interval = int(os.environ.get('SYNC_INTERVAL', '60')) # 默认60秒(实时模式)
324
+ manager = DatasetManager()
325
+
326
+ if not manager.validate():
327
+ logger.error("Configuration invalid, exiting")
328
+ sys.exit(1)
329
+
330
+ logger.info(f"Sync interval: {sync_interval} seconds")
331
+
332
+ # 如果 watchdog 可用,启动文件监听
333
+ observer = None
334
+ if WATCHDOG_AVAILABLE:
335
+ try:
336
+ logger.info("Starting file watcher for real-time sync...")
337
+ event_handler = ConfigFileHandler(manager)
338
+ observer = Observer()
339
+ observer.schedule(event_handler, str(manager.hermes_home), recursive=False)
340
+ observer.start()
341
+ logger.success("File watcher started - config changes will trigger immediate backup")
342
+ except Exception as e:
343
+ logger.error(f"Failed to start file watcher: {e}")
344
+ logger.warning("Falling back to scheduled sync only")
345
+ observer = None
346
+ else:
347
+ logger.warning("Watchdog not available, using scheduled sync only")
348
+
349
+ try:
350
+ while True:
351
+ try:
352
+ time.sleep(sync_interval)
353
+ logger.info("Performing scheduled backup...")
354
+ manager.upload_to_dataset()
355
+ except KeyboardInterrupt:
356
+ logger.info("Daemon stopped")
357
+ break
358
+ except Exception as e:
359
+ logger.error(f"Sync error: {e}")
360
+ finally:
361
+ # 清理文件监听器
362
+ if observer:
363
+ logger.info("Stopping file watcher...")
364
+ observer.stop()
365
+ observer.join()
366
+ logger.info("File watcher stopped")
367
+
368
+
369
+ def main():
370
+ parser = argparse.ArgumentParser(description='Hermes Agent Data Sync')
371
+ parser.add_argument('action', choices=['backup', 'restore', 'daemon'],
372
+ help='Action to perform')
373
+ parser.add_argument('--force', '-f', action='store_true',
374
+ help='Force backup even if no changes')
375
+
376
+ args = parser.parse_args()
377
+
378
+ manager = DatasetManager()
379
+
380
+ if not manager.validate():
381
+ logger.error("Configuration invalid")
382
+ sys.exit(1)
383
+
384
+ if args.action == 'backup':
385
+ success = manager.upload_to_dataset(force=args.force)
386
+ sys.exit(0 if success else 1)
387
+
388
+ elif args.action == 'restore':
389
+ success = manager.download_from_dataset()
390
+ sys.exit(0 if success else 1)
391
+
392
+ elif args.action == 'daemon':
393
+ run_daemon()
394
+
395
+
396
+ if __name__ == '__main__':
397
+ main()