tianzijian commited on
Commit
8a9dd29
·
verified ·
1 Parent(s): 5111dc8

Upload 4 files

Browse files
Files changed (4) hide show
  1. Dockerfile +18 -1
  2. entrypoint.sh +602 -13
  3. image-gen-siliconflow.ts +305 -0
  4. image-proxy.js +293 -0
Dockerfile CHANGED
@@ -41,6 +41,7 @@ RUN ARCH=$(dpkg --print-architecture) \
41
  && npm --version
42
 
43
  # ==================== Bun Runtime ====================
 
44
  # 安装到 /usr/local/bin 以便所有用户(包括 appuser)都能访问
45
  RUN echo "Installing Bun runtime" \
46
  && curl -fsSL https://bun.sh/install | bash \
@@ -49,6 +50,19 @@ RUN echo "Installing Bun runtime" \
49
  && cp /root/.bun/bin/bun /usr/local/bin/bun \
50
  && chmod +x /usr/local/bin/bun
51
 
 
 
 
 
 
 
 
 
 
 
 
 
 
52
  # ==================== 工具安装 ====================
53
  # yq: 运行时修改 config.yaml
54
  RUN curl -sL https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 -o /usr/bin/yq && \
@@ -84,6 +98,8 @@ WORKDIR /app
84
 
85
  COPY src/ /app/src/
86
  COPY entrypoint.sh /app/
 
 
87
  COPY config/config.yaml /data/.hermes/config.yaml
88
 
89
  # 创建数据目录
@@ -94,7 +110,8 @@ RUN mkdir -p /data/.hermes /data/.hermes-web-ui /app/logs /home/appuser/.hermes-
94
  RUN useradd -m -u 1000 appuser && \
95
  ln -sf /data/.hermes /home/appuser/.hermes && \
96
  mkdir -p /home/appuser/.cache && \
97
- chown -R appuser:appuser /data /opt/hermes-web-ui /app /home/appuser
 
98
 
99
  USER appuser
100
 
 
41
  && npm --version
42
 
43
  # ==================== Bun Runtime ====================
44
+ # baoyu-skills 需要 bun 运行时
45
  # 安装到 /usr/local/bin 以便所有用户(包括 appuser)都能访问
46
  RUN echo "Installing Bun runtime" \
47
  && curl -fsSL https://bun.sh/install | bash \
 
50
  && cp /root/.bun/bin/bun /usr/local/bin/bun \
51
  && chmod +x /usr/local/bin/bun
52
 
53
+ # bun 必须在运行时 PATH 中可用(agent 子进程通过 bun 调用 baoyu-skills)
54
+ # /usr/local/bin 已在默认 PATH 中,所有用户均可访问
55
+
56
+ # ==================== baoyu-skills 脚本预置 ====================
57
+ # 将完整的 baoyu-imagine 脚本预置到 ~/.baoyu-skills/ 目录
58
+ # 此目录是 main.ts loadExtendConfig() 的查找路径之一
59
+ # 避免依赖 Web UI 技能安装(可能只下载编译产物而丢失 .ts 源文件)
60
+ RUN mkdir -p /home/appuser/.baoyu-skills/baoyu-imagine && \
61
+ git clone --depth 1 https://github.com/JimLiu/baoyu-skills.git /tmp/baoyu-skills && \
62
+ cp -r /tmp/baoyu-skills/skills/baoyu-imagine/scripts \
63
+ /home/appuser/.baoyu-skills/baoyu-imagine/scripts && \
64
+ rm -rf /tmp/baoyu-skills
65
+
66
  # ==================== 工具安装 ====================
67
  # yq: 运行时修改 config.yaml
68
  RUN curl -sL https://github.com/mikefarah/yq/releases/latest/download/yq_linux_amd64 -o /usr/bin/yq && \
 
98
 
99
  COPY src/ /app/src/
100
  COPY entrypoint.sh /app/
101
+ COPY image-proxy.js /app/
102
+ COPY image-gen-siliconflow.ts /app/
103
  COPY config/config.yaml /data/.hermes/config.yaml
104
 
105
  # 创建数据目录
 
110
  RUN useradd -m -u 1000 appuser && \
111
  ln -sf /data/.hermes /home/appuser/.hermes && \
112
  mkdir -p /home/appuser/.cache && \
113
+ chown -R appuser:appuser /data /opt/hermes-web-ui /app /home/appuser && \
114
+ chown appuser:appuser /usr/local/bin
115
 
116
  USER appuser
117
 
entrypoint.sh CHANGED
@@ -13,6 +13,10 @@ set -e
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"
@@ -24,6 +28,12 @@ mkdir -p /data/.hermes/{cron,sessions,logs,memories,skills,pairing,hooks,image_c
24
  mkdir -p /data/.hermes-web-ui
25
  mkdir -p /app/logs
26
 
 
 
 
 
 
 
27
  # ==================== 数据恢复 ====================
28
  # 跳过从 Dataset 恢复 config.yaml(由本脚本根据环境变量重新生成)
29
  export SKIP_CONFIG_RESTORE=true
@@ -99,14 +109,14 @@ detect_main_model() {
99
  # ---- 检测辅助模型 ----
100
  detect_vision_model() {
101
  if [ -n "$VISION_MODEL" ]; then echo "$VISION_MODEL"; return; fi
102
- if [ -n "$NVIDIA_API_KEY" ]; then echo "qwen/qwen3.5-397b-a17b"; return; fi
103
  echo ""
104
  }
105
 
106
  detect_aux_model() {
107
  if [ -n "$AUX_MODEL" ]; then echo "$AUX_MODEL"; return; fi
108
- if [ -n "$NVIDIA_API_KEY" ]; then echo "moonshotai/kimi-k2.6"; return; fi
109
- if [ -n "$NVIDIA_API_KEY" ]; then echo "qwen/qwen3.5-122b-a10b"; return; fi
110
  echo ""
111
  }
112
 
@@ -224,6 +234,14 @@ terminal:
224
  backend: local
225
  timeout: 300
226
  shell: /bin/bash
 
 
 
 
 
 
 
 
227
 
228
  # 显示配置
229
  display:
@@ -357,6 +375,25 @@ export GATEWAY_ALLOW_ALL_USERS="${GATEWAY_ALLOW_ALL_USERS:-true}"
357
  # 导出 HERMES_MODEL 环境变量(进程级覆盖,影响 cron 等调度任务的模型选择)
358
  export HERMES_MODEL="$MAIN_MODEL"
359
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
360
  echo " ✅ Base URL 环境变量已设置"
361
  echo " ✅ API Server 环境变量已设置 (端口: 8642)"
362
  echo " ✅ HERMES_MODEL=$HERMES_MODEL (进程级模型覆盖)"
@@ -426,6 +463,526 @@ done
426
  RESTORED_COUNT=$(grep -c '=' "$ENV_FILE")
427
  echo " ✅ 已写入 ${RESTORED_COUNT} 个环境变量(含恢复的持久化变量)"
428
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
429
  # ==================== 启动数据同步服务 ====================
430
  SYNC_INTERVAL=${SYNC_INTERVAL:-60}
431
  echo "🔄 数据同步间隔: ${SYNC_INTERVAL}秒"
@@ -674,14 +1231,22 @@ else
674
  echo " ℹ️ Web UI 自动更新已禁用 (WEBUI_AUTO_UPDATE=false)"
675
  fi
676
 
677
- # ==================== 启动 Web UI (BFF Server) ====================
 
 
 
 
 
 
678
  echo "🌐 启动 Hermes Web UI..."
679
- echo " BFF Server: http://0.0.0.0:7860"
680
- echo " Upstream: http://127.0.0.1:8642"
 
 
681
  echo ""
682
 
683
  # 确保运行时环境变量设置完毕
684
- export PORT=7860
685
  export UPSTREAM=http://127.0.0.1:8642
686
  export HERMES_BIN=/usr/local/bin/hermes
687
  export HERMES_HOME=/data/.hermes
@@ -725,15 +1290,15 @@ cleanup() {
725
 
726
  trap cleanup SIGTERM SIGINT
727
 
728
- # 启动 BFF Server (替代 hermes dashboard)
729
  node /opt/hermes-web-ui/dist/server/index.js &
730
  BFF_PID=$!
731
 
732
  # 等待 BFF 就绪
733
- echo " ⏳ 等待 Web UI 就绪..."
734
  BFF_READY=false
735
  for i in $(seq 1 20); do
736
- if curl -sf http://localhost:7860/health > /dev/null 2>&1; then
737
  BFF_READY=true
738
  break
739
  fi
@@ -741,9 +1306,32 @@ for i in $(seq 1 20); do
741
  done
742
 
743
  if [ "$BFF_READY" = true ]; then
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
744
  echo " ✅ Web UI 已就绪 → http://localhost:7860"
 
745
  else
746
- echo " ⚠️ Web UI 未在 20 秒内就绪,请查看日志"
747
  fi
748
 
749
  # 再次验证模型配置(BFF 启动可能修改 config.yaml)
@@ -770,5 +1358,6 @@ if [ -f "$CONFIG_FILE" ]; then
770
  fi
771
  fi
772
 
773
- # 等待 BFF 主进程(前台阻塞,容器生命周期由 BFF 控制)
774
- wait $BFF_PID
 
 
13
  echo "🚀 Hermes Agent v0.10.0 - Hugging Face Spaces"
14
  echo "=============================================="
15
 
16
+ # 确保 bun 在 PATH 中(baoyu-skills 子进程需要)
17
+ # bun 已安装在 /usr/local/bin(全局可访问),/home/appuser/.local/bin 用于 wrapper 脚本
18
+ export PATH="$PATH:/usr/local/bin:/home/appuser/.local/bin"
19
+
20
  # 检查必要的环境变量
21
  if [ -z "$HF_DATASET_REPO" ]; then
22
  echo "⚠️ 警告: HF_DATASET_REPO 未设置,数据将不会持久化到 Dataset"
 
28
  mkdir -p /data/.hermes-web-ui
29
  mkdir -p /app/logs
30
 
31
+ echo "🔍 调试:初始化目录结构后检查"
32
+ pwd
33
+ ls -al /data/
34
+ ls -al /data/.hermes/
35
+ ls -al /data/.hermes/skills/
36
+
37
  # ==================== 数据恢复 ====================
38
  # 跳过从 Dataset 恢复 config.yaml(由本脚本根据环境变量重新生成)
39
  export SKIP_CONFIG_RESTORE=true
 
109
  # ---- 检测辅助模型 ----
110
  detect_vision_model() {
111
  if [ -n "$VISION_MODEL" ]; then echo "$VISION_MODEL"; return; fi
112
+ if [ -n "$GEMINI_API_KEY" ] || [ -n "$GOOGLE_API_KEY" ]; then echo "google/gemini-2.5-flash"; return; fi
113
  echo ""
114
  }
115
 
116
  detect_aux_model() {
117
  if [ -n "$AUX_MODEL" ]; then echo "$AUX_MODEL"; return; fi
118
+ if [ -n "$OPENROUTER_API_KEY" ]; then echo "google/gemini-3-flash-preview"; return; fi
119
+ if [ -n "$GEMINI_API_KEY" ] || [ -n "$GOOGLE_API_KEY" ]; then echo "google/gemini-2.0-flash"; return; fi
120
  echo ""
121
  }
122
 
 
234
  backend: local
235
  timeout: 300
236
  shell: /bin/bash
237
+ # 允许 baoyu-skills 使用的 API Key 传递到子进程
238
+ # (Hermes 默认会过滤包含 KEY/TOKEN/SECRET 的环境变量)
239
+ env_passthrough:
240
+ - GEMINI_API_KEY
241
+ - GOOGLE_API_KEY
242
+ - SILICONFLOW_API_KEY
243
+ - GOOGLE_IMAGE_MODEL
244
+ - GOOGLE_BASE_URL
245
 
246
  # 显示配置
247
  display:
 
375
  # 导出 HERMES_MODEL 环境变量(进程级覆盖,影响 cron 等调度任务的模型选择)
376
  export HERMES_MODEL="$MAIN_MODEL"
377
 
378
+ # 导出图像生成所需的环境变量(确保 baoyu-imagine 技能能检测到)
379
+ if [ -n "$SILICONFLOW_API_KEY" ]; then
380
+ export SILICONFLOW_API_KEY
381
+ export SILICONFLOW_BASE_URL="${SILICONFLOW_BASE_URL:-https://api.siliconflow.cn/v1}"
382
+ echo " ✅ SILICONFLOW_API_KEY 已导出(baoyu-imagine 技能可用)"
383
+ fi
384
+
385
+ if [ -n "$GEMINI_API_KEY" ]; then
386
+ export GEMINI_API_KEY
387
+ export GEMINI_BASE_URL="${GEMINI_BASE_URL:-https://generativelanguage.googleapis.com}"
388
+ # baoyu-imagine 的 google provider 使用 GOOGLE_API_KEY
389
+ export GOOGLE_API_KEY="${GEMINI_API_KEY}"
390
+ export GOOGLE_BASE_URL="${GEMINI_BASE_URL:-https://generativelanguage.googleapis.com}"
391
+ export GOOGLE_IMAGE_MODEL="gemini-3.1-flash-image-preview"
392
+ echo " ✅ GEMINI_API_KEY 已导出(baoyu-imagine 技能可用)"
393
+ echo " ✅ GOOGLE_API_KEY 已设置(baoyu-imagine google provider)"
394
+ echo " ✅ GOOGLE_IMAGE_MODEL=gemini-3.1-flash-image-preview"
395
+ fi
396
+
397
  echo " ✅ Base URL 环境变量已设置"
398
  echo " ✅ API Server 环境变量已设置 (端口: 8642)"
399
  echo " ✅ HERMES_MODEL=$HERMES_MODEL (进程级模型覆盖)"
 
463
  RESTORED_COUNT=$(grep -c '=' "$ENV_FILE")
464
  echo " ✅ 已写入 ${RESTORED_COUNT} 个环境变量(含恢复的持久化变量)"
465
 
466
+ # ==================== 配置 baoyu-skills 技能 (EXTEND.md) ====================
467
+ # baoyu-imagine / baoyu-cover-image / baoyu-article-illustrator 的 EXTEND.md
468
+ # 路径规范: $HOME/.baoyu-skills/<skill-name>/EXTEND.md
469
+ # (注意: .baoyu-skills 有连字符, 不是 .baoyu/skills)
470
+ # main.ts loadExtendConfig() 查找顺序: {cwd}/.baoyu-skills/ > $XDG_CONFIG_HOME > $HOME/.baoyu-skills/
471
+ BAOYU_SKILLS_BASE="/home/appuser/.baoyu-skills"
472
+
473
+ # --- baoyu-imagine (图像生成后端) ---
474
+ IMAGINE_EXTEND_DIR="${BAOYU_SKILLS_BASE}/baoyu-imagine"
475
+ IMAGINE_EXTEND_FILE="${IMAGINE_EXTEND_DIR}/EXTEND.md"
476
+
477
+ if [ -n "$SILICONFLOW_API_KEY" ] || [ -n "$GEMINI_API_KEY" ]; then
478
+ echo "⚙️ 配置 baoyu-imagine 技能..."
479
+ mkdir -p "${IMAGINE_EXTEND_DIR}"
480
+
481
+ if [ -n "$GEMINI_API_KEY" ]; then
482
+ # Gemini 作为主供应商(图像质量更好)
483
+ # SiliconFlow 作为备用(在 wrapper 脚本中实现 fallback)
484
+ cat > "${IMAGINE_EXTEND_FILE}" << EOF_IMAGINE
485
+ # Baoyu Imagine Configuration
486
+
487
+ # 默认供应商 (Google/Gemini)
488
+ default_provider = "google"
489
+
490
+ # 默认质量
491
+ default_quality = "2k"
492
+
493
+ # 默认宽高比
494
+ default_aspect_ratio = "16:9"
495
+
496
+ # 默认图片尺寸 (Google 使用 1K/2K/4K)
497
+ default_image_size = "2K"
498
+
499
+ # Google/Gemini 供应商配置
500
+ [default_model.google]
501
+ provider = "google"
502
+ model = "gemini-3.1-flash-image-preview"
503
+
504
+ # 批量设置
505
+ [batch]
506
+ max_workers = 4
507
+ EOF_IMAGINE
508
+ echo " ✅ baoyu-imagine EXTEND.md 已写入 (Gemini 主供应商)"
509
+
510
+ # 同时导出 SiliconFlow 配置到 EXTEND.md(备用)
511
+ if [ -n "$SILICONFLOW_API_KEY" ]; then
512
+ echo " 🔄 SiliconFlow 已配置为备用供应商"
513
+ fi
514
+ elif [ -n "$SILICONFLOW_API_KEY" ]; then
515
+ # 仅 SiliconFlow
516
+ cat > "${IMAGINE_EXTEND_FILE}" << EOF_IMAGINE
517
+ # Baoyu Imagine Configuration
518
+
519
+ # 默认供应商
520
+ default_provider = "siliconflow"
521
+
522
+ # 默认质量
523
+ default_quality = "2k"
524
+
525
+ # 默认宽高比
526
+ default_aspect_ratio = "16:9"
527
+
528
+ # 默认图片尺寸
529
+ default_image_size = "1024x1024"
530
+
531
+ # SiliconFlow 供应商配置
532
+ [default_model.siliconflow]
533
+ provider = "siliconflow"
534
+ model = "Kwai-Kolors/Kolors"
535
+
536
+ # 批量设置
537
+ [batch]
538
+ max_workers = 4
539
+ EOF_IMAGINE
540
+ echo " ✅ baoyu-imagine EXTEND.md 已写入 (SiliconFlow 后端)"
541
+ fi
542
+
543
+ # 生成 ~/.baoyu-skills/.env 文件(绕过 Hermes 环境变量过滤)
544
+ # Hermes 的 terminal 子进程会过滤包含 KEY/TOKEN/SECRET 的环境变量
545
+ # baoyu-imagine 的 main.ts 会自动加载 ~/.baoyu-skills/.env
546
+ BAOYU_ENV_FILE="${BAOYU_SKILLS_BASE}/.env"
547
+ echo " 📝 生成 baoyu-skills .env 文件..."
548
+ > "${BAOYU_ENV_FILE}"
549
+ if [ -n "$GEMINI_API_KEY" ]; then
550
+ echo "GEMINI_API_KEY=${GEMINI_API_KEY}" >> "${BAOYU_ENV_FILE}"
551
+ echo "GOOGLE_API_KEY=${GEMINI_API_KEY}" >> "${BAOYU_ENV_FILE}"
552
+ echo "GOOGLE_IMAGE_MODEL=gemini-3.1-flash-image-preview" >> "${BAOYU_ENV_FILE}"
553
+ echo "GOOGLE_BASE_URL=${GEMINI_BASE_URL:-https://generativelanguage.googleapis.com}" >> "${BAOYU_ENV_FILE}"
554
+ fi
555
+ if [ -n "$SILICONFLOW_API_KEY" ]; then
556
+ echo "SILICONFLOW_API_KEY=${SILICONFLOW_API_KEY}" >> "${BAOYU_ENV_FILE}"
557
+ fi
558
+ echo " ✅ .env 文件已写入 (${BAOYU_ENV_FILE})"
559
+ else
560
+ echo " ℹ️ 未配置 SILICONFLOW_API_KEY 或 GEMINI_API_KEY,跳过 baoyu-imagine 技能配置"
561
+ fi
562
+
563
+ # --- baoyu-cover-image (封面图生成) ---
564
+ COVER_EXTEND_DIR="${BAOYU_SKILLS_BASE}/baoyu-cover-image"
565
+ COVER_EXTEND_FILE="${COVER_EXTEND_DIR}/EXTEND.md"
566
+
567
+ if [ -n "$SILICONFLOW_API_KEY" ] || [ -n "$GEMINI_API_KEY" ]; then
568
+ echo "⚙️ 配置 baoyu-cover-image 技能..."
569
+ mkdir -p "${COVER_EXTEND_DIR}"
570
+ cat > "${COVER_EXTEND_FILE}" << EOF_COVER
571
+ # Baoyu Cover Image Configuration
572
+
573
+ # 首选图像后端
574
+ preferred_image_backend = "baoyu-imagine"
575
+
576
+ # 默认输出目录 (图片保存到哪里)
577
+ # independent = cover-image/{topic-slug}/
578
+ # imgs-subdir = {article-dir}/imgs/
579
+ # same-dir = {article-dir}/
580
+ # 使用 independent,图片会保存到 /data/cover-image/{topic-slug}/
581
+ # image-proxy.js 已配置扫描此目录
582
+ default_output_dir = "independent"
583
+
584
+ # 默认宽高比
585
+ default_aspect = "16:9"
586
+
587
+ # 默认类型与风格
588
+ preferred_type = "scene"
589
+ preferred_palette = "warm"
590
+ preferred_rendering = "digital"
591
+ preferred_font = "clean"
592
+
593
+ # 语言
594
+ language = "zh"
595
+ EOF_COVER
596
+ echo " ✅ baoyu-cover-image EXTEND.md 已写入 (${COVER_EXTEND_FILE})"
597
+ fi
598
+
599
+ # --- baoyu-article-illustrator (文章配图) ---
600
+ ILLUSTRATOR_EXTEND_DIR="${BAOYU_SKILLS_BASE}/baoyu-article-illustrator"
601
+ ILLUSTRATOR_EXTEND_FILE="${ILLUSTRATOR_EXTEND_DIR}/EXTEND.md"
602
+
603
+ if [ -n "$SILICONFLOW_API_KEY" ] || [ -n "$GEMINI_API_KEY" ]; then
604
+ echo "⚙️ 配置 baoyu-article-illustrator 技能..."
605
+ mkdir -p "${ILLUSTRATOR_EXTEND_DIR}"
606
+ cat > "${ILLUSTRATOR_EXTEND_FILE}" << EOF_ILLUSTRATOR
607
+ # Baoyu Article Illustrator Configuration
608
+
609
+ # 首选图像后端
610
+ preferred_image_backend = "baoyu-imagine"
611
+
612
+ # 默认输出目录
613
+ default_output_dir = "imgs-subdir"
614
+
615
+ # 默认类型与风格
616
+ preferred_type = "infographic"
617
+ preferred_style = "minimal-flat"
618
+ preferred_palette = "warm"
619
+
620
+ # 语言
621
+ language = "zh"
622
+ EOF_ILLUSTRATOR
623
+ echo " ✅ baoyu-article-illustrator EXTEND.md 已写入 (${ILLUSTRATOR_EXTEND_FILE})"
624
+ fi
625
+
626
+ # --- 调试: 验证 EXTEND.md 文件 ---
627
+ if [ -n "$SILICONFLOW_API_KEY" ] || [ -n "$GEMINI_API_KEY" ]; then
628
+ echo "🔍 调试:验证 baoyu-skills EXTEND.md 文件"
629
+ ls -la "${BAOYU_SKILLS_BASE}/" 2>/dev/null || echo " ⚠️ ${BAOYU_SKILLS_BASE} 不存在"
630
+ for skill_dir in "${BAOYU_SKILLS_BASE}"/*/; do
631
+ if [ -f "${skill_dir}EXTEND.md" ]; then
632
+ echo " ✅ ${skill_dir}EXTEND.md 存在"
633
+ # 显示 provider 配置(用于诊断)
634
+ grep -E "^(default_provider|preferred_image_backend)" "${skill_dir}EXTEND.md" 2>/dev/null || true
635
+ else
636
+ echo " ⚠️ ${skill_dir}EXTEND.md 缺失"
637
+ fi
638
+ done
639
+ fi
640
+
641
+ # ==================== 修复 baoyu-imagine 技能脚本缺失问题 ====================
642
+ # Hermes Skills Hub 安装 baoyu-imagine 时只下载了 SKILL.md 和 references
643
+ # 缺少 scripts/ 目录和 package.json,导致 agent 无法调用 bun scripts/main.ts
644
+ # 修复方案:将 Dockerfile 构建时预置的完整脚本复制到 skills 目录
645
+ # 如果 Dockerfile 预置失败(���络/缓存问题),则运行时下载
646
+
647
+ SKILL_IMAGINE_DIR="/data/.hermes/skills/baoyu-imagine"
648
+ SKILL_IMAGINE_SCRIPTS="${SKILL_IMAGINE_DIR}/scripts"
649
+ BUILTIN_IMAGINE_SCRIPTS="${BAOYU_SKILLS_BASE}/baoyu-imagine/scripts"
650
+
651
+ # 调试:显示脚本源状态
652
+ echo "🔍 调试:检查 baoyu-imagine 脚本源..."
653
+ echo " 内置脚本路径: ${BUILTIN_IMAGINE_SCRIPTS}"
654
+ if [ -d "$BUILTIN_IMAGINE_SCRIPTS" ]; then
655
+ echo " ✅ 内置脚本目录存在"
656
+ ls -la "${BUILTIN_IMAGINE_SCRIPTS}/" 2>/dev/null | head -5 || echo " ⚠️ 无法列出内置脚本内容"
657
+ else
658
+ echo " ⚠️ 内置脚本目录不存在(Dockerfile 构建时可能下载失败)"
659
+ fi
660
+ echo " 目标脚本路径: ${SKILL_IMAGINE_SCRIPTS}"
661
+ if [ -f "${SKILL_IMAGINE_SCRIPTS}/main.ts" ]; then
662
+ echo " ✅ 目标脚本已存在"
663
+ else
664
+ echo " ⚠️ 目标脚本缺失"
665
+ fi
666
+
667
+ # 主修复逻辑
668
+ if [ -n "$GEMINI_API_KEY" ]; then
669
+ echo "⚙️ 修复 baoyu-imagine 技能脚本..."
670
+
671
+ # 1. 确保 skills 目录存在
672
+ mkdir -p "${SKILL_IMAGINE_DIR}"
673
+
674
+ # 2. 获取脚本(强制使用最新原始版本)
675
+ # 注意:Dataset 恢复可能包含旧版本(Pollinations/SiliconFlow 特化版)
676
+ # 必须重新下载原始 baoyu-skills 脚本以确保配置系统正常工作
677
+ # 先删除可能存在的只读旧版本(chmod 555 导致 cp -r 无法覆盖)
678
+ if [ -d "$BUILTIN_IMAGINE_SCRIPTS" ] && [ -f "${BUILTIN_IMAGINE_SCRIPTS}/main.ts" ]; then
679
+ echo " 📁 从内置目录复制 scripts/..."
680
+ rm -rf "${SKILL_IMAGINE_DIR}/scripts" 2>/dev/null || true
681
+ cp -r "${BUILTIN_IMAGINE_SCRIPTS}" "${SKILL_IMAGINE_DIR}/"
682
+ else
683
+ echo " 📥 内置脚本不可用,运行时下载..."
684
+ # 强制重新下载,忽略 Dataset 恢复的旧版本
685
+ rm -rf "${SKILL_IMAGINE_SCRIPTS}"
686
+ mkdir -p "${SKILL_IMAGINE_SCRIPTS}"
687
+ TEMP_SKILLS_DIR="/tmp/baoyu-skills-download"
688
+ rm -rf "$TEMP_SKILLS_DIR"
689
+ if git clone --depth 1 https://github.com/JimLiu/baoyu-skills.git "$TEMP_SKILLS_DIR" 2>/dev/null; then
690
+ if [ -f "${TEMP_SKILLS_DIR}/skills/baoyu-imagine/scripts/main.ts" ]; then
691
+ cp -r "${TEMP_SKILLS_DIR}/skills/baoyu-imagine/scripts/" "${SKILL_IMAGINE_DIR}/"
692
+ echo " ✅ 运行时下载成功(原始完整版本)"
693
+ else
694
+ echo " ❌ 下载的仓库中找不到 main.ts"
695
+ fi
696
+ rm -rf "$TEMP_SKILLS_DIR"
697
+ else
698
+ echo " ❌ git clone 失败,请检查网络连接"
699
+ echo " ⚠️ 使用现有脚本(可能不是原始版本)"
700
+ fi
701
+ fi
702
+
703
+ # 3. 创建 package.json(如果不存在)
704
+ if [ ! -f "${SKILL_IMAGINE_DIR}/package.json" ]; then
705
+ echo " 📝 创建 package.json..."
706
+ cat > "${SKILL_IMAGINE_DIR}/package.json" << 'EOF_PKG'
707
+ {
708
+ "name": "baoyu-imagine",
709
+ "version": "1.58.0",
710
+ "type": "module",
711
+ "scripts": {
712
+ "build": "tsc",
713
+ "test": "bun test"
714
+ },
715
+ "dependencies": {
716
+ "@google/generative-ai": "^0.24.0"
717
+ },
718
+ "devDependencies": {
719
+ "typescript": "^5.8.0",
720
+ "@types/node": "^22.14.0"
721
+ }
722
+ }
723
+ EOF_PKG
724
+ fi
725
+
726
+ # 4. 修复 google.ts 的 generateWithGemini 和 extractInlineImageData 函数
727
+ # 修复1: responseModalities 从 ["IMAGE"] 改为 ["TEXT", "IMAGE"]
728
+ # 修复2: extractInlineImageData 支持 inline_data 字段(snake_case)
729
+ echo " 🔧 修复 google.ts 以支持 Google API 响应格式..."
730
+ if [ -f "${SKILL_IMAGINE_DIR}/scripts/providers/google.ts" ]; then
731
+ node -e "
732
+ const fs = require('fs');
733
+ const filePath = '${SKILL_IMAGINE_DIR}/scripts/providers/google.ts';
734
+ let content = fs.readFileSync(filePath, 'utf8');
735
+ let modified = false;
736
+
737
+ // 修复1: responseModalities
738
+ if (content.includes('responseModalities: [\"IMAGE\"],')) {
739
+ content = content.replace(/responseModalities: \\[\"IMAGE\"\\],/g, 'responseModalities: [\"TEXT\", \"IMAGE\"],');
740
+ console.log(' ✅ 已修复 responseModalities: [\"TEXT\", \"IMAGE\"]');
741
+ modified = true;
742
+ }
743
+
744
+ // 修复2: extractInlineImageData 支持 inline_data 字段
745
+ const oldLine = ' const data = part.inlineData?.data;';
746
+ const newLine = ' const data = part.inlineData?.data ?? part.inline_data?.data;';
747
+ if (content.includes(oldLine)) {
748
+ content = content.replace(oldLine, newLine);
749
+ console.log(' ✅ 已修复 extractInlineImageData 函数');
750
+ modified = true;
751
+ }
752
+
753
+ if (modified) {
754
+ fs.writeFileSync(filePath, content, 'utf8');
755
+ console.log(' ✅ 所有修复应用完成');
756
+ } else {
757
+ console.log(' ⚠️ 未找到需要修复的代码');
758
+ }
759
+ "
760
+ fi
761
+
762
+ # 5. 安装依赖(如果 node_modules 不存在)
763
+ if [ ! -d "${SKILL_IMAGINE_DIR}/node_modules" ]; then
764
+ echo " 📦 安装 baoyu-imagine 依赖..."
765
+ (cd "${SKILL_IMAGINE_DIR}" && bun install) 2>&1 | tail -5 || {
766
+ echo " ⚠️ bun install 失败,尝试 npm install..."
767
+ (cd "${SKILL_IMAGINE_DIR}" && npm install) 2>&1 | tail -5 || true
768
+ }
769
+ fi
770
+
771
+ # 5. 最终验证(强检查)
772
+ echo " 🔍 验证脚本完整性..."
773
+ if [ -f "${SKILL_IMAGINE_SCRIPTS}/main.ts" ]; then
774
+ echo " ✅ baoyu-imagine 技能已就绪"
775
+ echo " 脚本: ${SKILL_IMAGINE_SCRIPTS}/main.ts"
776
+ ls -lh "${SKILL_IMAGINE_SCRIPTS}/main.ts"
777
+ if [ -d "${SKILL_IMAGINE_DIR}/node_modules" ]; then
778
+ echo " 依赖: 已安装 (${SKILL_IMAGINE_DIR}/node_modules)"
779
+ else
780
+ echo " ⚠️ 依赖: 未安装"
781
+ fi
782
+ else
783
+ echo " ❌ baoyu-imagine 技能修复失败: main.ts 仍然缺失"
784
+ echo " 这通常是因为网络问题导致无法下载脚本"
785
+ fi
786
+
787
+ # 6. 检测可用的图像生成后端并配置
788
+ # 优先级: gemini > siliconflow
789
+ # Gemini 图像质量更好,SiliconFlow 作为备用(国内稳定)
790
+ if [ -n "$GEMINI_API_KEY" ]; then
791
+ echo " 🎯 检测到 GEMINI_API_KEY,启用 Gemini 主供应商..."
792
+ echo " 模型: gemini-3.1-flash-image-preview"
793
+
794
+ # 恢复原始 main.ts(支持 google provider)
795
+ # 如果之前被 siliconflow 版本替换,从备份恢复
796
+ if [ -f "${SKILL_IMAGINE_SCRIPTS}/main.ts.orig" ]; then
797
+ cp "${SKILL_IMAGINE_SCRIPTS}/main.ts.orig" "${SKILL_IMAGINE_SCRIPTS}/main.ts"
798
+ echo " ✅ 已恢复原始 main.ts(支持 google provider)"
799
+ fi
800
+
801
+ # 创建智能包装脚本
802
+ # 使用 /usr/local/bin 而非 /home/appuser/.local/bin
803
+ # 因为 /usr/local/bin 在系统默认 PATH 中,Agent 子进程可直接调用
804
+ WRAPPER_DIR="/usr/local/bin"
805
+ mkdir -p "$WRAPPER_DIR"
806
+
807
+ if [ -n "$SILICONFLOW_API_KEY" ]; then
808
+ # 双供应商:Gemini 主 + SiliconFlow 备
809
+ # 使用双引号 heredoc 以展开 SKILL_IMAGINE_SCRIPTS 变量
810
+ cat > "${WRAPPER_DIR}/baoyu-imagine" << EOF_WRAPPER
811
+ #!/bin/bash
812
+ # Smart wrapper: Gemini primary, SiliconFlow fallback
813
+
814
+ # 加载 baoyu-skills .env 文件(绕过 Hermes 环境变量过滤)
815
+ if [ -f ~/.baoyu-skills/.env ]; then
816
+ set -a
817
+ source ~/.baoyu-skills/.env
818
+ set +a
819
+ fi
820
+
821
+ # 同时尝试从环境变量加载(如果未被过滤)
822
+ export GEMINI_API_KEY="\${GEMINI_API_KEY:-\$GEMINI_API_KEY}"
823
+ export GOOGLE_API_KEY="\${GOOGLE_API_KEY:-\$GEMINI_API_KEY}"
824
+ export GOOGLE_IMAGE_MODEL="\${GOOGLE_IMAGE_MODEL:-gemini-3.1-flash-image-preview}"
825
+ export GOOGLE_BASE_URL="\${GOOGLE_BASE_URL:-https://generativelanguage.googleapis.com}"
826
+ export SILICONFLOW_API_KEY="\${SILICONFLOW_API_KEY:-\$SILICONFLOW_API_KEY}"
827
+
828
+ # 确保图片保存到可访问的目录
829
+ mkdir -p /data/.hermes/image_cache
830
+ cd /data/.hermes/image_cache
831
+
832
+ # 尝试 Gemini 主供应商
833
+ # baoyu-imagine 的 google provider 会自动使用 GOOGLE_IMAGE_MODEL
834
+ echo "🎯 Trying Gemini (gemini-3.1-flash-image-preview)..."
835
+ if bun "${SKILL_IMAGINE_SCRIPTS}/main.ts" "\$@" 2>/tmp/gemini_error.log; then
836
+ exit 0
837
+ fi
838
+
839
+ # Fallback 到 SiliconFlow
840
+ echo "⚠️ Gemini failed, falling back to SiliconFlow (Kwai-Kolors/Kolors)..."
841
+ if [ -f "/app/image-gen-siliconflow.ts" ]; then
842
+ exec bun "/app/image-gen-siliconflow.ts" --model "Kwai-Kolors/Kolors" "\$@"
843
+ else
844
+ echo "❌ SiliconFlow fallback script not found"
845
+ cat /tmp/gemini_error.log >&2
846
+ exit 1
847
+ fi
848
+ EOF_WRAPPER
849
+ echo " ✅ 智能包装脚本: ${WRAPPER_DIR}/baoyu-imagine (Gemini主 + SiliconFlow备)"
850
+ else
851
+ # 仅 Gemini
852
+ cat > "${WRAPPER_DIR}/baoyu-imagine" << EOF_WRAPPER
853
+ #!/bin/bash
854
+ # Gemini-only wrapper
855
+
856
+ # 加载 baoyu-skills .env 文件(绕过 Hermes 环境变量过滤)
857
+ if [ -f ~/.baoyu-skills/.env ]; then
858
+ set -a
859
+ source ~/.baoyu-skills/.env
860
+ set +a
861
+ fi
862
+
863
+ # 同时尝试从环境变量加载(如果未被过滤)
864
+ export GEMINI_API_KEY="\${GEMINI_API_KEY:-\$GEMINI_API_KEY}"
865
+ export GOOGLE_API_KEY="\${GOOGLE_API_KEY:-\$GEMINI_API_KEY}"
866
+ export GOOGLE_IMAGE_MODEL="\${GOOGLE_IMAGE_MODEL:-gemini-3.1-flash-image-preview}"
867
+ export GOOGLE_BASE_URL="\${GOOGLE_BASE_URL:-https://generativelanguage.googleapis.com}"
868
+
869
+ mkdir -p /data/.hermes/image_cache
870
+ cd /data/.hermes/image_cache
871
+
872
+ exec bun "${SKILL_IMAGINE_SCRIPTS}/main.ts" "\$@"
873
+ EOF_WRAPPER
874
+ echo " ✅ 包装脚本: ${WRAPPER_DIR}/baoyu-imagine (仅 Gemini)"
875
+ fi
876
+ chmod +x "${WRAPPER_DIR}/baoyu-imagine"
877
+
878
+ elif [ -n "$SILICONFLOW_API_KEY" ]; then
879
+ echo " 🎯 检测到 SILICONFLOW_API_KEY,启用 SiliconFlow 后端..."
880
+
881
+ # 备份原始 main.ts
882
+ if [ ! -f "${SKILL_IMAGINE_SCRIPTS}/main.ts.orig" ]; then
883
+ cp "${SKILL_IMAGINE_SCRIPTS}/main.ts" "${SKILL_IMAGINE_SCRIPTS}/main.ts.orig"
884
+ fi
885
+
886
+ # 使用增强版 SiliconFlow 生成器(支持风格/尺寸/品质参数)
887
+ ENHANCED_GEN="/app/image-gen-siliconflow.ts"
888
+ if [ -f "$ENHANCED_GEN" ]; then
889
+ cp "$ENHANCED_GEN" "${SKILL_IMAGINE_SCRIPTS}/main.ts"
890
+ echo " ✅ 已复制增强版生成器 (${ENHANCED_GEN})"
891
+ else
892
+ echo " ⚠️ 增强版生成器不存在,使用内联简化版..."
893
+ # 内联简化版作为 fallback
894
+ cat > "${SKILL_IMAGINE_SCRIPTS}/main.ts" << 'EOF_SILICONFLOW'
895
+ #!/usr/bin/env bun
896
+ // Fallback simplified version
897
+ interface CliArgs { prompt: string; imagePath: string; model: string; }
898
+ function parseArgs(argv: string[]): CliArgs {
899
+ const args: CliArgs = { prompt: "", imagePath: "", model: "black-forest-labs/FLUX.1-dev" };
900
+ for (let i = 0; i < argv.length; i++) {
901
+ if (argv[i] === "--prompt" || argv[i] === "-p") args.prompt = argv[++i] || "";
902
+ else if (argv[i] === "--image") args.imagePath = argv[++i] || "";
903
+ else if (argv[i] === "--model" || argv[i] === "-m") args.model = argv[++i] || args.model;
904
+ }
905
+ return args;
906
+ }
907
+ async function generateImage(args: CliArgs): Promise<void> {
908
+ const apiKey = process.env.SILICONFLOW_API_KEY;
909
+ if (!apiKey) { console.error("Error: SILICONFLOW_API_KEY not set"); process.exit(1); }
910
+ console.log(`🎨 Generating image with ${args.model}...`);
911
+ const response = await fetch("https://api.siliconflow.cn/v1/images/generations", {
912
+ method: "POST", headers: { "Authorization": `Bearer ${apiKey}`, "Content-Type": "application/json" },
913
+ body: JSON.stringify({ model: args.model, prompt: args.prompt, image_size: "1024x1024", num_inference_steps: 20 })
914
+ });
915
+ if (!response.ok) { console.error(`❌ API error (${response.status})`); process.exit(1); }
916
+ const result = await response.json();
917
+ if (!result.images?.length) { console.error("❌ No images in response"); process.exit(1); }
918
+ const imageUrl = result.images[0].url;
919
+ const imageResponse = await fetch(imageUrl);
920
+ const imageBuffer = await imageResponse.arrayBuffer();
921
+ await Bun.write(args.imagePath, new Uint8Array(imageBuffer));
922
+ console.log(`✅ Saved: ${args.imagePath} (${imageBuffer.byteLength} bytes)`);
923
+ }
924
+ const args = parseArgs(process.argv.slice(2));
925
+ if (!args.prompt || !args.imagePath) { console.error("Usage: bun main.ts --prompt <text> --image <path>"); process.exit(1); }
926
+ await generateImage(args);
927
+ EOF_SILICONFLOW
928
+ fi
929
+
930
+ echo " ✅ 已配置 SiliconFlow 后端"
931
+ echo " 模型: Kwai-Kolors/Kolors"
932
+ echo " API: https://api.siliconflow.cn/v1/images/generations"
933
+ echo " 功能: --ar, --size, --quality, --n, --seed, --promptfiles"
934
+
935
+ # 创建包装脚本(baoyu skills 调用 baoyu-imagine 命令)
936
+ # WRAPPER_DIR 已改为 /usr/local/bin,确保在 Agent PATH 中
937
+ cat > "${WRAPPER_DIR}/baoyu-imagine" << EOF_WRAPPER
938
+ #!/bin/bash
939
+ # SiliconFlow wrapper
940
+
941
+ # 加载 baoyu-skills .env 文件(绕过 Hermes 环境变量过滤)
942
+ if [ -f ~/.baoyu-skills/.env ]; then
943
+ set -a
944
+ source ~/.baoyu-skills/.env
945
+ set +a
946
+ fi
947
+
948
+ # 同时尝试从环境变量加载(如果未被过滤)
949
+ export SILICONFLOW_API_KEY="\${SILICONFLOW_API_KEY:-\$SILICONFLOW_API_KEY}"
950
+
951
+ # 确保图片保存到可访问的目录
952
+ mkdir -p /data/.hermes/image_cache
953
+ cd /data/.hermes/image_cache
954
+
955
+ exec bun "${SKILL_IMAGINE_SCRIPTS}/main.ts" "\$@"
956
+ EOF_WRAPPER
957
+ chmod +x "${WRAPPER_DIR}/baoyu-imagine"
958
+ echo " ✅ 包装脚本: ${WRAPPER_DIR}/baoyu-imagine"
959
+ else
960
+ echo " ⚠️ 未检测到 SILICONFLOW_API_KEY 或 GEMINI_API_KEY"
961
+ echo " 图像生成功能不可用"
962
+ echo " 请设置以下环境变量之一:"
963
+ echo " - GEMINI_API_KEY (推荐,图像质量更好)"
964
+ echo " - SILICONFLOW_API_KEY (国内可访问)"
965
+ fi
966
+
967
+ # 7. 设置文件权限(只读,防止 agent 意外修改)
968
+ chmod -R 555 "${SKILL_IMAGINE_SCRIPTS}/" 2>/dev/null || true
969
+ echo " 🔒 已锁定 scripts/ 目录"
970
+
971
+ # 8. 创建 skills 目录下的 EXTEND.md 软链接
972
+ # baoyu-imagine 会优先查找 skill 目录下的 EXTEND.md
973
+ OLD_EXTEND="/data/.hermes/skills/baoyu-imagine/EXTEND.md"
974
+ if [ -f "${IMAGINE_EXTEND_FILE}" ]; then
975
+ mkdir -p "$(dirname "$OLD_EXTEND")"
976
+ ln -sf "${IMAGINE_EXTEND_FILE}" "$OLD_EXTEND"
977
+ echo " 🔗 创建 EXTEND.md 软链接: $OLD_EXTEND -> ${IMAGINE_EXTEND_FILE}"
978
+ fi
979
+ fi
980
+
981
+ # ==================== 确保 image_cache 目录可写 ====================
982
+ mkdir -p /data/.hermes/image_cache
983
+ chmod 755 /data/.hermes/image_cache
984
+ chown appuser:appuser /data/.hermes/image_cache 2>/dev/null || true
985
+
986
  # ==================== 启动数据同步服务 ====================
987
  SYNC_INTERVAL=${SYNC_INTERVAL:-60}
988
  echo "🔄 数据同步间隔: ${SYNC_INTERVAL}秒"
 
1231
  echo " ℹ️ Web UI 自动更新已禁用 (WEBUI_AUTO_UPDATE=false)"
1232
  fi
1233
 
1234
+ # ==================== 启动 Web UI (BFF Server + Image Proxy) ====================
1235
+ # 架构: image-proxy.js (:7860) → BFF (:7861) → Gateway (:8642)
1236
+ #
1237
+ # image-proxy.js 在 :7860 监听:
1238
+ # /images/ → 图片文件浏览/下载 (来自 /data/.hermes/image_cache)
1239
+ # 其他所有请求 → HTTP/WebSocket 透传给 BFF :7861
1240
+ # BFF 在 :7861 内部监听 (hermes-web-ui)
1241
  echo "🌐 启动 Hermes Web UI..."
1242
+ echo " Image+Proxy: http://0.0.0.0:7860"
1243
+ echo " BFF Server: http://127.0.0.1:7861"
1244
+ echo " Upstream: http://127.0.0.1:8642"
1245
+ echo " 📷 图片浏览: http://localhost:7860/images/"
1246
  echo ""
1247
 
1248
  # 确保运行时环境变量设置完毕
1249
+ export PORT=7861
1250
  export UPSTREAM=http://127.0.0.1:8642
1251
  export HERMES_BIN=/usr/local/bin/hermes
1252
  export HERMES_HOME=/data/.hermes
 
1290
 
1291
  trap cleanup SIGTERM SIGINT
1292
 
1293
+ # 启动 BFF Server (内部端口 7861, 不对外暴露)
1294
  node /opt/hermes-web-ui/dist/server/index.js &
1295
  BFF_PID=$!
1296
 
1297
  # 等待 BFF 就绪
1298
+ echo " ⏳ 等待 BFF 就绪 (:7861)..."
1299
  BFF_READY=false
1300
  for i in $(seq 1 20); do
1301
+ if curl -sf http://localhost:7861/health > /dev/null 2>&1; then
1302
  BFF_READY=true
1303
  break
1304
  fi
 
1306
  done
1307
 
1308
  if [ "$BFF_READY" = true ]; then
1309
+ echo " ✅ BFF 已就绪 → http://127.0.0.1:7861"
1310
+ else
1311
+ echo " ⚠️ BFF 未在 20 秒内就绪,请查看日志"
1312
+ fi
1313
+
1314
+ # 启动 Image Proxy (对外端口 7860, HF Spaces 入口)
1315
+ echo "🖼️ 启动 Image Proxy..."
1316
+ BFF_PORT=7861 LISTEN_PORT=7860 IMAGE_DIR=/data/.hermes/image_cache \
1317
+ node /app/image-proxy.js &
1318
+ PROXY_PID=$!
1319
+
1320
+ # 等待 Image Proxy 就绪
1321
+ PROXY_READY=false
1322
+ for i in $(seq 1 10); do
1323
+ if curl -sf http://localhost:7860/health > /dev/null 2>&1; then
1324
+ PROXY_READY=true
1325
+ break
1326
+ fi
1327
+ sleep 1
1328
+ done
1329
+
1330
+ if [ "$PROXY_READY" = true ]; then
1331
  echo " ✅ Web UI 已就绪 → http://localhost:7860"
1332
+ echo " 📷 图片浏览 → http://localhost:7860/images/"
1333
  else
1334
+ echo " ⚠️ Image Proxy 未就绪,Web UI 可能不可用"
1335
  fi
1336
 
1337
  # 再次验证模型配置(BFF 启动可能修改 config.yaml)
 
1358
  fi
1359
  fi
1360
 
1361
+ # 等待 Image Proxy 主进程(前台阻塞,容器生命周期由 Proxy 控制)
1362
+ # Proxy 退出通常意味着 BFF 也挂了
1363
+ wait $PROXY_PID
image-gen-siliconflow.ts ADDED
@@ -0,0 +1,305 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bun
2
+ /**
3
+ * Enhanced SiliconFlow Image Generator
4
+ * Supports baoyu-imagine CLI interface with style/quality/aspect parameters
5
+ * Compatible with: black-forest-labs/FLUX.1-dev
6
+ *
7
+ * Supported args:
8
+ * --prompt <text> Prompt text
9
+ * --promptfiles <files> Read prompt from files (space-separated)
10
+ * --image <path> Output image path (required)
11
+ * --ar <ratio> Aspect ratio: 1:1, 16:9, 9:16, 4:3, 3:4, 2.35:1
12
+ * --size <WxH> Explicit size, e.g. 1024x1024 (overrides --ar)
13
+ * --quality <preset> normal (default) | 2k
14
+ * --n <count> Number of images (default: 1)
15
+ * --seed <number> Random seed
16
+ * --model <id> Model ID (default: black-forest-labs/FLUX.1-dev)
17
+ */
18
+
19
+ import { mkdir } from "node:fs/promises";
20
+ import { readFile } from "node:fs/promises";
21
+ import { dirname } from "node:path";
22
+
23
+ interface CliArgs {
24
+ prompt: string;
25
+ promptFiles: string[];
26
+ imagePath: string;
27
+ aspectRatio: string | null;
28
+ size: string | null;
29
+ quality: "normal" | "2k";
30
+ n: number;
31
+ seed: number | null;
32
+ model: string;
33
+ }
34
+
35
+ // ==================== Aspect Ratio Mapping ====================
36
+ // Maps common ratios to exact pixel dimensions (max 2,359,296 pixels per SiliconFlow limit)
37
+ const AR_MAP: Record<string, string> = {
38
+ "1:1": "1024x1024",
39
+ "16:9": "1024x576",
40
+ "9:16": "576x1024",
41
+ "4:3": "1024x768",
42
+ "3:4": "768x1024",
43
+ "2.35:1": "1024x435",
44
+ "21:9": "1024x439",
45
+ "3:2": "1024x683",
46
+ "2:3": "683x1024",
47
+ };
48
+
49
+ // ==================== Argument Parser ====================
50
+ function parseArgs(argv: string[]): CliArgs {
51
+ const args: CliArgs = {
52
+ prompt: "",
53
+ promptFiles: [],
54
+ imagePath: "",
55
+ aspectRatio: null,
56
+ size: null,
57
+ quality: "normal",
58
+ n: 1,
59
+ seed: null,
60
+ model: "Kwai-Kolors/Kolors", // Default: Kolors (available). Fallback to FLUX.1-dev if authorized.
61
+ };
62
+
63
+ for (let i = 0; i < argv.length; i++) {
64
+ const flag = argv[i];
65
+ const val = argv[++i] || "";
66
+
67
+ if (flag === "--prompt" || flag === "-p") {
68
+ args.prompt = val;
69
+ } else if (flag === "--promptfiles") {
70
+ while (i + 1 < argv.length && !argv[i + 1].startsWith("-")) {
71
+ args.promptFiles.push(argv[++i]);
72
+ }
73
+ } else if (flag === "--image") {
74
+ args.imagePath = val;
75
+ } else if (flag === "--ar") {
76
+ args.aspectRatio = val;
77
+ } else if (flag === "--size") {
78
+ args.size = val;
79
+ } else if (flag === "--quality") {
80
+ if (val === "2k" || val === "normal") args.quality = val as "normal" | "2k";
81
+ } else if (flag === "--n") {
82
+ const n = parseInt(val, 10);
83
+ if (!isNaN(n) && n > 0) args.n = Math.min(n, 4);
84
+ } else if (flag === "--seed") {
85
+ const s = parseInt(val, 10);
86
+ if (!isNaN(s)) args.seed = s;
87
+ } else if (flag === "--model" || flag === "-m") {
88
+ args.model = val;
89
+ }
90
+ }
91
+
92
+ return args;
93
+ }
94
+
95
+ // ==================== Prompt Builder ====================
96
+ async function buildPrompt(args: CliArgs): Promise<string> {
97
+ const parts: string[] = [];
98
+
99
+ // 1. From prompt files (highest priority)
100
+ for (const file of args.promptFiles) {
101
+ try {
102
+ const content = await readFile(file, "utf-8");
103
+ parts.push(content.trim());
104
+ } catch (e) {
105
+ console.error(`⚠️ Failed to read prompt file: ${file}`);
106
+ }
107
+ }
108
+
109
+ // 2. From inline prompt
110
+ if (args.prompt) {
111
+ parts.push(args.prompt);
112
+ }
113
+
114
+ let prompt = parts.join("\n\n").trim();
115
+
116
+ // 3. Quality enhancement suffixes
117
+ const suffixes: string[] = [];
118
+ if (args.quality === "2k") {
119
+ suffixes.push("high quality, highly detailed, sharp focus, professional");
120
+ }
121
+ suffixes.push("best quality, masterpiece");
122
+
123
+ if (suffixes.length > 0) {
124
+ prompt = prompt ? `${prompt}, ${suffixes.join(", ")}` : suffixes.join(", ");
125
+ }
126
+
127
+ return prompt;
128
+ }
129
+
130
+ // ==================== Image Size Resolver ====================
131
+ function resolveImageSize(args: CliArgs): string {
132
+ // Explicit size wins
133
+ if (args.size) {
134
+ const [w, h] = args.size.split("x").map(Number);
135
+ if (!isNaN(w) && !isNaN(h) && w * h <= 2359296) {
136
+ return args.size;
137
+ }
138
+ console.warn(`⚠️ Invalid size ${args.size}, falling back to aspect ratio`);
139
+ }
140
+
141
+ // Aspect ratio mapping
142
+ if (args.aspectRatio && AR_MAP[args.aspectRatio]) {
143
+ return AR_MAP[args.aspectRatio];
144
+ }
145
+
146
+ // Default
147
+ return "1024x1024";
148
+ }
149
+
150
+ // ==================== Inference Steps Resolver ====================
151
+ function resolveSteps(quality: string): number {
152
+ return quality === "2k" ? 28 : 20;
153
+ }
154
+
155
+ // ==================== Main Generation ====================
156
+ async function generateImage(args: CliArgs): Promise<void> {
157
+ const apiKey = process.env.SILICONFLOW_API_KEY;
158
+ if (!apiKey) {
159
+ console.error("❌ Error: SILICONFLOW_API_KEY not set");
160
+ console.error(" Please set SILICONFLOW_API_KEY environment variable");
161
+ process.exit(1);
162
+ }
163
+
164
+ // Redirect /tmp/ paths to image_cache for web accessibility
165
+ if (args.imagePath.startsWith("/tmp/")) {
166
+ const filename = args.imagePath.slice("/tmp/".length);
167
+ args.imagePath = `/data/.hermes/image_cache/${filename}`;
168
+ console.log(`📁 Redirected output to: ${args.imagePath}`);
169
+ }
170
+
171
+ const prompt = await buildPrompt(args);
172
+ const imageSize = resolveImageSize(args);
173
+ const numInferenceSteps = resolveSteps(args.quality);
174
+
175
+ console.log(`🎨 Generating image with ${args.model}`);
176
+ console.log(` Prompt: ${prompt.slice(0, 100)}${prompt.length > 100 ? "..." : ""}`);
177
+ console.log(` Size: ${imageSize} | Quality: ${args.quality} | Steps: ${numInferenceSteps}`);
178
+ if (args.seed) console.log(` Seed: ${args.seed}`);
179
+
180
+ const requestBody: any = {
181
+ model: args.model,
182
+ prompt: prompt,
183
+ image_size: imageSize,
184
+ num_inference_steps: numInferenceSteps,
185
+ };
186
+
187
+ if (args.seed !== null) {
188
+ requestBody.seed = args.seed;
189
+ }
190
+
191
+ // Call SiliconFlow API
192
+ const response = await fetch("https://api.siliconflow.cn/v1/images/generations", {
193
+ method: "POST",
194
+ headers: {
195
+ "Authorization": `Bearer ${apiKey}`,
196
+ "Content-Type": "application/json",
197
+ },
198
+ body: JSON.stringify(requestBody),
199
+ });
200
+
201
+ if (!response.ok) {
202
+ const errorText = await response.text();
203
+ console.error(`❌ API error (${response.status}): ${errorText}`);
204
+
205
+ if (response.status === 403) {
206
+ console.error("");
207
+ console.error("🔍 诊断: SiliconFlow API 返回 403 Forbidden");
208
+ console.error(" 网络连接正常,但所选模型需要额外授权");
209
+ console.error("");
210
+
211
+ // 自动 fallback 到 Kolors(已验证可用)
212
+ if (args.model !== "Kwai-Kolors/Kolors") {
213
+ console.error(`🔄 自动切换至备用模型: Kwai-Kolors/Kolors`);
214
+ args.model = "Kwai-Kolors/Kolors";
215
+ return generateImage(args); // 递归重试
216
+ }
217
+
218
+ console.error("解决步骤:");
219
+ console.error(" 1. 访问 https://cloud.siliconflow.cn 检查账户状态");
220
+ console.error(" 2. 确认 API Key 有效且余额充足");
221
+ console.error(" 3. 确认已开通所选模型的使用权限");
222
+ }
223
+
224
+ process.exit(1);
225
+ }
226
+
227
+ const result = await response.json();
228
+
229
+ if (!result.images || result.images.length === 0) {
230
+ console.error("❌ Error: No images in response");
231
+ console.error(JSON.stringify(result, null, 2));
232
+ process.exit(1);
233
+ }
234
+
235
+ // Ensure output directory exists
236
+ const outDir = dirname(args.imagePath);
237
+ await mkdir(outDir, { recursive: true });
238
+
239
+ // Download and save images
240
+ // Note: SiliconFlow currently returns 1 image per request regardless of --n
241
+ for (let idx = 0; idx < result.images.length; idx++) {
242
+ const imageUrl = result.images[idx].url;
243
+ console.log(`📥 Downloading from: ${imageUrl}`);
244
+
245
+ const imageResponse = await fetch(imageUrl);
246
+ if (!imageResponse.ok) {
247
+ console.error(`❌ Download failed: ${imageResponse.status}`);
248
+ continue;
249
+ }
250
+
251
+ // Validate response is actually an image
252
+ const contentType = imageResponse.headers.get("content-type") || "";
253
+ // Allow image/* and application/octet-stream (common for CDN-hosted images)
254
+ if (!contentType.startsWith("image/") && !contentType.includes("octet-stream")) {
255
+ const text = await imageResponse.text();
256
+ console.error(`❌ Unexpected response type: ${contentType}`);
257
+ console.error(` Body: ${text.slice(0, 200)}`);
258
+ continue;
259
+ }
260
+
261
+ const imageBuffer = await imageResponse.arrayBuffer();
262
+
263
+ // Handle multiple images naming
264
+ let outPath = args.imagePath;
265
+ if (result.images.length > 1) {
266
+ const dotIdx = outPath.lastIndexOf(".");
267
+ const ext = dotIdx > 0 ? outPath.slice(dotIdx) : ".png";
268
+ const base = dotIdx > 0 ? outPath.slice(0, dotIdx) : outPath;
269
+ outPath = `${base}-${String(idx + 1).padStart(2, "0")}${ext}`;
270
+ }
271
+
272
+ await Bun.write(outPath, new Uint8Array(imageBuffer));
273
+ console.log(`✅ Saved: ${outPath} (${imageBuffer.byteLength} bytes)`);
274
+ }
275
+ }
276
+
277
+ // ==================== CLI Entry ====================
278
+ const args = parseArgs(process.argv.slice(2));
279
+
280
+ if (!args.imagePath) {
281
+ console.error("Usage: bun main.ts --prompt <text> --image <path> [options]");
282
+ console.error("");
283
+ console.error("Options:");
284
+ console.error(" --prompt <text> Prompt text");
285
+ console.error(" --promptfiles <f...> Read prompt from files");
286
+ console.error(" --image <path> Output image path (required)");
287
+ console.error(" --ar <ratio> Aspect ratio: 1:1, 16:9, 9:16, 4:3, 3:4, 2.35:1");
288
+ console.error(" --size <WxH> Explicit size, e.g. 1024x576");
289
+ console.error(" --quality <preset> normal (default) | 2k");
290
+ console.error(" --n <count> Number of images (1-4)");
291
+ console.error(" --seed <number> Random seed");
292
+ console.error(" --model <id> Model ID (default: black-forest-labs/FLUX.1-dev)");
293
+ console.error("");
294
+ console.error("Example:");
295
+ console.error(' bun main.ts --prompt "a cute cat" --image ./cat.png --ar 16:9 --quality 2k');
296
+ process.exit(1);
297
+ }
298
+
299
+ // Validate prompt source
300
+ if (!args.prompt && args.promptFiles.length === 0) {
301
+ console.error("❌ Error: --prompt or --promptfiles required");
302
+ process.exit(1);
303
+ }
304
+
305
+ await generateImage(args);
image-proxy.js ADDED
@@ -0,0 +1,293 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ /**
2
+ * Image Proxy + BFF Reverse Proxy
3
+ *
4
+ * 在 BFF (hermes-web-ui) 前端增加一层轻量代理:
5
+ * - /images/ → 列出所有已生成图片 (HTML 页面)
6
+ * - /images/<file> → 直接下载/预览图片
7
+ * - 其他所有请求 → 透传给 BFF (含 WebSocket)
8
+ *
9
+ * 端口: 7860 (HF Spaces 对外端口)
10
+ * BFF: 7861 (内部端口, 仅本代理访问)
11
+ * 图片目录: /data/.hermes/image_cache (主目录)
12
+ * /data/cover-image (baoyu-cover-image 输出目录)
13
+ */
14
+
15
+ const http = require('http');
16
+ const fs = require('fs');
17
+ const path = require('path');
18
+ const net = require('net');
19
+
20
+ const BFF_HOST = '127.0.0.1';
21
+ const BFF_PORT = parseInt(process.env.BFF_PORT || '7861', 10);
22
+ const LISTEN_PORT = parseInt(process.env.LISTEN_PORT || '7860', 10);
23
+ const IMAGE_DIR = process.env.IMAGE_DIR || '/data/.hermes/image_cache';
24
+
25
+ // 额外的图片搜索路径(baoyu-cover-image 等技能的输出目录)
26
+ const EXTRA_IMAGE_DIRS = [
27
+ '/data/cover-image',
28
+ '/data/.hermes/image_cache',
29
+ ];
30
+
31
+ const MIME_TYPES = {
32
+ '.png': 'image/png',
33
+ '.jpg': 'image/jpeg',
34
+ '.jpeg': 'image/jpeg',
35
+ '.gif': 'image/gif',
36
+ '.webp': 'image/webp',
37
+ '.svg': 'image/svg+xml',
38
+ '.txt': 'text/plain',
39
+ '.json': 'application/json',
40
+ '.md': 'text/markdown',
41
+ };
42
+
43
+ // ==================== 图片文件服务 ====================
44
+
45
+ function serveImageList(res) {
46
+ const allImageFiles = [];
47
+ let dirsScanned = 0;
48
+ const totalDirs = EXTRA_IMAGE_DIRS.length;
49
+
50
+ function checkComplete() {
51
+ dirsScanned++;
52
+ if (dirsScanned < totalDirs) return;
53
+
54
+ const uniqueFiles = Array.from(new Map(allImageFiles.map(f => [f.path, f])).values());
55
+ uniqueFiles.sort((a, b) => b.mtime - a.mtime);
56
+
57
+ const html = buildImageListHtml(uniqueFiles);
58
+ res.writeHead(200, { 'Content-Type': 'text/html; charset=utf-8' });
59
+ res.end(html);
60
+ }
61
+
62
+ EXTRA_IMAGE_DIRS.forEach(dir => {
63
+ function scanDir(currentDir, relativePath, callback) {
64
+ fs.readdir(currentDir, { withFileTypes: true }, (err, entries) => {
65
+ if (err) {
66
+ callback();
67
+ return;
68
+ }
69
+
70
+ let pending = entries.length;
71
+ if (pending === 0) {
72
+ callback();
73
+ return;
74
+ }
75
+
76
+ entries.forEach(entry => {
77
+ const fullPath = path.join(currentDir, entry.name);
78
+ const relPath = path.join(relativePath, entry.name);
79
+
80
+ if (entry.isDirectory()) {
81
+ scanDir(fullPath, relPath, () => {
82
+ pending--;
83
+ if (pending === 0) callback();
84
+ });
85
+ } else if (/\.(png|jpe?g|gif|webp|svg|bmp)$/i.test(entry.name)) {
86
+ try {
87
+ const stat = fs.statSync(fullPath);
88
+ allImageFiles.push({
89
+ name: entry.name,
90
+ path: fullPath,
91
+ relPath: relPath,
92
+ dir: dir,
93
+ size: stat.size,
94
+ mtime: stat.mtime
95
+ });
96
+ } catch (e) {}
97
+ pending--;
98
+ if (pending === 0) callback();
99
+ } else {
100
+ pending--;
101
+ if (pending === 0) callback();
102
+ }
103
+ });
104
+ });
105
+ }
106
+
107
+ scanDir(dir, '', () => {
108
+ checkComplete();
109
+ });
110
+ });
111
+ }
112
+
113
+ function buildImageListHtml(imageFiles) {
114
+ const html = `<!DOCTYPE html>
115
+ <html lang="zh-CN">
116
+ <head>
117
+ <meta charset="utf-8">
118
+ <meta name="viewport" content="width=device-width, initial-scale=1">
119
+ <title>🖼️ Image Cache - Hermes Agent</title>
120
+ <style>
121
+ * { box-sizing: border-box; margin: 0; padding: 0; }
122
+ body { font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', sans-serif;
123
+ background: #0f0f23; color: #e0e0e0; padding: 2em; }
124
+ h1 { color: #7eb8da; margin-bottom: 1em; font-size: 1.5em; }
125
+ .card { background: #1a1a3e; border-radius: 12px; padding: 1.5em;
126
+ margin-bottom: 1.5em; box-shadow: 0 4px 12px rgba(0,0,0,.3); }
127
+ .card h3 { color: #9dd6e8; margin-bottom: 0.8em; font-size: 1.1em; }
128
+ .card img { max-width: 100%; border-radius: 8px; cursor: pointer;
129
+ transition: transform .2s; }
130
+ .card img:hover { transform: scale(1.02); }
131
+ .actions { margin-top: 0.8em; display: flex; gap: 1em; flex-wrap: wrap; }
132
+ .actions a { color: #7eb8da; text-decoration: none; padding: 0.4em 1em;
133
+ border: 1px solid #7eb8da; border-radius: 6px; font-size: 0.9em;
134
+ transition: background .2s; }
135
+ .actions a:hover { background: #7eb8da22; }
136
+ .meta { color: #888; font-size: 0.85em; margin-top: 0.5em; }
137
+ .path { color: #666; font-size: 0.8em; margin-top: 0.3em; }
138
+ .empty { text-align: center; padding: 3em; color: #888; }
139
+ .empty p { margin-top: 1em; font-size: 0.95em; }
140
+ </style>
141
+ </head>
142
+ <body>
143
+ <h1>🖼️ Image Cache</h1>
144
+ ${
145
+ imageFiles.length === 0
146
+ ? `<div class="empty"><p style="font-size:2em">📭</p><p>暂无图片。让 agent 生成图片后将自动出现在此。</p>
147
+ <p>提示: 让 agent 使用 baoyu-imagine 技能,并将图片保存到 /data/.hermes/image_cache/</p></div>`
148
+ : imageFiles
149
+ .map((f) => {
150
+ const sizeMB = (f.size / 1024 / 1024).toFixed(2);
151
+ const mtime = f.mtime.toISOString().replace('T', ' ').slice(0, 19);
152
+ return `<div class="card">
153
+ <h3>${f.name}</h3>
154
+ <div class="path">${f.relPath}</div>
155
+ <img src="/images/${encodeURIComponent(f.relPath)}" alt="${f.name}" loading="lazy" />
156
+ <div class="meta">${sizeMB} MB · ${mtime}</div>
157
+ <div class="actions">
158
+ <a href="/images/${encodeURIComponent(f.relPath)}" download="${f.name}">⬇️ 下载</a>
159
+ <a href="/images/${encodeURIComponent(f.relPath)}" target="_blank">🔍 原始大小</a>
160
+ </div>
161
+ </div>`;
162
+ })
163
+ .join('\n')
164
+ }
165
+ </body></html>`;
166
+ return html;
167
+ }
168
+
169
+ function serveImage(urlPath, res) {
170
+ const relativePath = decodeURIComponent(urlPath.slice('/images/'.length));
171
+
172
+ // Try each image directory in order
173
+ function tryDir(index) {
174
+ if (index >= EXTRA_IMAGE_DIRS.length) {
175
+ res.writeHead(404, { 'Content-Type': 'text/plain' });
176
+ res.end('Not found');
177
+ return;
178
+ }
179
+
180
+ const dir = EXTRA_IMAGE_DIRS[index];
181
+ const filePath = path.join(dir, relativePath);
182
+ const resolved = path.resolve(filePath);
183
+
184
+ // Security: prevent directory traversal
185
+ const imageRoot = path.resolve(dir);
186
+ if (!resolved.startsWith(imageRoot + path.sep) && resolved !== imageRoot) {
187
+ tryDir(index + 1);
188
+ return;
189
+ }
190
+
191
+ fs.stat(resolved, (err, stat) => {
192
+ if (err || !stat.isFile()) {
193
+ tryDir(index + 1);
194
+ return;
195
+ }
196
+
197
+ const ext = path.extname(resolved).toLowerCase();
198
+ const contentType = MIME_TYPES[ext] || 'application/octet-stream';
199
+
200
+ res.writeHead(200, {
201
+ 'Content-Type': contentType,
202
+ 'Content-Length': stat.size,
203
+ 'Cache-Control': 'public, max-age=3600',
204
+ 'Content-Disposition': `inline; filename="${path.basename(resolved)}"`,
205
+ });
206
+ fs.createReadStream(resolved).pipe(res);
207
+ });
208
+ }
209
+
210
+ tryDir(0);
211
+ }
212
+
213
+ // ==================== HTTP 反向代理 ====================
214
+
215
+ function proxyHttpRequest(clientReq, clientRes) {
216
+ const options = {
217
+ hostname: BFF_HOST,
218
+ port: BFF_PORT,
219
+ path: clientReq.url,
220
+ method: clientReq.method,
221
+ headers: { ...clientReq.headers, host: `${BFF_HOST}:${BFF_PORT}` },
222
+ };
223
+
224
+ const bffReq = http.request(options, (bffRes) => {
225
+ clientRes.writeHead(bffRes.statusCode, bffRes.headers);
226
+ bffRes.pipe(clientRes, { end: true });
227
+ });
228
+
229
+ bffReq.on('error', () => {
230
+ if (!clientRes.headersSent) {
231
+ clientRes.writeHead(502, { 'Content-Type': 'text/plain' });
232
+ clientRes.end('Bad Gateway: BFF server unavailable');
233
+ }
234
+ });
235
+
236
+ clientReq.pipe(bffReq, { end: true });
237
+ }
238
+
239
+ // ==================== WebSocket 反向代理 ====================
240
+
241
+ function proxyWebSocket(clientReq, clientSocket, clientHead) {
242
+ const bffSocket = net.connect(BFF_PORT, BFF_HOST, () => {
243
+ // 重新构造原始 HTTP Upgrade 请求发给 BFF
244
+ let rawRequest = `${clientReq.method} ${clientReq.url} HTTP/${clientReq.httpVersion}\r\n`;
245
+ for (let i = 0; i < clientReq.rawHeaders.length; i += 2) {
246
+ rawRequest += `${clientReq.rawHeaders[i]}: ${clientReq.rawHeaders[i + 1]}\r\n`;
247
+ }
248
+ rawRequest += '\r\n';
249
+
250
+ bffSocket.write(rawRequest);
251
+ if (clientHead && clientHead.length) {
252
+ bffSocket.write(clientHead);
253
+ }
254
+
255
+ // 双向管道: BFF ↔ Client
256
+ bffSocket.pipe(clientSocket);
257
+ clientSocket.pipe(bffSocket);
258
+ });
259
+
260
+ const cleanup = () => {
261
+ try { bffSocket.destroy(); } catch (_) {}
262
+ try { clientSocket.destroy(); } catch (_) {}
263
+ };
264
+
265
+ bffSocket.on('error', cleanup);
266
+ clientSocket.on('error', cleanup);
267
+ clientSocket.on('close', () => { try { bffSocket.end(); } catch (_) {} });
268
+ bffSocket.on('close', () => { try { clientSocket.end(); } catch (_) {} });
269
+ }
270
+
271
+ // ==================== 主服务器 ====================
272
+
273
+ const server = http.createServer((clientReq, clientRes) => {
274
+ // 图片文件服务
275
+ if (clientReq.url === '/images' || clientReq.url === '/images/') {
276
+ return serveImageList(clientRes);
277
+ }
278
+ if (clientReq.url.startsWith('/images/')) {
279
+ return serveImage(clientReq.url, clientRes);
280
+ }
281
+
282
+ // 其他请求透传给 BFF
283
+ proxyHttpRequest(clientReq, clientRes);
284
+ });
285
+
286
+ // WebSocket 透传
287
+ server.on('upgrade', proxyWebSocket);
288
+
289
+ server.listen(LISTEN_PORT, () => {
290
+ console.log(`🖼️ Image proxy listening on :${LISTEN_PORT}`);
291
+ console.log(`📷 Images: http://localhost:${LISTEN_PORT}/images/`);
292
+ console.log(`tunnel: http://${BFF_HOST}:${BFF_PORT}`);
293
+ });