Skip to content

Self-evolving Context Database for AI Agents. Unify Agent Memory, Knowledge RAG and Skills.

feat(bot):Single Channel (BotChannel) Integration, Werewolf demo (#1196)

yeshion23333020cc17b3c13
diff --git a/benchmark/locomo/README.md b/benchmark/locomo/README.md
new file mode 100644
index 000000000..cbb1bf460
--- /dev/null
+++ b/benchmark/locomo/README.md
@@ -0,0 +1,248 @@
+# LoCoMo 评测脚本使用指南
+
+本目录包含 LoCoMo(Long-Term Conversation Memory)评测脚本,用于评估对话记忆系统的性能。
+
+## 目录结构
+
+```
+benchmark/locomo/
+├── vikingbot/ # VikingBot 评测脚本
+│ ├── run_eval.py # 运行 QA 评估
+│ ├── judge.py # LLM 裁判打分
+│ ├── import_to_ov.py # 导入数据到 OpenViking
+│ ├── stat_judge_result.py # 统计评分结果
+│ ├── run_full_eval.sh # 一键运行完整评测流程
+│ ├── test_data/ # 测试数据目录
+│ └── result/ # 评测结果目录
+└── openclaw/ # OpenClaw 评测脚本
+ └── eval.py # OpenClaw 评估脚本
+```
+
+---
+
+## VikingBot 评测流程
+
+### 完整一键评测
+
+使用 `run_full_eval.sh` 可以一键运行完整评测流程:
+
+```bash
+cd benchmark/locomo/vikingbot
+bash run_full_eval.sh
+```
+
+该脚本会依次执行以下四个步骤:
+
+### 分步使用说明
+
+#### 步骤 1: 导入对话数据
+
+使用 `import_to_ov.py` 将 LoCoMo 数据集导入到 OpenViking:
+
+```bash
+python import_to_ov.py --input <数据文件路径> [选项]
+```
+
+**参数说明:**
+- `--input`: 输入文件路径(JSON 或 TXT 格式),默认 `./test_data/locomo10.json`
+- `--sample`: 指定样本索引(0-based),默认处理所有样本
+- `--sessions`: 指定会话范围,例如 `1-4` 或 `3`,默认所有会话
+- `--parallel`: 并发导入数,默认 5
+- `--force-ingest`: 强制重新导入,即使已导入过
+- `--clear-ingest-record`: 清除所有导入记录
+- `--openviking-url`: OpenViking 服务地址,默认 `http://localhost:1933`
+
+**示例:**
+```bash
+# 导入第一个样本的 1-4 会话
+python import_to_ov.py --input ./test_data/locomo10.json --sample 0 --sessions 1-4
+
+# 强制重新导入所有数据
+python import_to_ov.py --input ./test_data/locomo10.json --force-ingest
+```
+
+#### 步骤 2: 运行 QA 评估
+
+使用 `run_eval.py` 运行问答评估:
+
+```bash
+python run_eval.py <输入数据> [选项]
+```
+
+**参数说明:**
+- `input`: 输入 JSON/CSV 文件路径,默认 `./test_data/locomo10.json`
+- `--output`: 输出 CSV 文件路径,默认 `./result/locomo_qa_result.csv`
+- `--sample`: 指定样本索引
+- `--count`: 运行的 QA 问题数量,默认全部
+- `--threads`: 并发线程数,默认 5
+
+**示例:**
+```bash
+# 使用默认参数运行
+python run_eval.py
+
+# 指定输入输出文件,使用 20 线程
+python run_eval.py ./test_data/locomo_qa_1528.csv --output ./result/my_result.csv --threads 20
+```
+
+#### 步骤 3: LLM 裁判打分
+
+使用 `judge.py` 对评估结果进行打分:
+
+```bash
+python judge.py [选项]
+```
+
+**参数说明:**
+- `--input`: QA 结果 CSV 文件路径,默认 `./result/locomo_qa_result.csv`
+- `--token`: API Token(也可通过 `ARK_API_KEY` 或 `OPENAI_API_KEY` 环境变量设置)
+- `--base-url`: API 基础 URL,默认 `https://ark.cn-beijing.volces.com/api/v3`
+- `--model`: 裁判模型名称,默认 `doubao-seed-2-0-pro-260215`
+- `--parallel`: 并发请求数,默认 5
+
+**示例:**
+```bash
+python judge.py --input ./result/locomo_qa_result.csv --token <your_token> --parallel 10
+```
+
+#### 步骤 4: 统计结果
+
+使用 `stat_judge_result.py` 统计评分结果:
+
+```bash
+python stat_judge_result.py --input <评分结果文件>
+```
+
+**参数说明:**
+- `--input`: 评分结果 CSV 文件路径
+
+**输出统计信息包括:**
+- 正确率(Accuracy)
+- 平均耗时
+- 平均迭代次数
+- Token 使用情况
+
+---
+
+## OpenClaw 评测流程
+
+使用 `openclaw/eval.py` 进行 OpenClaw 评测,该脚本有两种模式:
+
+### 模式 1: ingest - 导入对话数据到OpenClaw
+
+```bash
+python eval.py ingest <输入文件> [选项]
+```
+
+**参数说明:**
+- `--sample`: 指定样本索引
+- `--sessions`: 指定会话范围,如 `1-4`
+- `--viking`: 使用 OpenViking 而非 OpenClaw 导入
+- `--force-ingest`: 强制重新导入
+- `--agent-id`: Agent ID,默认 `locomo-eval`
+
+**示例:**
+```bash
+# 导入第一个样本的 1-4 会话到 OpenClaw
+python eval.py ingest locomo10.json --sample 0 --sessions 1-4
+
+# 导入到 OpenViking
+python eval.py ingest locomo10.json --sample 0 --viking
+```
+
+### 模式 2: qa - 运行 QA 评估
+- 该评测制定了指定了`X-OpenClaw-Session-Key`,确保每次openclaw使用相同的session_id。Token计算将统计`session.jsonl`文件中的所有assistant轮次的Token消耗。每道题目执行完后会清空session.jsonl文件。
+- 该评测仅支持单线程运行,不支持并发。
+- 需先执行一次,查看`.openclaw/agents/{your_agent_id}/sessions/`下的session文件ID,作为`--session-id`参数的值开始完整评测。
+```bash
+python eval.py qa <输入文件> [选项]
+```
+
+**参数说明:**
+- `--output`: 输出文件路径
+- `--sample`: 指定样本索引
+- `--count`: 运行的 QA 问题数量
+- `--user`: 用户 ID,默认 `eval-1`
+- `--token`: OpenClaw Gateway Token(或设置 `OPENCLAW_GATEWAY_TOKEN` 环境变量)
+
+**示例:**
+```bash
+python eval.py qa locomo10.json --sample 0 --output qa_results.txt
+```
+
+---
+
+## 测试数据格式
+
+### LoCoMo JSON 格式
+
+```json
+[
+ {
+ "sample_id": "sample_001",
+ "conversation": {
+ "speaker_a": "Alice",
+ "speaker_b": "Bob",
+ "session_1": [
+ {
+ "speaker": "Alice",
+ "text": "你好,我是 Alice",
+ "img_url": [],
+ "blip_caption": ""
+ }
+ ],
+ "session_1_date_time": "9:36 am on 2 April, 2023"
+ },
+ "qa": [
+ {
+ "question": "Alice 叫什么名字?",
+ "answer": "Alice",
+ "category": "1",
+ "evidence": []
+ }
+ ]
+ }
+]
+```
+
+### CSV 格式(QA 数据)
+
+必须包含字段:
+- `sample_id`: 样本 ID
+- `question`: 问题
+- `answer`: 标准答案
+
+---
+
+## 输出文件说明
+
+| 文件 | 说明 |
+|------|------|
+| `result/locomo_qa_result.csv` | QA 评估原始结果 |
+| `result/judge_result.csv` | 包含裁判打分的结果 |
+| `result/summary.txt` | 统计摘要 |
+| `result/import_success.csv` | 导入成功记录 |
+| `result/import_errors.log` | 导入错误日志 |
+
+---
+
+## 环境变量
+
+| 变量名 | 说明 |
+|--------|------|
+| `ARK_API_KEY` | 火山引擎 API Key(用于 judge.py) |
+| `OPENAI_API_KEY` | OpenAI API Key(备选) |
+| `OPENCLAW_GATEWAY_TOKEN` | OpenClaw Gateway Token |
+
+---
+
+## 常见问题
+
+### Q: 如何中断后继续评测?
+A: 所有脚本都支持断点续传,重新运行相同命令会自动跳过已处理的项目。
+
+### Q: 如何强制重新运行?
+A: 使用 `--force-ingest`(导入)或删除结果 CSV 文件。
+
+### Q: 评测速度慢怎么办?
+A: 增加 `--threads`(run_eval.py)或 `--parallel`(其他脚本)参数值。
diff --git a/bot/demo/werewolf/Cubic_11_1.010_R.ttf b/bot/demo/werewolf/Cubic_11_1.010_R.ttf
new file mode 100644
index 000000000..eba307995
Binary files /dev/null and b/bot/demo/werewolf/Cubic_11_1.010_R.ttf differ
diff --git a/bot/demo/werewolf/GeistPixel-Square.woff2 b/bot/demo/werewolf/GeistPixel-Square.woff2
new file mode 100644
index 000000000..eb0ef6235
Binary files /dev/null and b/bot/demo/werewolf/GeistPixel-Square.woff2 differ
diff --git a/bot/demo/werewolf/werewolfUI.html b/bot/demo/werewolf/werewolfUI.html
new file mode 100644
index 000000000..7dd3d0612
--- /dev/null
+++ b/bot/demo/werewolf/werewolfUI.html
@@ -0,0 +1,3384 @@
+<!doctype html>
+<html lang="zh">
+<head>
+ <meta charset="utf-8"/>
+ <meta name="viewport" content="width=device-width, initial-scale=1"/>
+ <title>狼人杀 Demo · 像素桌面 + 记忆目录</title>
+ <link rel="preconnect" href="https://fonts.googleapis.com">
+ <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
+ <link href="https://fonts.googleapis.com/css2?family=Press+Start+2P&display=swap" rel="stylesheet">
+ <style>
+ @font-face {
+ font-family: 'Geist Pixel';
+ src: url('/fonts/GeistPixel-Square.woff2') format('woff2');
+ font-weight: normal;
+ font-style: normal;
+ }
+ @font-face {
+ font-family: 'Cubic 11';
+ src: url('/fonts/Cubic_11_1.010_R.ttf') format('truetype');
+ font-weight: normal;
+ font-style: normal;
+ }
+ :root {
+ --bg0: #070913;
+ --bg1: #0b0f1c;
+ --panel: #12162a;
+ --panel2: #0e1223;
+ --stroke: #2b3350;
+ --stroke2: #3a4466;
+ --text: #e9edf7;
+ --muted: #9aa4b2;
+ --good: #6ee7b7;
+ --warn: #fbbf24;
+ --bad: #fb7185;
+ --accent: #7c3aed;
+ --accent2: #38bdf8;
+ --paper: #ffefc0;
+ --paperStroke: #3a2e1b;
+ }
+ * { box-sizing: border-box; }
+ html, body { height: 100%; }
+ body {
+ margin: 0;
+ background: radial-gradient(1200px 700px at 20% 10%, #141a33 0%, var(--bg0) 45%, #050612 100%);
+ color: var(--text);
+ font-family: "Geist Pixel", "Cubic 11", "Press Start 2P", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace;
+ }
+ header {
+ display: flex;
+ align-items: center;
+ justify-content: space-between;
+ gap: 12px;
+ padding: 14px 20px;
+ background: linear-gradient(180deg, rgba(18, 22, 42, 0.95) 0%, rgba(9, 11, 21, 0.92) 100%);
+ border-bottom: 4px solid rgba(43, 51, 80, 0.8);
+ position: sticky;
+ top: 0;
+ z-index: 10;
+ backdrop-filter: blur(8px);
+ }
+ h1 { margin: 0; font-size: 14px; letter-spacing: 1px; }
+ .headerRight { display: flex; align-items: center; gap: 10px; flex-wrap: wrap; justify-content: flex-end; }
+ .navBar { display: flex; gap: 8px; flex-wrap: wrap; }
+ .navBtn { border: 2px solid rgba(43, 51, 80, 0.75); background: rgba(9, 11, 21, 0.55); color: rgba(233, 237, 247, 0.9); padding: 6px 12px; border-radius: 12px; font-family: inherit; font-size: 11px; cursor: pointer; }
+ .navBtn.active { border-color: rgba(56, 189, 248, 0.75); }
+ .pill {
+ border: 2px solid var(--stroke);
+ background: rgba(15, 18, 35, 0.7);
+ padding: 6px 10px;
+ border-radius: 999px;
+ font-size: 11px;
+ color: var(--muted);
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
+ .dot { width: 10px; height: 10px; border-radius: 2px; background: var(--accent2); box-shadow: 0 0 0 2px rgba(56, 189, 248, 0.25); }
+ .dot.night { background: var(--accent); box-shadow: 0 0 0 2px rgba(124, 58, 237, 0.25); }
+ .page { display: none; }
+ .page.active { display: block; }
+ .wrap {
+ padding: 16px 18px 22px 18px;
+ display: grid;
+ grid-template-columns: minmax(560px, 1.8fr) minmax(360px, 1fr);
+ gap: 16px;
+ align-items: start;
+ }
+ .panel {
+ background: linear-gradient(180deg, rgba(18, 22, 42, 0.92) 0%, rgba(11, 14, 28, 0.92) 100%);
+ border: 2px solid var(--stroke);
+ border-radius: 16px;
+ box-shadow: 0 0 0 2px rgba(7, 9, 19, 0.9) inset, 0 18px 50px rgba(0,0,0,0.35);
+ overflow: hidden;
+ }
+ .panelHeader {
+ display: flex;
+ align-items: baseline;
+ justify-content: space-between;
+ gap: 10px;
+ padding: 12px 14px;
+ border-bottom: 2px solid rgba(43, 51, 80, 0.7);
+ background: rgba(14, 18, 35, 0.75);
+ }
+ .panelHeader h2 { margin: 0; font-size: 13px; color: var(--muted); letter-spacing: 0.5px; }
+ .panelHeader .hint { font-size: 11px; color: rgba(154, 164, 178, 0.75); display: flex; gap: 8px; align-items: center; justify-content: flex-end; flex-wrap: wrap; }
+ .btn {
+ border: 2px solid rgba(43, 51, 80, 0.75);
+ background: rgba(9, 11, 21, 0.55);
+ color: rgba(233, 237, 247, 0.9);
+ padding: 6px 12px;
+ border-radius: 12px;
+ font-family: inherit;
+ font-size: 11px;
+ cursor: pointer;
+ white-space: nowrap;
+ }
+ .btn.active { border-color: rgba(56, 189, 248, 0.75); }
+ .leftCol { display: grid; gap: 16px; }
+ .rightCol { display: flex; flex-direction: column; gap: 16px; min-height: 0; }
+ .arenaWrap { padding: 10px 14px 20px 14px; }
+ .arena {
+ position: relative;
+ height: 560px;
+ background:
+ radial-gradient(circle at center, rgba(26, 32, 51, 0.95) 0%, rgba(7, 9, 19, 0.92) 70%),
+ linear-gradient(180deg, rgba(56, 189, 248, 0.08) 0%, rgba(124, 58, 237, 0.06) 100%);
+ border: 2px solid rgba(58, 68, 102, 0.9);
+ border-radius: 18px;
+ overflow: visible;
+ }
+ .scanlines {
+ pointer-events: none;
+ position: absolute;
+ inset: 0;
+ background: repeating-linear-gradient(180deg, rgba(255,255,255,0.03) 0px, rgba(255,255,255,0.03) 1px, rgba(0,0,0,0) 3px, rgba(0,0,0,0) 6px);
+ mix-blend-mode: overlay;
+ opacity: 0.35;
+ }
+ .table {
+ position: absolute;
+ left: 50%;
+ top: 50%;
+ width: 260px;
+ height: 260px;
+ transform: translate(-50%, -50%);
+ border-radius: 50%;
+ background:
+ radial-gradient(circle at 30% 30%, rgba(124, 58, 237, 0.25) 0%, rgba(43, 51, 80, 0.8) 55%, rgba(18, 22, 42, 0.9) 100%),
+ linear-gradient(180deg, rgba(56, 189, 248, 0.08) 0%, rgba(0, 0, 0, 0) 60%);
+ box-shadow: 0 0 0 8px rgba(27, 33, 53, 0.95) inset, 0 0 0 2px rgba(7, 9, 19, 0.95), 0 24px 60px rgba(0,0,0,0.35);
+ }
+ .seat {
+ position: absolute;
+ width: 118px;
+ text-align: center;
+ font-size: 11px;
+ cursor: pointer;
+ user-select: none;
+ }
+ .seat.dead { opacity: 0.45; filter: grayscale(0.35); }
+ .seat .name { color: rgba(233, 237, 247, 0.9); text-shadow: 0 2px 0 rgba(0,0,0,0.35); }
+ .seat .sub { margin-top: 4px; color: rgba(154, 164, 178, 0.9); font-size: 10px; }
+ .avatar {
+ width: 72px;
+ height: 72px;
+ margin: 0 auto 6px;
+ border-radius: 12px;
+ border: 3px solid rgba(58, 68, 102, 0.95);
+ background: radial-gradient(circle at 30% 30%, rgba(56, 189, 248, 0.22) 0%, rgba(29, 36, 56, 0.9) 55%, rgba(17, 21, 35, 0.95) 100%);
+ display: grid;
+ place-items: center;
+ box-shadow: 0 0 0 2px rgba(7, 9, 19, 0.95) inset;
+ position: relative;
+ }
+ .avatar .badge {
+ position: absolute;
+ left: -6px;
+ top: -6px;
+ width: 24px;
+ height: 24px;
+ border-radius: 8px;
+ background: rgba(251, 191, 36, 0.25);
+ border: 2px solid rgba(251, 191, 36, 0.7);
+ display: grid;
+ place-items: center;
+ color: rgba(251, 191, 36, 0.95);
+ font-size: 10px;
+ }
+ .avatar .badgeCandidate {
+ position: absolute;
+ left: -6px;
+ bottom: -6px;
+ width: 24px;
+ height: 24px;
+ border-radius: 8px;
+ background: rgba(110, 231, 183, 0.2);
+ border: 2px solid rgba(110, 231, 183, 0.7);
+ display: grid;
+ place-items: center;
+ color: rgba(110, 231, 183, 0.95);
+ font-size: 9px;
+ }
+ .sigil {
+ width: 42px;
+ height: 42px;
+ border-radius: 10px;
+ border: 2px solid rgba(43, 51, 80, 0.9);
+ background: rgba(14, 18, 35, 0.7);
+ display: grid;
+ place-items: center;
+ }
+ .sigil svg { width: 28px; height: 28px; image-rendering: pixelated; }
+ .voteBadge {
+ position: absolute;
+ right: -6px;
+ top: -6px;
+ min-width: 24px;
+ height: 24px;
+ border-radius: 8px;
+ background: rgba(56, 189, 248, 0.25);
+ border: 2px solid rgba(56, 189, 248, 0.7);
+ display: grid;
+ place-items: center;
+ color: rgba(56, 189, 248, 0.95);
+ font-size: 9px;
+ padding: 0 4px;
+ }
+ .bubble {
+ position: absolute;
+ background: var(--paper);
+ color: #1c1c1c;
+ border: 2px solid var(--paperStroke);
+ padding: 8px 10px;
+ border-radius: 10px;
+ font-size: 11px;
+ width: 190px;
+ transform: translate(-50%, -100%);
+ line-height: 1.35;
+ box-shadow: 0 10px 30px rgba(0,0,0,0.35);
+ }
+ .bubble:after { content: ""; position: absolute; left: 26px; bottom: -8px; border-width: 8px 8px 0; border-style: solid; border-color: var(--paperStroke) transparent transparent; }
+ .bubble:before { content: ""; position: absolute; left: 28px; bottom: -6px; border-width: 6px 6px 0; border-style: solid; border-color: var(--paper) transparent transparent; }
+ .bubble.down { transform: translate(-50%, 22%); }
+ .bubble.down:after { bottom: auto; top: -8px; border-width: 0 8px 8px; border-color: transparent transparent var(--paperStroke); }
+ .bubble.down:before { bottom: auto; top: -6px; border-width: 0 6px 6px; border-color: transparent transparent var(--paper); }
+ .bubble.left { transform: translate(-110%, -50%); }
+ .bubble.left:after { left: auto; right: -8px; bottom: 12px; border-width: 8px 0 8px 8px; border-color: transparent transparent transparent var(--paperStroke); }
+ .bubble.left:before { left: auto; right: -6px; bottom: 14px; border-width: 6px 0 6px 6px; border-color: transparent transparent transparent var(--paper); }
+ .bubble.right { transform: translate(10%, -50%); }
+ .bubble.right:after { left: -8px; bottom: 12px; border-width: 8px 8px 8px 0; border-color: transparent var(--paperStroke) transparent transparent; }
+ .bubble.right:before { left: -6px; bottom: 14px; border-width: 6px 6px 6px 0; border-color: transparent var(--paper) transparent transparent; }
+ .bubble .cursor { display: inline-block; width: 6px; height: 10px; background: #1c1c1c; margin-left: 4px; animation: blink 1s steps(1) infinite; }
+ @keyframes blink { 50% { opacity: 0; } }
+ .seat.speaking .avatar { box-shadow: 0 0 0 2px rgba(251,191,36,0.8) inset, 0 0 18px rgba(251,191,36,0.45); }
+ .seat.speaking .sigil { border-color: rgba(251,191,36,0.7); }
+ .speaker-wave {
+ position: absolute;
+ top: -24px;
+ left: 50%;
+ transform: translateX(-50%);
+ display: flex;
+ align-items: center;
+ gap: 3px;
+ background: rgba(14, 18, 35, 0.85);
+ padding: 4px 8px;
+ border-radius: 8px;
+ border: 1px solid rgba(251, 191, 36, 0.6);
+ box-shadow: 0 2px 8px rgba(0,0,0,0.4);
+ }
+ .speaker-wave .bar {
+ width: 3px;
+ height: 8px;
+ background-color: #f59e0b;
+ border-radius: 2px;
+ animation: sound-wave 0.6s ease-in-out infinite alternate;
+ }
+ .speaker-wave .bar:nth-child(2) { animation-delay: 0.2s; }
+ .speaker-wave .bar:nth-child(3) { animation-delay: 0.4s; }
+
+ @keyframes sound-wave {
+ 0% { height: 4px; }
+ 100% { height: 14px; }
+ }
+ .seat .phaseIcon { position: absolute; right: 4px; bottom: -16px; font-size: 11px; color: rgba(251, 191, 36, 0.85); }
+ .phaseIndicator {
+ position: absolute;
+ left: 14px;
+ top: 14px;
+ padding: 6px 10px;
+ border-radius: 12px;
+ border: 2px solid rgba(43, 51, 80, 0.8);
+ background: rgba(9, 11, 21, 0.6);
+ font-size: 11px;
+ display: flex;
+ gap: 6px;
+ align-items: center;
+ color: rgba(233, 237, 247, 0.9);
+ }
+ .arena::before {
+ content: "";
+ position: absolute;
+ inset: -20px;
+ border-radius: 50%;
+ background: conic-gradient(from 0deg, rgba(56,189,248,0.06), rgba(124,58,237,0.08), rgba(56,189,248,0.06));
+ animation: spin 16s linear infinite;
+ opacity: 0.6;
+ }
+ @keyframes spin { to { transform: rotate(360deg); } }
+ .btn.hidden { display: none; }
+ .chatWrap { display: grid; grid-template-rows: auto 1fr auto; height: 100%; min-height: 520px; }
+ .chatHeader { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 12px 14px; border-bottom: 2px solid rgba(43, 51, 80, 0.7); background: rgba(14, 18, 35, 0.75); }
+ .chatHeader .phase { display: flex; gap: 10px; align-items: center; font-size: 15px; color: rgba(233, 237, 247, 0.9); }
+ .chatHeader .phaseIcon { font-size: 18px; }
+ .chatBody { padding: 12px; overflow: auto; display: grid; gap: 10px; }
+ .chatBubble { display: grid; grid-template-columns: 32px 1fr; gap: 10px; align-items: start; }
+ .chatBubble .avatarMini { width: 32px; height: 32px; border-radius: 8px; border: 2px solid rgba(58, 68, 102, 0.95); background: rgba(14, 18, 35, 0.8); display: grid; place-items: center; }
+ .chatBubble .text { font-size: 14px; line-height: 1.6; color: rgba(233, 237, 247, 0.9); background: rgba(9, 11, 21, 0.55); border: 2px solid rgba(43, 51, 80, 0.6); border-radius: 10px; padding: 10px 12px; }
+ .chatBubble.system .text { color: rgba(251, 191, 36, 0.95); border-color: rgba(251, 191, 36, 0.5); background: rgba(20, 15, 10, 0.4); }
+ .chatFooter { padding: 10px 12px; border-top: 2px solid rgba(43, 51, 80, 0.7); display: grid; gap: 6px; font-size: 13px; color: rgba(154, 164, 178, 0.9); }
+ .voteRow { display: flex; gap: 8px; flex-wrap: wrap; }
+ .voteRow .pill { font-size: 13px; }
+ .drawer {
+ position: fixed;
+ top: 0;
+ right: 0;
+ width: 420px;
+ height: 100%;
+ background: rgba(12, 16, 30, 0.96);
+ border-left: 2px solid rgba(43, 51, 80, 0.8);
+ transform: translateX(100%);
+ transition: transform 0.25s ease;
+ z-index: 40;
+ display: grid;
+ grid-template-rows: auto 1fr;
+ }
+ .drawer.show { transform: translateX(0); }
+ .drawerHeader { display: flex; align-items: center; justify-content: space-between; padding: 12px 14px; border-bottom: 2px solid rgba(43, 51, 80, 0.7); }
+ .drawerBody { padding: 12px; overflow: auto; font-family: "Geist Pixel", "Cubic 11", "Press Start 2P", ui-monospace, monospace; }
+ .drawerBody .raw { font-size: 14px; line-height: 1.6; white-space: pre-wrap; }
+ .memoryPage, .replayPage, .rankPage {
+ padding: 18px;
+ display: grid;
+ gap: 16px;
+ }
+ .grid2 { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 16px; }
+ .grid3 { display: grid; grid-template-columns: repeat(3, minmax(0, 1fr)); gap: 16px; }
+ .card {
+ border: 2px solid rgba(43, 51, 80, 0.75);
+ border-radius: 14px;
+ background: rgba(14, 18, 35, 0.55);
+ padding: 12px;
+ }
+ .card h3 { margin: 0 0 8px 0; font-size: 16px; color: rgba(233, 237, 247, 0.92); }
+ .card .muted { color: rgba(154, 164, 178, 0.8); font-size: 13px; }
+ .timeline { display: grid; gap: 10px; }
+ .event {
+ border-left: 3px solid rgba(56, 189, 248, 0.8);
+ padding: 8px 10px;
+ background: rgba(9, 11, 21, 0.55);
+ border-radius: 10px;
+ font-size: 14px;
+ }
+ .rankList { display: grid; gap: 8px; }
+ .rankItem { display: flex; justify-content: space-between; gap: 10px; font-size: 14px; padding: 10px 12px; border-radius: 10px; border: 2px solid rgba(43, 51, 80, 0.6); background: rgba(9, 11, 21, 0.55); }
+ .humanChatWrap { display: grid; grid-template-rows: auto 1fr auto; height: 100%; min-height: 300px; border: 2px solid rgba(167,139,250,0.5); border-radius: 14px; overflow: hidden; }
+ .humanChatHeader { display: flex; align-items: center; justify-content: space-between; gap: 10px; padding: 10px 12px; border-bottom: 2px solid rgba(167,139,250,0.5); background: rgba(26,20,46,0.8); }
+ .humanChatBody { padding: 12px; overflow: auto; display: grid; gap: 10px; min-height: 150px; background: rgba(10,8,20,0.4); }
+ .humanChatFooter { padding: 10px 12px; border-top: 2px solid rgba(167,139,250,0.5); background: rgba(26,20,46,0.8); display: grid; gap: 8px; }
+ .humanInput { width: 100%; padding: 10px 12px; border-radius: 10px; border: 2px solid rgba(167,139,250,0.5); background: rgba(10,8,20,0.6); color: rgba(233,237,247,0.95); font-family: inherit; font-size: 13px; resize: none; min-height: 60px; }
+ .humanInput:focus { outline: none; border-color: rgba(167,139,250,0.9); }
+ .humanModeIndicator { display: flex; align-items: center; gap: 8px; padding: 6px 12px; border-radius: 999px; background: rgba(167,139,250,0.15); border: 2px solid rgba(167,139,250,0.4); }
+ .humanModeIndicator .dot { width: 8px; height: 8px; border-radius: 2px; background: rgba(167,139,250,0.9); animation: pulse 1s ease-in-out infinite; }
+ @keyframes pulse { 0%, 100% { opacity: 1; } 50% { opacity: 0.4; } }
+ .bar { height: 6px; border-radius: 999px; background: rgba(56, 189, 248, 0.2); overflow: hidden; margin-top: 6px; }
+ .bar > span { display: block; height: 100%; background: rgba(56, 189, 248, 0.75); }
+ .searchRow { display: flex; gap: 8px; align-items: center; }
+ .searchInput { flex: 1; padding: 8px 10px; border-radius: 10px; border: 2px solid rgba(43, 51, 80, 0.6); background: rgba(9, 11, 21, 0.6); color: rgba(233, 237, 247, 0.95); font-family: inherit; font-size: 13px; }
+ .selectInput { padding: 8px 10px; border-radius: 10px; border: 2px solid rgba(43, 51, 80, 0.6); background: rgba(9, 11, 21, 0.6); color: rgba(233, 237, 247, 0.95); font-family: inherit; font-size: 13px; }
+ .panelHeader .hint .btn { margin: 0 2px; padding: 3px 8px; font-size: 10px; }
+ .panelHeader .hint .btn.active { border-color: rgba(56, 189, 248, 0.75); background: rgba(56, 189, 248, 0.15); }
+ .endOverlay {
+ position: fixed;
+ inset: 0;
+ background: rgba(5, 6, 16, 0.82);
+ display: none;
+ align-items: center;
+ justify-content: center;
+ z-index: 50;
+ backdrop-filter: blur(6px);
+ }
+ .endOverlay.show { display: flex; animation: fadeIn 0.4s ease-out; }
+ .endCard {
+ border: 2px solid rgba(124, 58, 237, 0.7);
+ border-radius: 18px;
+ padding: 20px 22px;
+ background: linear-gradient(180deg, rgba(12, 16, 30, 0.95) 0%, rgba(8, 11, 23, 0.95) 100%);
+ box-shadow: 0 0 30px rgba(124, 58, 237, 0.35);
+ text-align: center;
+ min-width: 320px;
+ }
+ .endTitle { font-size: 16px; color: rgba(251, 191, 36, 0.95); margin-bottom: 10px; }
+ .endWinner { font-size: 13px; color: rgba(233, 237, 247, 0.95); margin-bottom: 16px; }
+ .endStatus { font-size: 11px; color: rgba(154, 164, 178, 0.85); margin-top: 8px; }
+ .pulseRing {
+ width: 120px;
+ height: 120px;
+ border-radius: 50%;
+ border: 2px solid rgba(124, 58, 237, 0.65);
+ margin: 0 auto 12px;
+ position: relative;
+ box-shadow: 0 0 0 6px rgba(124, 58, 237, 0.08) inset;
+ }
+ .pulseRing::after {
+ content: "";
+ position: absolute;
+ inset: -10px;
+ border-radius: 50%;
+ border: 2px solid rgba(56, 189, 248, 0.5);
+ animation: ring 1.6s ease-out infinite;
+ }
+ @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }
+ @keyframes ring {
+ 0% { transform: scale(0.9); opacity: 0.8; }
+ 100% { transform: scale(1.15); opacity: 0; }
+ }
+ .rosterWrap { padding: 12px 14px 14px; }
+ .rosterGrid { display: grid; grid-template-columns: repeat(4, minmax(0, 1fr)); gap: 12px; }
+ .roleCard {
+ border-radius: 14px;
+ border: 2px solid rgba(58, 68, 102, 0.95);
+ background: linear-gradient(180deg, rgba(14, 18, 35, 0.8) 0%, rgba(10, 12, 24, 0.9) 100%);
+ box-shadow: 0 0 0 2px rgba(7, 9, 19, 0.95) inset;
+ overflow: hidden;
+ cursor: pointer;
+ }
+ .roleCard.dead { opacity: 0.55; filter: grayscale(0.4); }
+ .roleCardTop { display: flex; gap: 10px; padding: 10px 10px 8px; align-items: center; }
+ .roleCardTitle { display: grid; gap: 4px; min-width: 0; }
+ .roleName { font-size: 11px; color: rgba(233, 237, 247, 0.95); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+ .roleMeta { font-size: 10px; color: rgba(154, 164, 178, 0.9); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
+ .roleCardBottom {
+ border-top: 2px solid rgba(43, 51, 80, 0.7);
+ padding: 8px 10px 10px;
+ display: flex;
+ justify-content: space-between;
+ gap: 8px;
+ align-items: center;
+ color: rgba(154, 164, 178, 0.9);
+ font-size: 10px;
+ }
+ .tag { padding: 4px 8px; border-radius: 999px; border: 2px solid rgba(43, 51, 80, 0.85); background: rgba(15, 18, 35, 0.55); font-size: 10px; }
+ .tag.good { border-color: rgba(110, 231, 183, 0.55); color: rgba(110, 231, 183, 0.95); }
+ .tag.bad { border-color: rgba(251, 113, 133, 0.55); color: rgba(251, 113, 133, 0.95); }
+ .tag.special { border-color: rgba(251, 191, 36, 0.55); color: rgba(251, 191, 36, 0.95); }
+ .rightCol { display: flex; flex-direction: column; gap: 16px; min-height: 0; }
+ .memoryBody { display: flex; flex-direction: column; gap: 12px; padding: 12px 14px 14px; min-height: 0; }
+ .memoryGrid { display: grid; grid-template-columns: 1fr; gap: 12px; }
+ .treePanel { border: 2px solid rgba(43, 51, 80, 0.75); border-radius: 14px; background: rgba(14, 18, 35, 0.55); overflow: hidden; display: flex; flex-direction: column; flex: 1; min-height: 0; }
+ .treeHeader { padding: 10px 10px; border-bottom: 2px solid rgba(43, 51, 80, 0.6); display: flex; justify-content: space-between; gap: 10px; align-items: center; }
+ .treeHeader .title { font-size: 14px; color: rgba(233, 237, 247, 0.92); }
+ .treeHeader .sub { font-size: 12px; color: rgba(154, 164, 178, 0.85); }
+ .tree { padding: 8px 8px 10px; overflow: auto; flex: 1; min-height: 0; }
+ details { border-radius: 12px; }
+ summary {
+ list-style: none;
+ cursor: pointer;
+ padding: 8px 8px;
+ border-radius: 12px;
+ color: rgba(233, 237, 247, 0.92);
+ font-size: 13px;
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ }
+ summary::-webkit-details-marker { display: none; }
+ summary:hover { background: rgba(124, 58, 237, 0.10); }
+ .node { margin-left: 12px; display: grid; gap: 8px; padding-bottom: 8px; }
+ .fileBtn {
+ display: flex;
+ justify-content: space-between;
+ gap: 10px;
+ width: 100%;
+ padding: 8px 10px;
+ border-radius: 12px;
+ border: 2px solid rgba(43, 51, 80, 0.6);
+ background: rgba(9, 11, 21, 0.55);
+ color: rgba(233, 237, 247, 0.92);
+ font-family: inherit;
+ font-size: 13px;
+ cursor: pointer;
+ text-align: left;
+ }
+ .fileBtn:hover { border-color: rgba(56, 189, 248, 0.65); }
+ .fileBtn.active { border-color: rgba(124, 58, 237, 0.75); box-shadow: 0 0 0 2px rgba(124, 58, 237, 0.18) inset; }
+ .fileBtn .meta { color: rgba(154, 164, 178, 0.85); font-size: 11px; white-space: nowrap; }
+ .viewer {
+ border: 2px solid rgba(43, 51, 80, 0.75);
+ border-radius: 14px;
+ background: rgba(14, 18, 35, 0.55);
+ overflow: hidden;
+ display: grid;
+ grid-template-rows: auto 1fr;
+ min-height: 420px;
+ }
+ .viewerTop { padding: 10px 10px; border-bottom: 2px solid rgba(43, 51, 80, 0.6); display: flex; justify-content: space-between; gap: 10px; align-items: center; }
+ .viewerTop .title { font-size: 14px; color: rgba(233, 237, 247, 0.92); overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
+ .viewerTop .mode { display: flex; gap: 8px; }
+ .viewerBody { padding: 12px 12px 14px; overflow-y: auto; flex: 1; min-height: 0; }
+ .md { font-family: "Geist Pixel", "Cubic 11", "Press Start 2P", ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace; font-size: 14px; line-height: 1.6; }
+ .md h1, .md h2, .md h3 { font-weight: normal; }
+ .md h1 { font-size: 16px; margin: 0 0 12px 0; }
+ .md h2 { font-size: 14px; margin: 16px 0 10px 0; color: rgba(233, 237, 247, 0.95); }
+ .md h3 { font-size: 13px; margin: 14px 0 8px 0; color: rgba(233, 237, 247, 0.92); }
+ .md pre { background: rgba(9, 11, 21, 0.65); border: 2px solid rgba(43, 51, 80, 0.75); padding: 10px 10px; border-radius: 12px; overflow: auto; }
+ .md code { background: rgba(9, 11, 21, 0.55); border: 1px solid rgba(43, 51, 80, 0.7); padding: 2px 6px; border-radius: 8px; }
+ .md ul { padding-left: 18px; margin: 8px 0; }
+ .md li { margin: 6px 0; }
+ .raw { font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace; white-space: pre-wrap; word-break: break-word; font-size: 14px; line-height: 1.6; color: rgba(233, 237, 247, 0.92); }
+ @media (max-width: 1100px) {
+ .wrap { grid-template-columns: 1fr; }
+ .rosterGrid { grid-template-columns: repeat(3, minmax(0, 1fr)); }
+ }
+ @media (max-width: 720px) {
+ .rosterGrid { grid-template-columns: repeat(2, minmax(0, 1fr)); }
+ }
+ </style>
+</head>
+<body>
+ <header>
+ <h1>狼人杀 Demo · 像素桌面 + 记忆目录</h1>
+ <div class="headerRight">
+ <div class="navBar">
+ <button class="navBtn active" id="navGame">游戏</button>
+ <button class="navBtn" id="navMemory">记忆</button>
+ <button class="navBtn" id="navRank">排行榜</button>
+ </div>
+ <button class="btn" id="navForceRestart" style="margin-right: 12px; padding: 4px 12px; font-size: 13px; height: 26px;">强制重开</button>
+ <div class="pill"><span id="phaseDot" class="dot"></span><span id="phaseText">DAY</span></div>
+ <div class="pill"><span class="dot" style="background: rgba(110,231,183,0.95); box-shadow: 0 0 0 2px rgba(110,231,183,0.25)"></span><span id="aliveText">0/0 alive</span></div>
+ <div class="pill"><span class="dot" style="background: rgba(251,191,36,0.95); box-shadow: 0 0 0 2px rgba(251,191,36,0.25)"></span><span id="fsText">http: /data</span></div>
+ </div>
+ </header>
+ <section class="page active" id="page-game">
+ <div class="wrap" id="gameWrap" style="height: calc(100vh - 80px); grid-template-columns: minmax(560px, 1.8fr) minmax(360px, 1fr); gap: 16px;">
+ <div class="leftCol" style="height: 100%; display: flex; flex-direction: column;">
+ <section class="panel" style="flex: 1; display: flex; flex-direction: column;">
+ <div class="panelHeader">
+ <h2>游戏界面</h2>
+ </div>
+ <div class="arenaWrap" style="flex: 1; display: flex; align-items: center; justify-content: center; position: relative;">
+ <div class="arena" id="arena" style="width: 100%;"></div>
+ </div>
+ </section>
+ </div>
+ <div class="rightCol" style="height: 100%; display: flex; flex-direction: column; min-height: 0; gap: 16px;">
+ <section class="panel" style="flex: 1; display: flex; flex-direction: column; min-height: 0;">
+ <div class="chatWrap" style="flex: 1; display: flex; flex-direction: column; overflow: hidden; min-height: 0;">
+ <div class="chatHeader">
+ <div class="phase">
+ <span class="phaseIcon" id="chatPhaseIcon">☀️</span>
+ <span id="chatPhaseText">白天</span>
+ <span id="chatRoundText">第1轮</span>
+ </div>
+ <div class="pill"><span id="chatAliveText">0/0 alive</span></div>
+ </div>
+ <div class="chatBody" id="chatBody" style="flex: 1; overflow-y: auto;"></div>
+ <div class="chatFooter">
+ <div id="chatStatus">等待开始...</div>
+ <div class="voteRow" id="chatVotes"></div>
+ </div>
+ </div>
+ </section>
+ <section class="panel" id="humanPlayerPanel" style="display: none; min-height: 320px;">
+ <div class="panelHeader">
+ <h2>真实玩家</h2>
+ <div class="humanModeIndicator"><span class="dot"></span><span id="humanStatus">等待中...</span></div>
+ </div>
+ <div class="humanChatWrap" style="flex: 1;">
+ <div class="humanChatBody" id="humanChatBody"></div>
+ <div class="humanChatFooter">
+ <textarea class="humanInput" id="humanInput" placeholder="在此输入你的回复..."></textarea>
+ <button class="btn" id="humanSendBtn" style="width: 100%; background: rgba(167,139,250,0.2); border-color: rgba(167,139,250,0.6);">发送</button>
+ <div style="display: flex; gap: 8px; margin-top: 8px;">
+ <button class="btn" id="humanEditGameMd" style="flex: 1; font-size: 11px;">编辑GAME.md</button>
+ </div>
+ </div>
+ </div>
+ </section>
+ </div>
+ </div>
+ </section>
+ <section class="page memoryPage" id="page-memory" style="display: none;">
+ <div class="wrap" style="height: calc(100vh - 80px); display: grid; grid-template-columns: minmax(320px, 1fr) minmax(600px, 2fr); gap: 16px;">
+ <div class="leftCol" style="height: 100%; display: flex; flex-direction: column; min-height: 0;">
+ <section class="panel" style="flex: 1; display: flex; flex-direction: column; min-height: 0;">
+ <div class="panelHeader">
+ <h2>OpenViking 记忆目录</h2>
+ <div class="hint">世界记忆 / agent / user / 智能体</div>
+ </div>
+ <div class="memoryBody" style="flex: 1; display: flex; flex-direction: column; overflow: hidden; padding-right: 8px;">
+ <div class="searchRow" style="margin-bottom: 12px;">
+ <input class="searchInput" id="memSearch" placeholder="输入关键词检索记忆 / 记录 / 玩家" />
+ <button class="btn" id="memSearchBtn">检索</button>
+ </div>
+ <div class="treePanel">
+ <div class="treeHeader">
+ <div class="title">目录式展开</div>
+ <div class="sub" id="memTreeCount">0 files</div>
+ </div>
+ <div class="tree" id="memTree"></div>
+ </div>
+ </div>
+ </section>
+ </div>
+ <div class="rightCol" style="height: 100%; display: flex; flex-direction: column; min-height: 0;">
+ <section class="panel" style="flex: 1; display: flex; flex-direction: column; min-height: 0;">
+ <div class="panelHeader">
+ <h2>记忆查看器</h2>
+ <div class="hint">解析与格式化显示</div>
+ </div>
+ <div class="viewer" style="flex: 1; display: flex; flex-direction: column; overflow: hidden; min-height: 0;">
+ <div class="viewerTop">
+ <div class="title" id="viewerTitle">世界记忆 / GAME_RECORD.md</div>
+ </div>
+ <div class="viewerBody md" id="viewerBody" style="flex: 1; overflow-y: auto; max-height: none;"></div>
+ </div>
+ </section>
+ </div>
+ </div>
+ </section>
+ <section class="page rankPage" id="page-rank" style="display: none;">
+ <div class="wrap" style="height: calc(100vh - 80px); grid-template-columns: 1fr 1fr; gap: 16px;">
+ <div class="panel" style="width: 100%; height: 100%; display: flex; flex-direction: column;">
+ <div class="panelHeader">
+ <h2>排行榜</h2>
+ <div class="hint">存活 + 阵营胜负</div>
+ </div>
+ <div class="memoryBody" style="flex: 1; overflow-y: auto;">
+ <div class="rankList" id="rankList"></div>
+ </div>
+ </div>
+ <div class="panel" style="width: 100%; height: 100%; display: flex; flex-direction: column;">
+ <div class="panelHeader">
+ <h2>Agent 架构</h2>
+ <div class="hint">消息流向图</div>
+ </div>
+ <div class="memoryBody" style="flex: 1; display: flex; justify-content: center; align-items: center; overflow: hidden;">
+ <div id="relationGraph" style="width: 100%; height: 100%;"></div>
+ </div>
+ </div>
+ </div>
+ </section>
+ <div class="endOverlay" id="endOverlay">
+ <div class="endCard">
+ <div class="pulseRing"></div>
+ <div class="endTitle">游戏结束</div>
+ <div class="endWinner" id="endWinner">胜利方:-</div>
+ <div class="searchRow" style="margin: 8px 0;">
+ <select class="selectInput" id="restartMode">
+ <option value="random">随机配置</option>
+ <option value="classic">经典局</option>
+ <option value="tubian">屠边局</option>
+ <option value="whitewolf">白狼王局</option>
+ <option value="purewhite">纯白少女局</option>
+ </select>
+ </div>
+ <button class="btn" id="btnRestart">再来一局</button>
+ <div class="endStatus" id="endStatus"></div>
+ </div>
+ </div>
+ <div class="drawer" id="playerDrawer">
+ <div class="drawerHeader">
+ <div id="drawerTitle">玩家详情</div>
+ <button class="btn" id="drawerClose">关闭</button>
+ </div>
+ <div class="drawerBody">
+ <div class="raw" id="drawerContent"></div>
+ </div>
+ </div>
+
+ <script>
+ function escapeHtml(s) {
+ return String(s || '')
+ .replaceAll('&', '&amp;')
+ .replaceAll('<', '&lt;')
+ .replaceAll('>', '&gt;')
+ .replaceAll('"', '&quot;')
+ .replaceAll("'", '&#039;');
+ }
+
+ function mdToHtml(md) {
+ const src = String(md || '');
+ const lines = src.split(/\r?\n/);
+ let out = '';
+ let inCode = false;
+ let codeLang = '';
+ let listOpen = false;
+ function closeList() {
+ if (listOpen) {
+ out += '</ul>';
+ listOpen = false;
+ }
+ }
+ for (const rawLine of lines) {
+ const line = rawLine || '';
+ const fence = line.match(/^```(\w+)?\s*$/);
+ if (fence) {
+ closeList();
+ if (!inCode) {
+ inCode = true;
+ codeLang = fence[1] || '';
+ out += '<pre><code data-lang="' + escapeHtml(codeLang) + '">';
+ } else {
+ inCode = false;
+ out += '</code></pre>';
+ }
+ continue;
+ }
+ if (inCode) {
+ out += escapeHtml(line) + '\n';
+ continue;
+ }
+ const h = line.match(/^(#{1,3})\s+(.*)$/);
+ if (h) {
+ closeList();
+ const level = h[1].length;
+ out += '<h' + level + '>' + escapeHtml(h[2]) + '</h' + level + '>';
+ continue;
+ }
+ const li = line.match(/^\s*-\s+(.*)$/);
+ if (li) {
+ if (!listOpen) {
+ out += '<ul>';
+ listOpen = true;
+ }
+ out += '<li>' + escapeHtml(li[1]) + '</li>';
+ continue;
+ }
+ closeList();
+ if (line.trim() === '') {
+ out += '<div style="height:10px"></div>';
+ continue;
+ }
+ const inline = escapeHtml(line)
+ .replace(/`([^`]+)`/g, '<code>$1</code>')
+ .replace(/\*\*([^*]+)\*\*/g, '<b>$1</b>');
+ out += '<div>' + inline + '</div>';
+ }
+ closeList();
+ if (inCode) out += '</code></pre>';
+ return out;
+ }
+
+ function parseRecordInfo(recordText) {
+ const text = String(recordText || '');
+ const dead = new Set();
+
+ // Parse dead from old format: (昨夜死亡|放逐):X号
+ const deadRe = /(昨夜死亡|放逐):\s*(\d{1,2})号/g;
+ for (const m of text.matchAll(deadRe)) {
+ const seat = parseInt(m[2], 10);
+ if (!Number.isNaN(seat)) dead.add(seat - 1);
+ }
+
+ // Parse dead from new table format: | X号 | player_X | 身份 | 死亡 |
+ const tableRe = /\|\s*(\d+)号\s*\|\s*[^|]+\s*\|\s*[^|]+\s*\|\s*死亡\s*\|/g;
+ for (const m of text.matchAll(tableRe)) {
+ const seat = parseInt(m[1], 10);
+ if (!Number.isNaN(seat)) dead.add(seat - 1);
+ }
+
+ let badge = null;
+ const badgeRe = /警长当选:\s*(\d{1,2})号/g;
+ let badgeMatch = null;
+ for (const m of text.matchAll(badgeRe)) badgeMatch = m;
+ if (badgeMatch) {
+ const seat = parseInt(badgeMatch[1], 10);
+ if (!Number.isNaN(seat)) badge = seat - 1;
+ }
+
+ let campaigners = [];
+ const campRe = /警长竞选:候选人\n((?:-\s*\d+号\n?)*)/g;
+ let campMatch = null;
+ for (const m of text.matchAll(campRe)) campMatch = m;
+ if (campMatch && badge === null) { // 只有在最终警长还没产生时才标记候选人
+ const lines = campMatch[1].split('\n');
+ for (const line of lines) {
+ const m = line.match(/-\s*(\d+)号/);
+ if (m) campaigners.push(parseInt(m[1], 10) - 1);
+ }
+ }
+
+ const dayRe = /第(\d+)天/g;
+ const nightRe = /第(\d+)晚/g;
+ let lastDay = null;
+ let lastNight = null;
+ for (const m of text.matchAll(dayRe)) lastDay = parseInt(m[1], 10);
+ for (const m of text.matchAll(nightRe)) lastNight = parseInt(m[1], 10);
+
+ // Parse day/night from game time field: - 游戏时间: [白天/黑夜]
+ const timeRe = /游戏时间[::]\s*\[?(白天|黑夜)\]?/;
+ const timeMatch = text.match(timeRe);
+
+ let lastSection = '';
+ const sectionRe = /^##\s+(.+)$/gm;
+ for (const sm of text.matchAll(sectionRe)) lastSection = sm[1];
+
+ let phase = 'day';
+ let isNight = false;
+
+ if (timeMatch) {
+ // Use explicit game time field if available
+ isNight = timeMatch[1] === '黑夜';
+ } else {
+ // Fall back to section-based detection
+ isNight = lastSection.includes('夜');
+ }
+
+ if (lastSection.includes('投票')) phase = 'vote';
+ else if (isNight) phase = 'night';
+ else if (lastSection.includes('竞选')) phase = 'day';
+ else if (lastSection.includes('发言')) phase = 'day';
+
+ const round = isNight ? (lastNight || 0) : (lastDay || 0);
+ const day = lastDay || 0;
+
+ let winner = '';
+ const winRe = /游戏结束:\s*(.+)\s*$/gm;
+ let m = null;
+ for (const mm of text.matchAll(winRe)) m = mm;
+ if (m && m[1]) winner = m[1].trim();
+
+ return { dead, badge, isNight, round, day, winner, phase, lastSection };
+ }
+
+ function roleInfo(role) {
+ const r = String(role || '未知');
+ const map = {
+ Seer: { kind: 'special', label: 'SEER' },
+ Witch: { kind: 'special', label: 'WITCH' },
+ Hunter: { kind: 'special', label: 'HUNTER' },
+ Guard: { kind: 'special', label: 'GUARD' },
+ Guardian: { kind: 'special', label: 'GUARD' },
+ Dreamer: { kind: 'special', label: 'DREAMER' },
+ PureWhiteGirl: { kind: 'special', label: 'PURE WHITE' },
+ OldVillageChief: { kind: 'special', label: 'CHIEF' },
+ Villager: { kind: 'good', label: 'VILLAGER' },
+ Werewolf: { kind: 'bad', label: 'WEREWOLF' },
+ WhiteWolfKing: { kind: 'bad', label: 'WHITE WOLF' },
+ WolfCub: { kind: 'bad', label: 'WOLF CUB' },
+ WolfBeauty: { kind: 'bad', label: 'WOLF BEAUTY' },
+ Idiot: { kind: 'special', label: 'IDIOT' },
+ };
+ return map[r] || { kind: 'good', label: r.toUpperCase() };
+ }
+
+ function sigilSvg(role) {
+ const r = String(role || '');
+ if (r === 'Werewolf' || r === 'WhiteWolfKing' || r === 'WolfCub' || r === 'WolfBeauty') {
+ return '<svg viewBox="0 0 24 24" fill="none"><path d="M6 20l2-8-4-2 4-6 4 4 4-4 4 6-4 2 2 8" stroke="rgba(251,113,133,0.95)" stroke-width="2"/><path d="M9 14h6" stroke="rgba(251,113,133,0.95)" stroke-width="2"/></svg>';
+ }
+ if (r === 'Seer') {
+ return '<svg viewBox="0 0 24 24" fill="none"><path d="M12 3l3 6 6 3-6 3-3 6-3-6-6-3 6-3 3-6z" stroke="rgba(56,189,248,0.95)" stroke-width="2"/><circle cx="12" cy="12" r="2.5" stroke="rgba(56,189,248,0.95)" stroke-width="2"/></svg>';
+ }
+ if (r === 'Witch') {
+ return '<svg viewBox="0 0 24 24" fill="none"><path d="M8 9h8l-1 10H9L8 9z" stroke="rgba(251,191,36,0.95)" stroke-width="2"/><path d="M10 9c0-3 1-5 2-5s2 2 2 5" stroke="rgba(251,191,36,0.95)" stroke-width="2"/></svg>';
+ }
+ if (r === 'Hunter') {
+ return '<svg viewBox="0 0 24 24" fill="none"><path d="M4 18l8-8 8 8" stroke="rgba(251,191,36,0.95)" stroke-width="2"/><path d="M12 10V4" stroke="rgba(251,191,36,0.95)" stroke-width="2"/></svg>';
+ }
+ if (r === 'Guard' || r === 'Guardian') {
+ return '<svg viewBox="0 0 24 24" fill="none"><path d="M12 3l8 4v6c0 5-4 8-8 8s-8-3-8-8V7l8-4z" stroke="rgba(110,231,183,0.95)" stroke-width="2"/><path d="M12 7v10" stroke="rgba(110,231,183,0.95)" stroke-width="2"/></svg>';
+ }
+ if (r === 'Idiot') {
+ return '<svg viewBox="0 0 24 24" fill="none"><path d="M7 18c0-3 2-5 5-5s5 2 5 5" stroke="rgba(251,191,36,0.95)" stroke-width="2"/><path d="M9 10l3-6 3 6" stroke="rgba(251,191,36,0.95)" stroke-width="2"/></svg>';
+ }
+ return '<svg viewBox="0 0 24 24" fill="none"><path d="M6 8h12M6 12h12M6 16h12" stroke="rgba(110,231,183,0.95)" stroke-width="2"/></svg>';
+ }
+
+ async function getDirHandleByPath(rootHandle, segments) {
+ let h = rootHandle;
+ for (const s of segments) {
+ h = await h.getDirectoryHandle(s, { create: false });
+ }
+ return h;
+ }
+
+ async function readTextFile(rootHandle, pathSegments) {
+ try {
+ const dirSegs = pathSegments.slice(0, -1);
+ const fileName = pathSegments[pathSegments.length - 1];
+ const dir = dirSegs.length ? await getDirHandleByPath(rootHandle, dirSegs) : rootHandle;
+ const fileHandle = await dir.getFileHandle(fileName, { create: false });
+ const file = await fileHandle.getFile();
+ const txt = await file.text();
+ return { text: txt, lastModified: file.lastModified };
+ } catch (_) {
+ return { text: '', lastModified: 0 };
+ }
+ }
+
+ function extractRole(gameMd) {
+ const md = String(gameMd || '');
+ let role = '未知';
+ for (const line of md.split(/\r?\n/)) {
+ const match = line.match(/身份[::]\s*(.+)/);
+ if (match) {
+ role = match[1].trim();
+ break;
+ }
+ }
+
+ // Strip any leading emoji or special characters
+ role = role.replace(/^[\s\p{Emoji}\p{P}]+/gu, '').trim();
+
+ // Fallback: guess from phase headers if missing
+ if (role === '未知') {
+ if (/女巫/.test(md)) role = 'Witch';
+ else if (/预言家/.test(md)) role = 'Seer';
+ else if (/守卫/.test(md)) role = 'Guard';
+ else if (/猎人/.test(md)) role = 'Hunter';
+ else if (/狼人/.test(md)) role = 'Werewolf';
+ else if (/发言/.test(md)) role = 'Villager';
+ }
+
+ // Map Chinese roles to English keys used by roleInfo
+ const roleMap = {
+ '女巫': 'Witch',
+ '预言家': 'Seer',
+ '守卫': 'Guard',
+ '猎人': 'Hunter',
+ '狼人': 'Werewolf',
+ '平民': 'Villager',
+ '村民': 'Villager',
+ '白狼王': 'WhiteWolfKing',
+ '狼美人': 'WolfBeauty',
+ '白痴': 'Idiot'
+ };
+
+ return roleMap[role] || role;
+ }
+
+ function extractLastSpeech(gameMd, currentPhase) {
+ const md = String(gameMd || '');
+
+ if (currentPhase === 'night' || currentPhase === 'vote') return '';
+
+ const idx = md.lastIndexOf('发言:');
+ if (idx === -1) return '';
+ const seg = md.slice(idx).split(/\r?\n/);
+ if (!seg.length) return '';
+
+ const voteIdx = md.lastIndexOf('投票:');
+ if (voteIdx > idx) return '';
+
+ return seg[0].replace(/.*?(竞选发言:|发言:)/, '').trim();
+ }
+
+ function stripMarkdown(text) {
+ let s = String(text || '');
+ s = s.replace(/```[\s\S]*?```/g, ' ');
+ s = s.replace(/`([^`]+)`/g, '$1');
+ s = s.replace(/^#{1,6}\s*/gm, '');
+ s = s.replace(/^\s*[-*+]\s+/gm, '');
+ s = s.replace(/\*\*([^*]+)\*\*/g, '$1');
+ s = s.replace(/\*([^*]+)\*/g, '$1');
+ s = s.replace(/__([^_]+)__/g, '$1');
+ s = s.replace(/_([^_]+)_/g, '$1');
+ s = s.replace(/\[([^\]]+)\]\([^)]+\)/g, '$1');
+ s = s.replace(/\s+/g, ' ').trim();
+ return s;
+ }
+
+ function extractBadgeCandidates(recordText) {
+ const text = String(recordText || '');
+ const match = text.match(/## 警长竞选:候选人\r?\n([^\n]+)/);
+ if (!match) return new Set();
+ const candidates = new Set();
+ const parts = match[1].split('、');
+ parts.forEach(p => {
+ const m = p.match(/(\d+)/);
+ if (m) {
+ candidates.add(parseInt(m[1], 10) - 1);
+ }
+ });
+ return candidates;
+ }
+
+ function extractLatestVote(gameMd, day) {
+ const md = String(gameMd || '');
+ const re = new RegExp(`##\\s+第${day}天-投票[\\s\\S]*?-\\s*投票:\\s*(\\d{1,2})号`, 'm');
+ const m = md.match(re);
+ if (!m) return null;
+ const v = parseInt(m[1], 10);
+ return Number.isNaN(v) ? null : v;
+ }
+
+ function extractLatestSpeechLines(players) {
+ const sorted = [...players].filter(p => p.last_speech).sort((a, b) => String(a.updated_at || '').localeCompare(String(b.updated_at || '')));
+ return sorted.map(p => ({
+ type: 'speech',
+ id: p.id,
+ text: stripMarkdown(p.last_speech),
+ role: p.role,
+ }));
+ }
+
+ function parseRecordMessages(recordText, players) {
+ const lines = String(recordText || '').split(/\r?\n/);
+ const msgs = [];
+
+ // 合并系统消息和玩家发言
+ for (const line of lines) {
+ if (!line) continue;
+
+ // 提取带座位号的系统消息或流程标题
+ if (line.startsWith('## ')) {
+ msgs.push({ type: 'system', text: line.replace('## ', ''), timestamp: msgs.length });
+ } else if (/(昨夜死亡|放逐|警长当选|游戏结束|狼人投票结果|玩家身份|游戏信息|游戏状态|当前阶段)/.test(line)) {
+ msgs.push({ type: 'system', text: line, timestamp: msgs.length });
+ } else if (line.startsWith('- ')) {
+ // Also show list items from game info section
+ msgs.push({ type: 'system', text: line, timestamp: msgs.length });
+ }
+ }
+
+ // 如果有玩家发言,将其插入到正确的阶段后面
+ // (基于 GAME.md 中按天记录的特点)
+ if (players && players.length > 0) {
+ const speechMap = new Map();
+
+ players.forEach(p => {
+ if (p.has_session === false) return;
+ const gameMd = p.game || '';
+ const pLines = gameMd.split(/\r?\n/);
+ let currentPhase = '';
+
+ for (let i = 0; i < pLines.length; i++) {
+ const line = pLines[i];
+ const phaseMatch = line.match(/^##\s+(第\d+天-发言|警长竞选|警长竞选发言)\s*$/);
+ if (phaseMatch) {
+ // Normalize phase name
+ currentPhase = phaseMatch[1].replace('发言', '') === '警长竞选' ? '警长竞选' : phaseMatch[1];
+ } else if (currentPhase && line.startsWith('- 发言:')) {
+ const text = stripMarkdown(line.replace('- 发言:', ''));
+ if (text) {
+ if (!speechMap.has(currentPhase)) speechMap.set(currentPhase, []);
+ speechMap.get(currentPhase).push({
+ type: 'speech',
+ id: p.id,
+ text: text,
+ role: p.role,
+ seat: parseInt(p.id.split('_')[1], 10) || 0
+ });
+ }
+ } else if (currentPhase && line.startsWith('- 竞选发言:')) {
+ const text = stripMarkdown(line.replace('- 竞选发言:', ''));
+ if (text) {
+ if (!speechMap.has('警长竞选')) speechMap.set('警长竞选', []);
+ speechMap.get('警长竞选').push({
+ type: 'speech',
+ id: p.id,
+ text: text,
+ role: p.role,
+ seat: parseInt(p.id.split('_')[1], 10) || 0
+ });
+ }
+ }
+ }
+ });
+
+ // 重组消息流:找到系统流程节点,把对应的发言插入后面
+ const mergedMsgs = [];
+ let speechPhaseToInject = null;
+
+ // Find out what speeches are already seen from previous states
+ const previousSeenTexts = new Set((uiState.lastSpeechKey || '').split('|'));
+
+ for (const msg of msgs) {
+ mergedMsgs.push(msg);
+
+ if (msg.type === 'system') {
+ // First logic: map the system event to a phase name
+ if (msg.text.includes('警长竞选:候选人') || msg.text.includes('警长竞选:开始')) {
+ speechPhaseToInject = '警长竞选';
+ } else if (msg.text.includes('发言环节:开始')) {
+ // Wait for the explicit daytime speech event to start before injecting
+ const dayMatch = msg.text.match(/第(\d+)天:开始/);
+ // But we don't have this explicit text in the record right now!
+ // Let's use the '警长当选' or '昨夜死亡' as a trigger for daytime speech
+ } else if (msg.text.match(/第\d+天:开始/)) {
+ // We will inject speech at the END of the daytime events, usually after "警长当选"
+ // Or if it's day 2, after "昨夜死亡"
+ } else if (msg.text.includes('投票结果') || msg.text.includes('投票:')) {
+ speechPhaseToInject = null;
+ }
+
+ // Let's check if the current system event is the trigger to show speeches
+ if (msg.text.includes('警长当选') || msg.text.match(/第\d+天:开始/) && !speechMap.has('警长竞选')) {
+ // If sheriff is elected, or day starts (and no election), inject daytime speeches
+ const roundMatch = msg.text.match(/第(\d+)天:开始/);
+ // We don't have day in '警长当选', so we need to track it
+ }
+
+ // New logic to ensure speeches are shown right after the correct events
+ let triggerPhase = null;
+ if (msg.text.includes('警长竞选:候选人')) {
+ triggerPhase = '警长竞选';
+ } else if (msg.text.includes('警长当选')) {
+ // Day 1 speech happens after sheriff is elected
+ triggerPhase = '第1天-发言';
+ } else if (msg.text.includes('第1天:开始') && !msg.text.includes('警长当选')) {
+ // If there's no sheriff elected yet, the speech might be queued. We will let '警长当选' handle it.
+ } else if (msg.text.match(/第\d+天:开始/)) {
+ // For Day 2 and onwards, speech happens immediately after day starts
+ const dayMatch = msg.text.match(/第(\d+)天:开始/);
+ if (dayMatch && parseInt(dayMatch[1]) > 1) {
+ triggerPhase = `第${dayMatch[1]}天-发言`;
+ }
+ }
+
+ if (triggerPhase && speechMap.has(triggerPhase)) {
+ const speeches = speechMap.get(triggerPhase);
+ speeches.sort((a, b) => a.seat - b.seat);
+ speeches.forEach(sp => {
+ sp.isNew = !previousSeenTexts.has(sp.text);
+ mergedMsgs.push(sp);
+ });
+ speechMap.delete(triggerPhase);
+ }
+ }
+ }
+
+ // Handle any remaining speeches that didn't find a matching trigger
+ speechMap.forEach((speeches, phase) => {
+ speeches.sort((a, b) => a.seat - b.seat);
+ speeches.forEach(sp => {
+ sp.isNew = !previousSeenTexts.has(sp.text);
+ mergedMsgs.push(sp);
+ });
+ });
+
+ return mergedMsgs;
+ }
+
+ return msgs;
+ }
+
+ function extractVotes(players, day) {
+ const map = new Map();
+ players.forEach((p, i) => {
+ const vote = extractLatestVote(p.game || '', day);
+ if (vote) map.set(i, vote);
+ });
+ return map;
+ }
+
+ function renderChat(data, info) {
+ const chatBody = document.getElementById('chatBody');
+ const chatStatus = document.getElementById('chatStatus');
+ const chatVotes = document.getElementById('chatVotes');
+ if (!chatBody) return;
+
+ if (data && data._starting) {
+ uiState.lastSpeechKey = '';
+ chatBody.innerHTML = '';
+ if (chatStatus) chatStatus.textContent = '新局启动中...';
+ if (chatVotes) chatVotes.innerHTML = '';
+ return;
+ }
+
+ const merged = parseRecordMessages(data.game_record || '', data.players || []);
+ const speechKey = merged.filter(m => m.type === 'speech').map(m => m.text).join('|');
+
+ // Determine if we need to full re-render
+ const currentChatItems = chatBody.querySelectorAll('.chatBubble');
+ const needsFullRender = currentChatItems.length !== merged.length || uiState.lastSpeechKey !== speechKey;
+
+ if (needsFullRender) {
+ uiState.lastSpeechKey = speechKey;
+ chatBody.innerHTML = '';
+
+ const animateIdx = (() => {
+ for (let i = merged.length - 1; i >= 0; i--) {
+ if (merged[i].type === 'speech' && merged[i].isNew) return i;
+ }
+ return -1;
+ })();
+
+ merged.forEach((m, idx) => {
+ const row = document.createElement('div');
+ row.className = 'chatBubble' + (m.type === 'system' ? ' system' : '');
+ const avatar = document.createElement('div');
+ avatar.className = 'avatarMini';
+ if (m.type !== 'system') {
+ const player = (data.players || []).find(p => p.id === m.id);
+ avatar.innerHTML = sigilSvg(player ? player.role : '');
+ } else {
+ avatar.textContent = '!';
+ }
+ const text = document.createElement('div');
+ text.className = 'text';
+
+ row.appendChild(avatar);
+ row.appendChild(text);
+ chatBody.appendChild(row);
+
+ if (idx === animateIdx && m.type === 'speech' && m.isNew) {
+ typeSpeech(text, m.text);
+ } else {
+ if (m.type === 'system') {
+ text.innerHTML = m.text;
+ } else {
+ text.textContent = m.text;
+ }
+ }
+ });
+ chatBody.scrollTop = chatBody.scrollHeight;
+ }
+
+ const dead = info.dead.size;
+ const alive = Math.max(0, (data.players || []).length - dead);
+ const phaseLabel = info.phase === 'vote' ? '投票中' : (info.isNight ? '黑夜' : '白天');
+ chatStatus.textContent = `${phaseLabel} · 存活 ${alive}/${(data.players || []).length}`;
+ chatVotes.innerHTML = '';
+ if (info.phase === 'vote') {
+ const votes = extractVotes(data.players || [], info.round || 1);
+ const tally = new Map();
+ votes.forEach((v, seatIdx) => {
+ const pill = document.createElement('div');
+ pill.className = 'pill';
+ pill.textContent = `${String(seatIdx + 1).padStart(2, '0')}号已投`;
+ chatVotes.appendChild(pill);
+ tally.set(v, (tally.get(v) || 0) + 1);
+ });
+ const total = (data.players || []).length;
+ const voted = votes.size;
+ const summary = document.createElement('div');
+ summary.className = 'pill';
+ summary.textContent = `已投票 ${voted}/${total}`;
+ chatVotes.appendChild(summary);
+ const result = Array.from(tally.entries()).sort((a, b) => b[1] - a[1]).map(([k, v]) => `${k}号(${v})`).join(' ');
+ if (result) {
+ const res = document.createElement('div');
+ res.className = 'pill';
+ res.textContent = `归票 ${result}`;
+ chatVotes.appendChild(res);
+ }
+ }
+ }
+
+ function renderChatFromMessages(messages, info, data) {
+ const chatBody = document.getElementById('chatBody');
+ const chatStatus = document.getElementById('chatStatus');
+ const chatVotes = document.getElementById('chatVotes');
+ if (!chatBody) return;
+
+ // Generate a key for the current state
+ const messagesKey = messages.map(m => `${m.channel_id}:${m.timestamp}:${m.content.substring(0, 50)}`).join('|');
+
+ // Check if we need to re-render
+ const currentChatItems = chatBody.querySelectorAll('.chatBubble');
+ const needsFullRender = currentChatItems.length !== messages.length || uiState.lastSpeechKey !== messagesKey;
+
+ if (needsFullRender) {
+ uiState.lastSpeechKey = messagesKey;
+ chatBody.innerHTML = '';
+
+ messages.forEach((msg, idx) => {
+ const row = document.createElement('div');
+ row.className = 'chatBubble' + (msg.is_user ? ' system' : '');
+ row.style.marginBottom = '8px';
+ row.style.padding = '8px 12px';
+
+ // Different background color for god
+ if (!msg.is_user && msg.channel_id === 'god') {
+ row.style.background = 'rgba(59, 130, 246, 0.15)';
+ row.style.borderRadius = '12px';
+ row.style.border = '1px solid rgba(59, 130, 246, 0.3)';
+ }
+
+ const avatar = document.createElement('div');
+ avatar.className = 'avatarMini';
+ avatar.style.flexShrink = '0';
+ avatar.style.marginRight = '10px';
+
+ if (msg.is_user) {
+ // System message (sent to agent)
+ avatar.textContent = '→';
+ avatar.style.fontSize = '14px';
+ } else {
+ // Agent reply
+ const player = (data.players || []).find(p => p.id === msg.channel_id);
+ if (player) {
+ avatar.innerHTML = sigilSvg(player.role);
+ } else if (msg.channel_id === 'god') {
+ avatar.innerHTML = sigilSvg('');
+ } else {
+ avatar.textContent = '?';
+ }
+ }
+
+ const text = document.createElement('div');
+ text.className = 'text';
+ text.style.flex = '1';
+ text.style.minWidth = '0';
+ text.style.overflow = 'hidden';
+
+ // Add sender label
+ const label = document.createElement('div');
+ label.style.fontWeight = '600';
+ label.style.fontSize = '11px';
+ label.style.opacity = '0.8';
+ label.style.marginBottom = '2px';
+ label.style.display = 'flex';
+ label.style.alignItems = 'center';
+ label.style.gap = '6px';
+
+ const nameSpan = document.createElement('span');
+ nameSpan.textContent = msg.channel_id;
+ if (msg.is_user) {
+ nameSpan.style.color = '#fbbf24'; // admin - yellow (original)
+ } else if (msg.channel_id === 'god') {
+ nameSpan.style.color = '#3b82f6'; // god - darker blue
+ } else {
+ nameSpan.style.color = '#60a5fa'; // players - original light blue
+ }
+ label.appendChild(nameSpan);
+
+ const typeSpan = document.createElement('span');
+ typeSpan.textContent = msg.is_user ? '发送' : '回复';
+ typeSpan.style.opacity = '0.6';
+ typeSpan.style.fontSize = '10px';
+ label.appendChild(typeSpan);
+
+ const time = new Date(msg.timestamp * 1000).toLocaleTimeString();
+ const timeSpan = document.createElement('span');
+ timeSpan.textContent = time;
+ timeSpan.style.opacity = '0.5';
+ timeSpan.style.fontSize = '10px';
+ timeSpan.style.marginLeft = 'auto';
+ label.appendChild(timeSpan);
+
+ text.appendChild(label);
+
+ // Add message content
+ const content = document.createElement('div');
+ content.textContent = msg.content;
+ content.style.fontSize = '13px';
+ content.style.lineHeight = '1.5';
+ content.style.wordWrap = 'break-word';
+ content.style.overflowWrap = 'break-word';
+ content.style.whiteSpace = 'pre-wrap';
+ content.style.color = 'rgba(255,255,255,0.9)';
+ text.appendChild(content);
+
+ row.appendChild(avatar);
+ row.appendChild(text);
+ chatBody.appendChild(row);
+ });
+
+ chatBody.scrollTop = chatBody.scrollHeight;
+ }
+
+ const dead = info.dead.size;
+ const alive = Math.max(0, (data.players || []).length - dead);
+ const phaseLabel = info.phase === 'vote' ? '投票中' : (info.isNight ? '黑夜' : '白天');
+ chatStatus.textContent = `${phaseLabel} · 存活 ${alive}/${(data.players || []).length}`;
+ chatVotes.innerHTML = '';
+ if (info.phase === 'vote') {
+ const votes = extractVotes(data.players || [], info.round || 1);
+ const tally = new Map();
+ votes.forEach((v, seatIdx) => {
+ const pill = document.createElement('div');
+ pill.className = 'pill';
+ pill.textContent = `${String(seatIdx + 1).padStart(2, '0')}号已投`;
+ chatVotes.appendChild(pill);
+ tally.set(v, (tally.get(v) || 0) + 1);
+ });
+ const total = (data.players || []).length;
+ const voted = votes.size;
+ const summary = document.createElement('div');
+ summary.className = 'pill';
+ summary.textContent = `已投票 ${voted}/${total}`;
+ chatVotes.appendChild(summary);
+ const result = Array.from(tally.entries()).sort((a, b) => b[1] - a[1]).map(([k, v]) => `${k}号(${v})`).join(' ');
+ if (result) {
+ const res = document.createElement('div');
+ res.className = 'pill';
+ res.textContent = `归票 ${result}`;
+ chatVotes.appendChild(res);
+ }
+ }
+ }
+
+ function openDrawer(player, seatIdx) {
+ const drawer = document.getElementById('playerDrawer');
+ const title = document.getElementById('drawerTitle');
+ const content = document.getElementById('drawerContent');
+ if (!drawer || !content) return;
+ title.textContent = `${String(seatIdx + 1).padStart(2, '0')}号 ${player.id || ''}`;
+
+ // Use markdown rendering for drawer content
+ content.className = 'drawerBody md';
+ content.innerHTML = mdToHtml(player.game || '');
+
+ drawer.classList.add('show');
+ }
+
+ function bindDrawer() {
+ const btn = document.getElementById('drawerClose');
+ const drawer = document.getElementById('playerDrawer');
+ if (btn && drawer) {
+ btn.addEventListener('click', () => drawer.classList.remove('show'));
+ }
+ }
+
+ function bindSearch() {
+ const memSearchBtn = document.getElementById('memSearchBtn');
+ const memSearchInput = document.getElementById('memSearch');
+ if (!memSearchBtn || !memSearchInput) return;
+ const doSearch = () => {
+ const keyword = memSearchInput.value.toLowerCase().trim();
+ if (!keyword || !uiState.lastData) return;
+ const lookup = buildMemoryLookup(uiState.lastData);
+
+ // Match both exact path and title text, making it easier to find e.g., "player_01"
+ const found = Array.from(lookup.entries()).find(([k, v]) =>
+ k.toLowerCase().includes(keyword) ||
+ (v.title && v.title.toLowerCase().includes(keyword)) ||
+ (v.content && v.content.toLowerCase().includes(keyword))
+ );
+
+ if (found) {
+ selectKey(found[0]);
+ setTimeout(() => {
+ const btn = document.querySelector(`.fileBtn[data-key="${found[0]}"]`);
+ if (btn) {
+ let p = btn.parentElement;
+ while (p) {
+ if (p.tagName === 'DETAILS') p.open = true;
+ p = p.parentElement;
+ }
+ btn.scrollIntoView({ behavior: 'smooth', block: 'center' });
+ }
+ }, 50);
+ } else {
+ // If not found, maybe show a brief alert
+ console.log('未找到匹配项');
+ }
+ };
+ memSearchBtn.addEventListener('click', doSearch);
+ memSearchInput.addEventListener('keypress', (e) => {
+ if (e.key === 'Enter') doSearch();
+ });
+ }
+
+ async function listPlayerDirs(workspaceHandle) {
+ const players = [];
+ for await (const [name, handle] of workspaceHandle.entries()) {
+ if (handle.kind !== 'directory') continue;
+ if (!name.startsWith('demo__werewolf__player_')) continue;
+ players.push({ name, handle });
+ }
+ players.sort((a, b) => a.name.localeCompare(b.name));
+ return players;
+ }
+
+ async function isDistributedRoot(workspaceHandle) {
+ if (!workspaceHandle) return false;
+ try {
+ await getDirHandleByPath(workspaceHandle, ['player_01']);
+ return true;
+ } catch (err) {
+ return false;
+ }
+ }
+
+ async function findSessionDirWithGame(workspaceDir) {
+ if (!workspaceDir) return null;
+ const candidates = [];
+ for await (const [name, handle] of workspaceDir.entries()) {
+ if (handle.kind !== 'directory') continue;
+ candidates.push({ name, handle });
+ }
+ candidates.sort((a, b) => a.name.localeCompare(b.name));
+ let best = null;
+ for (const c of candidates) {
+ const game = await readTextFile(c.handle, ['GAME.md']);
+ if (!game.text) continue;
+ if (!best || (game.lastModified || 0) > (best.lastModified || 0)) {
+ best = { handle: c.handle, lastModified: game.lastModified || 0 };
+ }
+ }
+ return best ? best.handle : (candidates.length ? candidates[0].handle : null);
+ }
+
+ async function readLatestRecord(refereeSession) {
+ if (!refereeSession) return { text: '', lastModified: 0 };
+ const records = [];
+ for await (const [name, handle] of refereeSession.entries()) {
+ if (handle.kind !== 'file') continue;
+ if (!name.startsWith('GAME_RECORD_') || !name.endsWith('.md')) continue;
+ const file = await handle.getFile();
+ records.push({ name, handle, lastModified: file.lastModified || 0 });
+ }
+ if (!records.length) return readTextFile(refereeSession, ['GAME_RECORD.md']);
+ records.sort((a, b) => b.lastModified - a.lastModified);
+ const f = await records[0].handle.getFile();
+ return { text: await f.text(), lastModified: records[0].lastModified };
+ }
+
+ async function listDistributedPlayers(dataRoot) {
+ const players = [];
+ for await (const [name, handle] of dataRoot.entries()) {
+ if (handle.kind !== 'directory') continue;
+ if (!name.startsWith('player_')) continue;
+ players.push({ name, handle });
+ }
+ players.sort((a, b) => a.name.localeCompare(b.name));
+ return players;
+ }
+
+ async function resolveWorldMemory(storageHandle) {
+ if (!storageHandle) return { overview: '', abstract: '', entities: '', events: '', preferences: '' };
+ const candidates = [
+ ['viking', 'werewolf_demo', 'user', 'referee', 'memories'],
+ ['viking', 'default', 'user', 'default', 'memories'],
+ ];
+ for (const segs of candidates) {
+ try {
+ const baseDir = await getDirHandleByPath(storageHandle, segs);
+ return {
+ overview: (await readTextFile(baseDir, ['.overview.md'])).text,
+ abstract: (await readTextFile(baseDir, ['.abstract.md'])).text,
+ entities: (await readTextFile(baseDir, ['entities', '.overview.md'])).text,
+ events: (await readTextFile(baseDir, ['events', '.overview.md'])).text,
+ preferences: (await readTextFile(baseDir, ['preferences', '.overview.md'])).text,
+ };
+ } catch (err) {
+ continue;
+ }
+ }
+ return { overview: '', abstract: '', entities: '', events: '', preferences: '' };
+ }
+
+ async function loadDataFromFS(workspaceHandle, storageHandle) {
+ const out = { game_record: '', world_memory: { overview: '', abstract: '', entities: '', events: '', preferences: '' }, players: [] };
+ if (workspaceHandle) {
+ if (await isDistributedRoot(workspaceHandle)) {
+ const refereeWorkspace = await getDirHandleByPath(workspaceHandle, ['referee', 'bot', 'workspace']);
+ const refereeSession = await findSessionDirWithGame(refereeWorkspace);
+ const record = await readLatestRecord(refereeSession);
+ out.game_record = record.text;
+ const playerDirs = await listDistributedPlayers(workspaceHandle);
+ for (const p of playerDirs) {
+ const ws = await getDirHandleByPath(p.handle, ['bot', 'workspace']);
+ const session = await findSessionDirWithGame(ws);
+ const game = await readTextFile(session, ['GAME.md']);
+ const memory = await readTextFile(session, ['memory', 'MEMORY.md']);
+ const history = await readTextFile(session, ['memory', 'HISTORY.md']);
+ const role = extractRole(game.text);
+ const info = out.game_record ? parseRecordInfo(out.game_record) : { phase: 'day' };
+ const lastSpeech = extractLastSpeech(game.text, info.phase);
+ out.players.push({
+ id: p.name,
+ game: game.text,
+ memory: memory.text,
+ history: history.text,
+ role,
+ last_speech: lastSpeech,
+ updated_at: String(Math.max(game.lastModified || 0, memory.lastModified || 0, history.lastModified || 0)),
+ });
+ }
+ } else {
+ const refereeDir = await getDirHandleByPath(workspaceHandle, ['demo__werewolf__referee']);
+ const record = await readTextFile(refereeDir, ['GAME_RECORD.md']);
+ out.game_record = record.text;
+ const playerDirs = await listPlayerDirs(workspaceHandle);
+ for (const p of playerDirs) {
+ const game = await readTextFile(p.handle, ['GAME.md']);
+ const memory = await readTextFile(p.handle, ['memory', 'MEMORY.md']);
+ const history = await readTextFile(p.handle, ['memory', 'HISTORY.md']);
+ const role = extractRole(game.text);
+ const info = out.game_record ? parseRecordInfo(out.game_record) : { phase: 'day' };
+ const lastSpeech = extractLastSpeech(game.text, info.phase);
+ out.players.push({
+ id: p.name,
+ game: game.text,
+ memory: memory.text,
+ history: history.text,
+ role,
+ last_speech: lastSpeech,
+ updated_at: String(Math.max(game.lastModified || 0, memory.lastModified || 0, history.lastModified || 0)),
+ });
+ }
+ }
+ }
+ if (storageHandle || workspaceHandle) {
+ const baseHandle = storageHandle || workspaceHandle;
+ out.world_memory = await resolveWorldMemory(baseHandle);
+ }
+ return out;
+ }
+
+ const uiState = {
+ selectedKey: 'world/GAME_RECORD.md',
+ viewerMode: 'render',
+ lastData: null,
+ workspaceHandle: null,
+ storageHandle: null,
+ httpBase: '/data',
+ lastArenaSpeechKey: '',
+ lastSpeechKey: '',
+ loading: false,
+ openvikingTree: null,
+ selectedOpenvikingPath: null,
+ expandedDetails: new Set(),
+ conversations: null,
+ botSessions: null,
+ };
+
+ function setViewer(title, content) {
+ const titleEl = document.getElementById('viewerTitle');
+ const bodyEl = document.getElementById('viewerBody');
+ if (titleEl) titleEl.textContent = title || '';
+ if (bodyEl) {
+ bodyEl.className = 'viewerBody md';
+ bodyEl.style.fontSize = '';
+ bodyEl.style.lineHeight = '';
+ bodyEl.innerHTML = mdToHtml(content || '');
+ }
+ }
+
+ function buildMemoryLookup(data) {
+ const m = new Map();
+ const record = data.game_record || '';
+ const world = data.world_memory || {};
+
+ // History records
+ if (data.history && data.history.records && data.history.records.length > 0) {
+ data.history.records.forEach((r, idx) => {
+ const suffix = idx === 0 ? ' (Latest)' : ` (${r.session.replace('cli__default__werewolf_', '')})`;
+ const key = `world/GAME_RECORD_${r.session}.md`;
+ m.set(key, { title: `世界记忆 / GAME_RECORD.md${suffix}`, content: r.text });
+ if (idx === 0) m.set('world/GAME_RECORD.md', { title: `世界记忆 / GAME_RECORD.md${suffix}`, content: r.text });
+ });
+ } else {
+ m.set('world/GAME_RECORD.md', { title: '世界记忆 / GAME_RECORD.md', content: record });
+ }
+
+ m.set('openviking/User Memory/.overview.md', { title: 'OpenViking / User Memory / .overview.md', content: world.overview || '' });
+ m.set('openviking/User Memory/.abstract.md', { title: 'OpenViking / User Memory / .abstract.md', content: world.abstract || '' });
+ m.set('openviking/entities/.overview.md', { title: 'OpenViking / entities / .overview.md', content: world.entities || '' });
+ m.set('openviking/events/.overview.md', { title: 'OpenViking / events / .overview.md', content: world.events || '' });
+ m.set('openviking/preferences/.overview.md', { title: 'OpenViking / preferences / .overview.md', content: world.preferences || '' });
+ const players = data.players || [];
+ players.forEach((p, i) => {
+ const seat = i + 1;
+ const pId = p.id || ('player_' + seat);
+ const base = 'agents/' + String(seat).padStart(2, '0') + '-' + pId;
+
+ if (data.history && data.history.player_sessions && data.history.player_sessions[pId]) {
+ data.history.player_sessions[pId].forEach((s, idx) => {
+ const suffix = idx === 0 ? ' (Latest)' : ` (${s.session.replace('cli__default__werewolf_', '')})`;
+ const sBase = base + '/' + s.session;
+ m.set(sBase + '/game.md', { title: `智能体 / ${pId} / GAME.md${suffix}`, content: s.game || '' });
+ m.set(sBase + '/memory.md', { title: `智能体 / ${pId} / MEMORY.md${suffix}`, content: s.memory || '' });
+ m.set(sBase + '/history.md', { title: `智能体 / ${pId} / HISTORY.md${suffix}`, content: s.history || '' });
+ });
+ } else {
+ m.set(base + '/game.md', { title: '智能体 / ' + pId + ' / GAME.md', content: p.game || '' });
+ m.set(base + '/memory.md', { title: '智能体 / ' + pId + ' / MEMORY.md', content: p.memory || '' });
+ m.set(base + '/history.md', { title: '智能体 / ' + pId + ' / HISTORY.md', content: p.history || '' });
+ }
+ });
+ return m;
+ }
+
+ function applySelection(data) {
+ if (!data) return;
+ const lookup = buildMemoryLookup(data);
+ const item = lookup.get(uiState.selectedKey);
+ if (!item) uiState.selectedKey = 'world/GAME_RECORD.md';
+ const resolved = lookup.get(uiState.selectedKey);
+ if (resolved) setViewer(resolved.title, resolved.content);
+ }
+
+ function selectKey(key) {
+ uiState.selectedKey = key;
+ renderMemoryTree(uiState.lastData);
+ applySelection(uiState.lastData);
+ }
+
+ function renderMemoryTree(data) {
+ const root = document.getElementById('memTree');
+ if (!root || !data) return;
+ const lookup = buildMemoryLookup(data);
+ const players = data.players || [];
+ document.getElementById('memTreeCount').textContent = lookup.size + ' files';
+
+ function fileButton(key, label, meta) {
+ const active = uiState.selectedKey === key ? ' active' : '';
+ const metaHtml = meta ? '<span class="meta">' + escapeHtml(meta) + '</span>' : '<span class="meta"></span>';
+ return '<button class="fileBtn' + active + '" data-key="' + escapeHtml(key) + '"><span>' + escapeHtml(label) + '</span>' + metaHtml + '</button>';
+ }
+
+ let html = '';
+ html += '<details open><summary>世界记忆</summary><div class="node">';
+ if (data.history && data.history.records) {
+ data.history.records.forEach((r, idx) => {
+ const suffix = idx === 0 ? ' (Latest)' : ` (${r.session.replace('cli__default__werewolf_', '')})`;
+ html += fileButton(`world/GAME_RECORD_${r.session}.md`, `GAME_RECORD.md`, suffix.trim());
+ });
+ } else {
+ html += fileButton('world/GAME_RECORD.md', 'GAME_RECORD.md', 'GAME_RECORD');
+ }
+ html += '</div></details>';
+
+ html += '<details open><summary>OpenViking 记忆</summary><div class="node">';
+ html += '<details open><summary>User Memory</summary><div class="node">';
+ html += fileButton('openviking/User Memory/.overview.md', '.overview.md', 'User Memory');
+ html += fileButton('openviking/User Memory/.abstract.md', '.abstract.md', 'User Memory');
+ html += '</div></details>';
+ html += '<details><summary>entities</summary><div class="node">';
+ html += fileButton('openviking/entities/.overview.md', '.overview.md', 'entities');
+ html += '</div></details>';
+ html += '<details><summary>events</summary><div class="node">';
+ html += fileButton('openviking/events/.overview.md', '.overview.md', 'events');
+ html += '</div></details>';
+ html += '<details><summary>preferences</summary><div class="node">';
+ html += fileButton('openviking/preferences/.overview.md', '.overview.md', 'preferences');
+ html += '</div></details>';
+ html += '</div></details>';
+
+ html += '<details open><summary>智能体记忆</summary><div class="node">';
+ players.forEach((p, i) => {
+ const seat = i + 1;
+ const pId = p.id || ('player_' + seat);
+ const label = String(seat).padStart(2, '0') + '号 ' + (pId.replace('demo__werewolf__', '').replaceAll('_', ' '));
+ const base = 'agents/' + String(seat).padStart(2, '0') + '-' + pId;
+ html += '<details><summary>' + escapeHtml(label) + '</summary><div class="node">';
+
+ if (data.history && data.history.player_sessions && data.history.player_sessions[pId]) {
+ data.history.player_sessions[pId].forEach((s, idx) => {
+ const suffix = idx === 0 ? 'Latest' : s.session.replace('cli__default__werewolf_game_', '');
+ const sBase = base + '/' + s.session;
+ html += '<details><summary>' + escapeHtml(suffix) + '</summary><div class="node">';
+ html += fileButton(sBase + '/game.md', 'game.md', 'GAME.md');
+ html += fileButton(sBase + '/memory.md', 'memory.md', 'MEMORY.md');
+ html += fileButton(sBase + '/history.md', 'history.md', 'HISTORY.md');
+ html += '</div></details>';
+ });
+ } else {
+ html += fileButton(base + '/game.md', 'game.md', 'GAME.md');
+ html += fileButton(base + '/memory.md', 'memory.md', 'MEMORY.md');
+ html += fileButton(base + '/history.md', 'history.md', 'HISTORY.md');
+ }
+
+ html += '</div></details>';
+ });
+ html += '</div></details>';
+
+ root.innerHTML = html;
+ root.querySelectorAll('.fileBtn').forEach(btn => {
+ btn.addEventListener('click', () => selectKey(btn.getAttribute('data-key')));
+ });
+ }
+
+ function renderArena(players, info, data) {
+ const arena = document.getElementById('arena');
+ arena.innerHTML = '<div class="table"></div><div class="scanlines"></div>';
+ const indicator = document.createElement('div');
+ indicator.className = 'phaseIndicator';
+ indicator.innerHTML = `<span>${info.isNight ? '🌙' : '☀️'}</span><span>${info.isNight ? '黑夜' : '白天'}</span><span>${info.round ? '第' + info.round + '轮' : ''}</span>`;
+ arena.appendChild(indicator);
+ let latest = null;
+ players.forEach(p => {
+ if (!latest || (p.updated_at && p.updated_at > latest.updated_at)) latest = p;
+ });
+ const votes = extractVotes(players, info.round || 1);
+ let badgeCandidates = new Set();
+ if (info.day === 1 && !data.game_record.includes('警长当选') && data.game_record.includes('警长竞选:候选人')) {
+ badgeCandidates = extractBadgeCandidates(data.game_record);
+ }
+ const totalSeats = players.length;
+ const center = { x: 50, y: 50 };
+ const radius = { x: 38, y: 34 };
+
+ players.forEach((p, i) => {
+ const angle = (-90 + (360 / totalSeats) * i) * (Math.PI / 180);
+ const pos = {
+ x: center.x + radius.x * Math.cos(angle),
+ y: center.y + radius.y * Math.sin(angle),
+ };
+ const seatIdx = i;
+ const dead = info.dead.has(seatIdx);
+ const seat = document.createElement('div');
+ seat.className = 'seat' + (dead ? ' dead' : '');
+ seat.style.left = `calc(${pos.x}% - 59px)`;
+ seat.style.top = `calc(${pos.y}% - 22px)`;
+
+ const avatar = document.createElement('div');
+ avatar.className = 'avatar';
+ if (info.badge === seatIdx) {
+ const badge = document.createElement('div');
+ badge.className = 'badge';
+ badge.textContent = '★';
+ avatar.appendChild(badge);
+ }
+ if (badgeCandidates.has(seatIdx)) {
+ const cand = document.createElement('div');
+ cand.className = 'badgeCandidate';
+ cand.textContent = '警';
+ avatar.appendChild(cand);
+ }
+ const voteTarget = votes.get(seatIdx);
+ if (info.phase === 'vote' && voteTarget) {
+ const vote = document.createElement('div');
+ vote.className = 'voteBadge';
+ vote.textContent = voteTarget + '号';
+ avatar.appendChild(vote);
+ }
+ const sigil = document.createElement('div');
+ sigil.className = 'sigil';
+ sigil.innerHTML = sigilSvg(p.role);
+ avatar.appendChild(sigil);
+
+ const name = document.createElement('div');
+ name.className = 'name';
+ name.textContent = String(seatIdx + 1).padStart(2, '0') + ' ' + ((p.id || '').replace('demo__werewolf__', '').replaceAll('_', ' ') || ('player_' + String(seatIdx + 1).padStart(2, '0')));
+ const sub = document.createElement('div');
+ sub.className = 'sub';
+ sub.textContent = (p.role || '未知');
+ seat.appendChild(avatar);
+ seat.appendChild(name);
+ seat.appendChild(sub);
+
+ seat.addEventListener('click', () => {
+ openDrawer(p, seatIdx);
+ });
+
+ if (latest && latest.id === p.id && p.last_speech) {
+ seat.className += ' speaking';
+ const wave = document.createElement('div');
+ wave.className = 'speaker-wave';
+ wave.innerHTML = '<div class="bar"></div><div class="bar"></div><div class="bar"></div>';
+ seat.appendChild(wave);
+ }
+
+ // Add compact speech bubble
+ const speechText = String(p.last_speech || '');
+ if (speechText && speechText.trim()) {
+ const bubble = document.createElement('div');
+ bubble.style.cssText = `
+ position: absolute;
+ background: rgba(37, 99, 235, 0.95);
+ color: white;
+ padding: 6px 10px;
+ border-radius: 10px;
+ font-size: 11px;
+ line-height: 1.3;
+ box-shadow: 0 3px 10px rgba(0,0,0,0.25);
+ z-index: 200;
+ pointer-events: auto;
+ top: -55px;
+ left: 50%;
+ transform: translateX(-50%);
+ white-space: nowrap;
+ overflow: hidden;
+ text-overflow: ellipsis;
+ max-width: 180px;
+ `;
+
+ // Show first 50 chars max
+ let displayText = speechText;
+ if (displayText.length > 50) {
+ displayText = displayText.substring(0, 47) + '...';
+ }
+ bubble.textContent = displayText;
+
+ // Add small tail
+ const tail = document.createElement('div');
+ tail.style.cssText = `
+ position: absolute;
+ width: 0;
+ height: 0;
+ border-left: 6px solid transparent;
+ border-right: 6px solid transparent;
+ border-top: 8px solid rgba(37, 99, 235, 0.95);
+ bottom: -6px;
+ left: 50%;
+ transform: translateX(-50%);
+ `;
+ bubble.appendChild(tail);
+
+ seat.appendChild(bubble);
+ }
+
+ arena.appendChild(seat);
+ });
+ }
+
+ const speechTimers = new WeakMap();
+ function typeSpeech(el, text) {
+ const full = String(text || '');
+ if (!full) return;
+ if (speechTimers.has(el)) {
+ clearInterval(speechTimers.get(el));
+ }
+ el.textContent = '';
+ const cursor = document.createElement('span');
+ cursor.className = 'cursor';
+ el.appendChild(cursor);
+ let i = 0;
+ const timer = setInterval(() => {
+ if (i >= full.length) {
+ clearInterval(timer);
+ el.textContent = full;
+ return;
+ }
+ el.textContent = full.slice(0, i + 1);
+ el.appendChild(cursor);
+ i += 1;
+ }, 90);
+ speechTimers.set(el, timer);
+ }
+
+ function renderRoster(players, info) {
+ const grid = document.getElementById('roster');
+ grid.innerHTML = '';
+ players.forEach((p, i) => {
+ const seatIdx = i;
+ const dead = info.dead.has(seatIdx);
+ const role = roleInfo(p.role);
+ const card = document.createElement('div');
+ card.className = 'roleCard' + (dead ? ' dead' : '');
+
+ const top = document.createElement('div');
+ top.className = 'roleCardTop';
+ const sigil = document.createElement('div');
+ sigil.className = 'sigil';
+ sigil.innerHTML = sigilSvg(p.role);
+ const title = document.createElement('div');
+ title.className = 'roleCardTitle';
+ const n1 = document.createElement('div');
+ n1.className = 'roleName';
+ n1.textContent = role.label;
+ const n2 = document.createElement('div');
+ n2.className = 'roleMeta';
+ n2.textContent = String(seatIdx + 1).padStart(2, '0') + '号 · ' + ((p.id || '').replace('demo__werewolf__', '').replaceAll('_', ' ') || ('player_' + String(seatIdx + 1).padStart(2, '0')));
+ title.appendChild(n1);
+ title.appendChild(n2);
+ top.appendChild(sigil);
+ top.appendChild(title);
+
+ const bottom = document.createElement('div');
+ bottom.className = 'roleCardBottom';
+ const tag = document.createElement('div');
+ tag.className = 'tag ' + role.kind;
+ tag.textContent = role.kind === 'bad' ? 'WOLF' : (role.kind === 'special' ? 'SPECIAL' : 'VILLAGE');
+ const state = document.createElement('div');
+ state.textContent = dead ? 'DEAD' : 'ALIVE';
+ bottom.appendChild(tag);
+ bottom.appendChild(state);
+
+ card.appendChild(top);
+ card.appendChild(bottom);
+ card.addEventListener('click', () => {
+ const base = 'agents/' + String(seatIdx + 1).padStart(2, '0') + '-' + (p.id || ('player_' + (seatIdx + 1)));
+ selectKey(base + '/game.md');
+ });
+ grid.appendChild(card);
+ });
+ }
+
+ function setHeaderState(info, players) {
+ const dot = document.getElementById('phaseDot');
+ const phase = document.getElementById('phaseText');
+ const aliveCount = document.getElementById('aliveText');
+ dot.className = 'dot' + (info.isNight ? ' night' : '');
+ phase.textContent = (info.isNight ? 'NIGHT' : 'DAY') + (info.round ? ' · ' + info.round : '');
+ const dead = info.dead.size;
+ const alive = Math.max(0, (players || []).length - dead);
+ aliveCount.textContent = alive + '/' + (players || []).length + ' alive';
+ const chatPhaseIcon = document.getElementById('chatPhaseIcon');
+ const chatPhaseText = document.getElementById('chatPhaseText');
+ const chatRoundText = document.getElementById('chatRoundText');
+ const chatAliveText = document.getElementById('chatAliveText');
+ if (chatPhaseIcon) chatPhaseIcon.textContent = info.isNight ? '🌙' : '☀️';
+ if (chatPhaseText) chatPhaseText.textContent = info.isNight ? '黑夜' : '白天';
+ if (chatRoundText) chatRoundText.textContent = info.round ? `第${info.round}轮` : '';
+ if (chatAliveText) chatAliveText.textContent = `${alive}/${(players || []).length} alive`;
+ }
+
+ function updateEndOverlay(info) {
+ const overlay = document.getElementById('endOverlay');
+ const winner = document.getElementById('endWinner');
+ const status = document.getElementById('endStatus');
+ if (info.winner) {
+ overlay.classList.add('show');
+ winner.textContent = '胜利方:' + info.winner;
+ } else {
+ overlay.classList.remove('show');
+ status.textContent = '';
+ }
+ }
+
+ function setFsState() {
+ const t = document.getElementById('fsText');
+ if (uiState.httpBase) {
+ t.textContent = 'http: ' + uiState.httpBase;
+ return;
+ }
+ const ws = uiState.workspaceHandle ? 'workspace: ok' : 'workspace: -';
+ const st = uiState.storageHandle ? 'storage: ok' : 'storage: -';
+ t.textContent = ws + ' · ' + st;
+ }
+
+ function bindViewerButtons() {
+ // 废弃的模式切换,现已全局启用格式化
+ }
+
+ async function refreshFromFS() {
+ if (uiState.loading) return;
+ uiState.loading = true;
+ try {
+ const data = await loadDataFromFS(uiState.workspaceHandle, uiState.storageHandle);
+ uiState.lastData = data;
+ const info = parseRecordInfo(data.game_record || '');
+ setHeaderState(info, data.players || []);
+ renderArena(data.players || [], info, data);
+ setFsState();
+ updateEndOverlay(info);
+ renderChat(data, info);
+
+ // 加载OpenViking树
+ await loadOpenvikingTree();
+
+ renderMemoryPage(data);
+ renderRank(data, info);
+ } finally {
+ uiState.loading = false;
+ }
+ }
+
+ async function loadOpenvikingTree() {
+ try {
+ const res = await fetch('/api/openviking/tree', { cache: 'no-store' });
+ if (res.ok) {
+ uiState.openvikingTree = await res.json();
+ }
+ } catch (e) {
+ console.error('Failed to load OpenViking tree:', e);
+ }
+ // 同时加载对话列表
+ try {
+ const res = await fetch('/api/conversations', { cache: 'no-store' });
+ if (res.ok) {
+ uiState.conversations = await res.json();
+ }
+ } catch (e) {
+ console.error('Failed to load conversations:', e);
+ }
+ // 同时加载bot sessions列表
+ try {
+ const res = await fetch('/api/bot-sessions', { cache: 'no-store' });
+ if (res.ok) {
+ uiState.botSessions = await res.json();
+ }
+ } catch (e) {
+ console.error('Failed to load bot sessions:', e);
+ }
+ return !!uiState.openvikingTree;
+ }
+
+ async function loadConversation(sessionId) {
+ try {
+ const res = await fetch('/api/conversation/' + encodeURIComponent(sessionId), { cache: 'no-store' });
+ if (res.ok) {
+ return await res.json();
+ }
+ } catch (e) {
+ console.error('Failed to load conversation:', e);
+ }
+ return null;
+ }
+
+ async function loadBotSession(filename) {
+ try {
+ const res = await fetch('/api/bot-session/' + encodeURIComponent(filename), { cache: 'no-store' });
+ if (res.ok) {
+ return await res.json();
+ }
+ } catch (e) {
+ console.error('Failed to load bot session:', e);
+ }
+ return null;
+ }
+
+ async function loadGameFile(channelId, filename) {
+ try {
+ const res = await fetch('/api/game-file/' + encodeURIComponent(channelId) + '/' + encodeURIComponent(filename), { cache: 'no-store' });
+ if (res.ok) {
+ return await res.json();
+ }
+ } catch (e) {
+ console.error('Failed to load game file:', e);
+ }
+ return null;
+ }
+
+ async function loadOpenvikingFile(path) {
+ try {
+ const res = await fetch('/api/openviking/file?path=' + encodeURIComponent(path), { cache: 'no-store' });
+ if (res.ok) {
+ return await res.json();
+ }
+ } catch (e) {
+ console.error('Failed to load OpenViking file:', e);
+ }
+ return null;
+ }
+
+ function renderOpenvikingTree() {
+ const root = document.getElementById('memTree');
+ if (!root || !uiState.openvikingTree) return;
+
+ // 保存当前details的打开状态
+ const currentDetails = root.querySelectorAll('details');
+ currentDetails.forEach((detail, index) => {
+ const summary = detail.querySelector('summary');
+ if (summary) {
+ const key = 'detail_' + index + '_' + summary.textContent.trim();
+ if (detail.open) {
+ uiState.expandedDetails.add(key);
+ } else {
+ uiState.expandedDetails.delete(key);
+ }
+ }
+ });
+
+ const tree = uiState.openvikingTree;
+ let fileCount = 0;
+
+ function countFiles(items) {
+ let count = 0;
+ for (const item of items) {
+ if (item.type === 'file') count++;
+ else if (item.children) count += countFiles(item.children);
+ }
+ return count;
+ }
+
+ fileCount += countFiles(tree.agent.files || []);
+ fileCount += countFiles(tree.user.files || []);
+ document.getElementById('memTreeCount').textContent = fileCount + ' files';
+
+ function fileButton(fullPath, label, meta) {
+ const active = uiState.selectedOpenvikingPath === fullPath ? ' active' : '';
+ const metaHtml = meta ? '<span class="meta">' + escapeHtml(meta) + '</span>' : '<span class="meta"></span>';
+ return '<button class="fileBtn' + active + '" data-ov-path="' + escapeHtml(fullPath) + '"><span>' + escapeHtml(label) + '</span>' + metaHtml + '</button>';
+ }
+
+ function renderItems(items, prefix) {
+ let html = '';
+ for (const item of items) {
+ if (item.type === 'directory') {
+ const detailsKey = 'detail_' + html.length + '_' + item.name;
+ const isOpen = uiState.expandedDetails.has(detailsKey) ? ' open' : '';
+ html += '<details' + isOpen + ' data-index="' + html.length + '"><summary>' + escapeHtml(item.name) + '</summary><div class="node">';
+ if (item.children) {
+ html += renderItems(item.children, prefix + '/' + item.name);
+ }
+ html += '</div></details>';
+ } else {
+ const fullPath = prefix + '/' + item.name;
+ html += fileButton(fullPath, item.name, item.size ? item.size + ' bytes' : '');
+ }
+ }
+ return html;
+ }
+
+ let html = '';
+
+ // 世界记忆 - 保持打开状态
+ const worldKey = 'detail_0_世界记忆';
+ const worldOpen = uiState.expandedDetails.size === 0 || uiState.expandedDetails.has(worldKey) ? ' open' : '';
+ html += '<details' + worldOpen + ' data-index="0"><summary>世界记忆</summary><div class="node">';
+
+ // 只显示当前对话记录
+ if (uiState.conversations && uiState.conversations.files) {
+ const currentSession = uiState.conversations.files.find(f => f.session_id === uiState.conversations.current_session_id);
+ if (currentSession) {
+ const label = 'CONVERSATION_' + currentSession.session_id + '.md';
+ html += fileButton('conversation/' + currentSession.session_id, label, '当前');
+ } else if (uiState.conversations.files.length > 0) {
+ // 如果没有找到当前session,显示最新的一个
+ const latest = uiState.conversations.files[0];
+ const label = 'CONVERSATION_' + latest.session_id + '.md';
+ html += fileButton('conversation/' + latest.session_id, label, '最新');
+ }
+ }
+ html += '</div></details>';
+
+ // OpenViking 记忆 - 保持打开状态
+ const ovKey = 'detail_1_OpenViking 记忆';
+ const ovOpen = uiState.expandedDetails.size === 0 || uiState.expandedDetails.has(ovKey) ? ' open' : '';
+ html += '<details' + ovOpen + ' data-index="1"><summary>OpenViking 记忆</summary><div class="node">';
+
+ // agent目录 - 保持打开状态
+ const agentKey = 'detail_2_agent';
+ const agentOpen = uiState.expandedDetails.size === 0 || uiState.expandedDetails.has(agentKey) ? ' open' : '';
+ html += '<details' + agentOpen + ' data-index="2"><summary>agent</summary><div class="node">';
+ if (tree.agent && tree.agent.files) {
+ html += renderItems(tree.agent.files, 'agent');
+ }
+ html += '</div></details>';
+
+ // user目录 - 保持打开状态
+ const userKey = 'detail_3_user';
+ const userOpen = uiState.expandedDetails.size === 0 || uiState.expandedDetails.has(userKey) ? ' open' : '';
+ html += '<details' + userOpen + ' data-index="3"><summary>user</summary><div class="node">';
+ if (tree.user && tree.user.files) {
+ html += renderItems(tree.user.files, 'user');
+ }
+ html += '</div></details>';
+
+ html += '</div></details>';
+
+ // 智能体记忆 - 保持打开状态
+ const playerKey = 'detail_4_智能体记忆';
+ const playerOpen = uiState.expandedDetails.size === 0 || uiState.expandedDetails.has(playerKey) ? ' open' : '';
+ html += '<details' + playerOpen + ' data-index="4"><summary>智能体记忆</summary><div class="node">';
+
+ // 获取玩家列表来确定座位号
+ const players = uiState.lastData ? (uiState.lastData.players || []) : [];
+ const playerIdToSeat = {};
+ players.forEach((p, i) => {
+ playerIdToSeat[p.id] = i + 1;
+ });
+
+ // 先显示god
+ if (uiState.botSessions && uiState.botSessions.files) {
+ const godSessions = uiState.botSessions.files.filter(f => f.channel_id === 'god');
+ if (godSessions.length > 0) {
+ const godKey = 'detail_5_god';
+ const godOpen = uiState.expandedDetails.has(godKey) ? ' open' : '';
+ html += '<details' + godOpen + ' data-index="5"><summary>god</summary><div class="node">';
+
+ // 显示当前session文件
+ const currentGodSession = godSessions.find(s =>
+ uiState.botSessions.current_session_id && s.session_id.includes(uiState.botSessions.current_session_id)
+ ) || godSessions[0];
+ html += fileButton('botsession/' + currentGodSession.filename, currentGodSession.filename, '当前会话');
+
+ // 显示GAME_RECORD.md
+ html += fileButton('gamefile/god/GAME_RECORD.md', 'GAME_RECORD.md', '游戏记录');
+
+ html += '</div></details>';
+ }
+ }
+
+ // 显示玩家
+ players.forEach((p, i) => {
+ const seat = i + 1;
+ const pId = p.id;
+ const label = String(seat).padStart(2, '0') + '号 ' + pId;
+ const playerDetailKey = 'detail_' + (6 + i) + '_' + label;
+ const playerDetailOpen = uiState.expandedDetails.has(playerDetailKey) ? ' open' : '';
+
+ html += '<details' + playerDetailOpen + ' data-index="' + (6 + i) + '"><summary>' + escapeHtml(label) + '</summary><div class="node">';
+
+ if (uiState.botSessions && uiState.botSessions.files) {
+ const playerSessions = uiState.botSessions.files.filter(f => f.channel_id === pId);
+ if (playerSessions.length > 0) {
+ // 显示当前session文件
+ const currentSession = playerSessions.find(s =>
+ uiState.botSessions.current_session_id && s.session_id.includes(uiState.botSessions.current_session_id)
+ ) || playerSessions[0];
+ html += fileButton('botsession/' + currentSession.filename, currentSession.filename, '当前会话');
+ }
+ }
+
+ // 显示GAME.md
+ html += fileButton('gamefile/' + pId + '/GAME.md', 'GAME.md', '玩家文件');
+
+ html += '</div></details>';
+ });
+
+ html += '</div></details>';
+
+ root.innerHTML = html;
+
+ // 监听所有details的toggle事件,更新状态
+ root.querySelectorAll('details').forEach((detail, index) => {
+ const summary = detail.querySelector('summary');
+ if (summary) {
+ const key = 'detail_' + (detail.getAttribute('data-index') || index) + '_' + summary.textContent.trim();
+ detail.addEventListener('toggle', () => {
+ if (detail.open) {
+ uiState.expandedDetails.add(key);
+ } else {
+ uiState.expandedDetails.delete(key);
+ }
+ });
+ }
+ });
+
+ root.querySelectorAll('.fileBtn[data-ov-path]').forEach(btn => {
+ btn.addEventListener('click', async (e) => {
+ e.stopPropagation();
+ const path = btn.getAttribute('data-ov-path');
+ await selectOpenvikingPath(path);
+ });
+ });
+
+ root.querySelectorAll('.fileBtn:not([data-ov-path])').forEach(btn => {
+ btn.addEventListener('click', (e) => {
+ e.stopPropagation();
+ selectKey(btn.getAttribute('data-key'));
+ });
+ });
+ }
+
+ async function selectOpenvikingPath(path) {
+ uiState.selectedOpenvikingPath = path;
+ uiState.selectedKey = null;
+ renderOpenvikingTree();
+
+ // 检查是否是对话文件
+ if (path.startsWith('conversation/')) {
+ const sessionId = path.replace('conversation/', '');
+ const convData = await loadConversation(sessionId);
+ if (convData) {
+ setViewer('对话记录 / ' + convData.filename, convData.content);
+ }
+ } else if (path.startsWith('botsession/')) {
+ const filename = path.replace('botsession/', '');
+ const sessionData = await loadBotSession(filename);
+ if (sessionData) {
+ setViewer('智能体会话 / ' + sessionData.filename, sessionData.content);
+ }
+ } else if (path.startsWith('gamefile/')) {
+ const parts = path.replace('gamefile/', '').split('/');
+ const channelId = parts[0];
+ const filename = parts[1];
+ const gameData = await loadGameFile(channelId, filename);
+ if (gameData) {
+ const label = channelId === 'god' ? 'god' : channelId;
+ setViewer('智能体文件 / ' + label + ' / ' + gameData.filename, gameData.content);
+ }
+ } else {
+ const fileData = await loadOpenvikingFile(path);
+ if (fileData) {
+ setViewer('OpenViking / ' + fileData.path, fileData.content);
+ }
+ }
+ }
+
+ function switchPage(id) {
+ document.querySelectorAll('.page').forEach(p => {
+ p.style.display = 'none';
+ p.classList.remove('active');
+ });
+ const el = document.getElementById(id);
+ if (el) {
+ el.style.display = 'block';
+ el.classList.add('active');
+ }
+ document.querySelectorAll('.navBtn').forEach(b => b.classList.remove('active'));
+ if (id === 'page-game') document.getElementById('navGame').classList.add('active');
+ if (id === 'page-memory') document.getElementById('navMemory').classList.add('active');
+ if (id === 'page-rank') document.getElementById('navRank').classList.add('active');
+
+ if (id === 'page-memory') {
+ loadOpenvikingTree().then(() => {
+ renderOpenvikingTree();
+ });
+ }
+ }
+
+ function renderMemoryPage(data) {
+ // 如果OpenViking树已加载,使用新的渲染方式
+ if (uiState.openvikingTree) {
+ renderOpenvikingTree();
+ } else {
+ // 否则使用旧的渲染方式
+ renderMemoryTree(data);
+ }
+ }
+
+ function computeLeaderboard(data, info) {
+ const players = data.players || [];
+ const historyScores = {};
+ const historyWins = {};
+ const historyPlays = {};
+
+ // Calculate scores dynamically from all history records in the workspace
+ if (data.history && data.history.records) {
+ data.history.records.forEach(r => {
+ const rInfo = parseRecordInfo(r.text);
+ if (!rInfo.winner) return;
+
+ const rWinner = rInfo.winner || '';
+ const rIsWolfWin = rWinner.includes('狼人');
+ const rDead = rInfo.dead || new Set();
+
+ players.forEach((p, i) => {
+ const pid = p.id || `player_${i+1}`;
+
+ // Try to find this player's role in this specific game session
+ let rRole = '未知';
+ if (data.history.player_sessions && data.history.player_sessions[pid]) {
+ const pSession = data.history.player_sessions[pid].find(s => s.session === r.session);
+ if (pSession) rRole = extractRole(pSession.game);
+ }
+ if (rRole === '未知') rRole = String(p.role || ''); // fallback
+
+ const rIsWolf = rRole === 'Werewolf' || rRole === 'WhiteWolfKing' || rRole === 'WolfCub' || rRole === 'WolfBeauty';
+
+ let score = 0;
+ if ((rIsWolfWin && rIsWolf) || (!rIsWolfWin && !rIsWolf)) {
+ score += 3;
+ historyWins[pid] = (historyWins[pid] || 0) + 1;
+ }
+ if (!rDead.has(i)) {
+ score += 1;
+ } else {
+ score -= 1;
+ }
+
+ historyScores[pid] = (historyScores[pid] || 0) + score;
+ historyPlays[pid] = (historyPlays[pid] || 0) + 1;
+ });
+ });
+ }
+
+ const results = players.map((p, i) => {
+ const role = String(p.role || '');
+ const isWolf = role === 'Werewolf' || role === 'WhiteWolfKing' || role === 'WolfCub' || role === 'WolfBeauty';
+
+ let currentScore = 0;
+ let winStatus = '进行中';
+
+ // Calculate current game score
+ const winner = info.winner || '';
+ const isWolfWin = winner.includes('狼人');
+ const dead = info.dead || new Set();
+
+ if (winner) {
+ if ((isWolfWin && isWolf) || (!isWolfWin && !isWolf)) {
+ currentScore += 3;
+ winStatus = '胜利';
+ } else {
+ winStatus = '失败';
+ }
+ if (!dead.has(i)) {
+ currentScore += 1;
+ } else {
+ currentScore -= 1;
+ }
+ }
+
+ const pid = p.id || `player_${i+1}`;
+ const totalScore = (historyScores[pid] || 0);
+ const wins = (historyWins[pid] || 0);
+ const plays = (historyPlays[pid] || 0);
+
+ return {
+ seat: i + 1,
+ id: pid,
+ role,
+ currentScore: winner ? currentScore : 0,
+ totalScore: totalScore,
+ wins: wins,
+ plays: plays,
+ winRate: plays > 0 ? Math.round((wins / plays) * 100) : 0,
+ winStatus
+ };
+ });
+
+ return results.sort((a, b) => b.totalScore - a.totalScore);
+ }
+
+ function renderRank(data, info) {
+ const list = document.getElementById('rankList');
+ list.innerHTML = '';
+ const rows = computeLeaderboard(data, info);
+
+ rows.forEach((r, idx) => {
+ const item = document.createElement('div');
+ item.className = 'rankItem';
+ const left = document.createElement('div');
+ left.textContent = `${idx === 0 ? '🏆 ' : ''}${idx + 1}. ${String(r.seat).padStart(2, '0')}号 ${String(r.id || '').replace('player_', '')} [${roleInfo(r.role).label}]`;
+ const right = document.createElement('div');
+ right.innerHTML = `<span style="color: rgba(154,164,178,0.8); margin-right: 8px;">胜率: ${r.winRate}% (${r.wins}/${r.plays})</span> <span style="color: rgba(154,164,178,0.8); margin-right: 8px;">本局: ${r.currentScore > 0 ? '+'+r.currentScore : r.currentScore}</span> <strong style="color: #6ee7b7;">总分: ${r.totalScore}</strong>`;
+ item.appendChild(left);
+ item.appendChild(right);
+ list.appendChild(item);
+ });
+ renderRelation();
+ }
+
+ function renderRelation() {
+ var root = document.getElementById('relationGraph');
+ root.innerHTML = '';
+ var svg = document.createElementNS('http://www.w3.org/2000/svg', 'svg');
+ svg.setAttribute('width', '100%');
+ svg.setAttribute('height', '100%');
+ svg.setAttribute('viewBox', '0 0 420 420');
+ svg.style.display = 'block';
+
+ var defs = document.createElementNS('http://www.w3.org/2000/svg', 'defs');
+
+ var filter = document.createElementNS('http://www.w3.org/2000/svg', 'filter');
+ filter.setAttribute('id', 'glow');
+ var feGaussianBlur = document.createElementNS('http://www.w3.org/2000/svg', 'feGaussianBlur');
+ feGaussianBlur.setAttribute('stdDeviation', '3');
+ feGaussianBlur.setAttribute('result', 'coloredBlur');
+ var feMerge = document.createElementNS('http://www.w3.org/2000/svg', 'feMerge');
+ var feMergeNode1 = document.createElementNS('http://www.w3.org/2000/svg', 'feMergeNode');
+ feMergeNode1.setAttribute('in', 'coloredBlur');
+ var feMergeNode2 = document.createElementNS('http://www.w3.org/2000/svg', 'feMergeNode');
+ feMergeNode2.setAttribute('in', 'SourceGraphic');
+ feMerge.appendChild(feMergeNode1);
+ feMerge.appendChild(feMergeNode2);
+ filter.appendChild(feGaussianBlur);
+ filter.appendChild(feMerge);
+ defs.appendChild(filter);
+
+ var marker = document.createElementNS('http://www.w3.org/2000/svg', 'marker');
+ marker.setAttribute('id', 'arrow');
+ marker.setAttribute('markerWidth', '5');
+ marker.setAttribute('markerHeight', '4');
+ marker.setAttribute('refX', '4');
+ marker.setAttribute('refY', '2');
+ marker.setAttribute('orient', 'auto');
+ var arrowPath = document.createElementNS('http://www.w3.org/2000/svg', 'path');
+ arrowPath.setAttribute('d', 'M 0 0 L 0 4 L 4 2 Z');
+ arrowPath.setAttribute('fill', '#38bdf8');
+ marker.appendChild(arrowPath);
+ defs.appendChild(marker);
+
+ var markerPurple = document.createElementNS('http://www.w3.org/2000/svg', 'marker');
+ markerPurple.setAttribute('id', 'arrowPurple');
+ markerPurple.setAttribute('markerWidth', '5');
+ markerPurple.setAttribute('markerHeight', '4');
+ markerPurple.setAttribute('refX', '4');
+ markerPurple.setAttribute('refY', '2');
+ markerPurple.setAttribute('orient', 'auto');
+ var arrowPathPurple = document.createElementNS('http://www.w3.org/2000/svg', 'path');
+ arrowPathPurple.setAttribute('d', 'M 0 0 L 0 4 L 4 2 Z');
+ arrowPathPurple.setAttribute('fill', '#a78bfa');
+ markerPurple.appendChild(arrowPathPurple);
+ defs.appendChild(markerPurple);
+
+ svg.appendChild(defs);
+
+ var bg = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
+ bg.setAttribute('x', '0');
+ bg.setAttribute('y', '0');
+ bg.setAttribute('width', '420');
+ bg.setAttribute('height', '420');
+ bg.setAttribute('fill', '#070913');
+ svg.appendChild(bg);
+
+ var border = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
+ border.setAttribute('x', '4');
+ border.setAttribute('y', '4');
+ border.setAttribute('width', '412');
+ border.setAttribute('height', '412');
+ border.setAttribute('fill', 'none');
+ border.setAttribute('stroke', '#2b3350');
+ border.setAttribute('stroke-width', '2');
+ svg.appendChild(border);
+
+ function addNode(x, y, label, icon, color, isBig) {
+ var w = isBig ? 78 : 50;
+ var h = isBig ? 56 : 38;
+ var nx = x - w/2;
+ var ny = y - h/2;
+
+ var glow = document.createElementNS('http://www.w3.org/2000/svg', 'circle');
+ glow.setAttribute('cx', String(x));
+ glow.setAttribute('cy', String(y));
+ glow.setAttribute('r', isBig ? '42' : '30');
+ glow.setAttribute('fill', 'none');
+ glow.setAttribute('stroke', color);
+ glow.setAttribute('stroke-width', '1');
+ glow.setAttribute('opacity', '0.25');
+ svg.appendChild(glow);
+
+ var anim = document.createElementNS('http://www.w3.org/2000/svg', 'animate');
+ anim.setAttribute('attributeName', 'opacity');
+ anim.setAttribute('values', '0.15;0.35;0.15');
+ anim.setAttribute('dur', '2s');
+ anim.setAttribute('repeatCount', 'indefinite');
+ glow.appendChild(anim);
+
+ var outer = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
+ outer.setAttribute('x', String(nx - 2));
+ outer.setAttribute('y', String(ny - 2));
+ outer.setAttribute('width', String(w + 4));
+ outer.setAttribute('height', String(h + 4));
+ outer.setAttribute('fill', color);
+ outer.setAttribute('opacity', '0.2');
+ svg.appendChild(outer);
+
+ var inner = document.createElementNS('http://www.w3.org/2000/svg', 'rect');
+ inner.setAttribute('x', String(nx));
+ inner.setAttribute('y', String(ny));
+ inner.setAttribute('width', String(w));
+ inner.setAttribute('height', String(h));
+ inner.setAttribute('fill', '#0b0f1c');
+ inner.setAttribute('stroke', color);
+ inner.setAttribute('stroke-width', '2');
+ inner.setAttribute('rx', '6');
+ inner.setAttribute('filter', 'url(#glow)');
+ svg.appendChild(inner);
+
+ var iconText = document.createElementNS('http://www.w3.org/2000/svg', 'text');
+ iconText.setAttribute('x', String(x));
+ var iconY = isBig ? 8 : 5;
+ iconText.setAttribute('y', String(y - iconY));
+ iconText.setAttribute('text-anchor', 'middle');
+ iconText.setAttribute('fill', color);
+ var iconSize = isBig ? '18' : '14';
+ iconText.setAttribute('font-size', iconSize);
+ iconText.setAttribute('font-family', 'monospace');
+ iconText.textContent = icon;
+ svg.appendChild(iconText);
+
+ var labelText = document.createElementNS('http://www.w3.org/2000/svg', 'text');
+ labelText.setAttribute('x', String(x));
+ var labelY = isBig ? 18 : 14;
+ labelText.setAttribute('y', String(y + labelY));
+ labelText.setAttribute('text-anchor', 'middle');
+ labelText.setAttribute('fill', color);
+ var labelSize = isBig ? '11' : '10';
+ labelText.setAttribute('font-size', labelSize);
+ labelText.setAttribute('font-family', 'monospace');
+ labelText.textContent = label;
+ svg.appendChild(labelText);
+
+ if (isBig) {
+ var subText = document.createElementNS('http://www.w3.org/2000/svg', 'text');
+ subText.setAttribute('x', String(x));
+ subText.setAttribute('y', String(y + 34));
+ subText.setAttribute('text-anchor', 'middle');
+ subText.setAttribute('fill', 'rgba(167,139,250,0.65)');
+ subText.setAttribute('font-size', '8');
+ subText.setAttribute('font-family', 'monospace');
+ subText.textContent = 'MEMORY';
+ svg.appendChild(subText);
+ }
+ }
+
+ function addLine(x1, y1, x2, y2, color, usePurpleArrow) {
+ var line = document.createElementNS('http://www.w3.org/2000/svg', 'line');
+ line.setAttribute('x1', String(x1));
+ line.setAttribute('y1', String(y1));
+ line.setAttribute('x2', String(x2));
+ line.setAttribute('y2', String(y2));
+ line.setAttribute('stroke', color);
+ line.setAttribute('stroke-width', '1.5');
+ var markerId = usePurpleArrow ? 'arrowPurple' : 'arrow';
+ line.setAttribute('marker-end', 'url(#' + markerId + ')');
+ svg.appendChild(line);
+ }
+
+ function addLabel(x, y, text, color) {
+ var t = document.createElementNS('http://www.w3.org/2000/svg', 'text');
+ t.setAttribute('x', String(x));
+ t.setAttribute('y', String(y));
+ t.setAttribute('text-anchor', 'middle');
+ t.setAttribute('fill', color);
+ t.setAttribute('font-size', '8');
+ t.setAttribute('font-family', 'monospace');
+ t.textContent = text;
+ svg.appendChild(t);
+ }
+
+ addLine(105, 75, 105, 105, '#6ee7b7', false);
+ addLine(105, 152, 105, 188, '#38bdf8', false);
+ addLine(100, 188, 100, 152, '#38bdf8', false);
+ addLine(92, 228, 70, 278, '#38bdf8', false);
+ addLine(118, 228, 140, 278, '#38bdf8', false);
+ addLine(70, 282, 92, 232, '#f87171', false);
+ addLine(140, 282, 118, 232, '#f87171', false);
+
+ addLine(125, 208, 265, 190, '#a78bfa', true);
+ addLine(265, 200, 125, 218, '#a78bfa', true);
+ addLabel(195, 199, 'R/W', '#a78bfa');
+
+ addLine(80, 300, 265, 215, '#a78bfa', true);
+ addLine(265, 225, 80, 310, '#a78bfa', true);
+ addLabel(175, 252, 'R/W', '#a78bfa');
+
+ addLine(130, 300, 265, 235, '#a78bfa', true);
+ addLine(265, 245, 130, 310, '#a78bfa', true);
+ addLabel(197, 267, 'R/W', '#a78bfa');
+
+ addNode(105, 48, 'ADMIN', '◆', '#6ee7b7', false);
+ addNode(105, 130, 'SERVER', '◇', '#38bdf8', false);
+ addNode(105, 210, 'GOD', '★', '#fbbf24', false);
+ addNode(60, 300, 'P1', '●', '#f87171', false);
+ addNode(150, 300, 'P2', '●', '#f87171', false);
+ addNode(300, 205, 'OpenViking', '◈', '#a78bfa', true);
+
+ root.appendChild(svg);
+}
+function bindNav() {
+ document.getElementById('navGame').addEventListener('click', () => switchPage('page-game'));
+ document.getElementById('navMemory').addEventListener('click', () => switchPage('page-memory'));
+ document.getElementById('navRank').addEventListener('click', () => {
+ switchPage('page-rank');
+ // Load history leaderboard when switching to rank page
+ loadHistoryLeaderboard();
+ });
+
+ // Rank tab buttons
+ const tabCurrent = document.getElementById('rankTabCurrent');
+ const tabHistory = document.getElementById('rankTabHistory');
+ const listCurrent = document.getElementById('rankList');
+ const listHistory = document.getElementById('rankListHistory');
+
+ if (tabCurrent && tabHistory) {
+ tabCurrent.classList.add('active');
+ tabCurrent.addEventListener('click', () => {
+ tabCurrent.classList.add('active');
+ tabHistory.classList.remove('active');
+ if (listCurrent) listCurrent.style.display = '';
+ if (listHistory) listHistory.style.display = 'none';
+ });
+
+ tabHistory.addEventListener('click', () => {
+ tabHistory.classList.add('active');
+ tabCurrent.classList.remove('active');
+ if (listCurrent) listCurrent.style.display = 'none';
+ if (listHistory) listHistory.style.display = '';
+ loadHistoryLeaderboard();
+ });
+ }
+
+ // Human player buttons
+ const humanSendBtn = document.getElementById('humanSendBtn');
+ if (humanSendBtn) {
+ humanSendBtn.addEventListener('click', sendHumanMessage);
+ }
+ const humanInput = document.getElementById('humanInput');
+ if (humanInput) {
+ humanInput.addEventListener('keydown', (e) => {
+ if (e.key === 'Enter' && !e.shiftKey) {
+ e.preventDefault();
+ sendHumanMessage();
+ }
+ });
+ }
+ const humanEditGameMd = document.getElementById('humanEditGameMd');
+ if (humanEditGameMd) {
+ humanEditGameMd.addEventListener('click', editHumanGameMd);
+ }
+
+ // Load human GAME.md on init
+ loadHumanGameMd();
+ }
+
+ async function loadHistoryLeaderboard() {
+ const listHistory = document.getElementById('rankListHistory');
+ if (!listHistory) return;
+
+ try {
+ const res = await fetch('/api/leaderboard', { cache: 'no-store' });
+ if (!res.ok) return;
+
+ const leaderboard = await res.json();
+ const players = leaderboard.players || {};
+
+ const playerList = Object.values(players).sort((a, b) => b.total_score - a.total_score);
+
+ listHistory.innerHTML = '';
+ playerList.forEach((p, idx) => {
+ const item = document.createElement('div');
+ item.className = 'rankItem';
+
+ const winRate = p.games_played > 0 ? Math.round((p.games_won / p.games_played) * 100) : 0;
+ const roles = Object.entries(p.roles || {}).map(([role, count]) => `${role}(${count})`).join(', ');
+
+ const left = document.createElement('div');
+ left.textContent = `${idx === 0 ? '🏆 ' : ''}${idx + 1}. ${String(p.id || '').replace('player_', '')}`;
+
+ const right = document.createElement('div');
+ right.innerHTML = `<span style="color: rgba(154,164,178,0.8); margin-right: 8px;">胜率: ${winRate}% (${p.games_won}/${p.games_played})</span> <strong style="color: #6ee7b7;">总分: ${p.total_score}</strong>`;
+
+ if (roles) {
+ const rolesDiv = document.createElement('div');
+ rolesDiv.style.cssText = 'font-size: 11px; color: rgba(154,164,178,0.7); margin-top: 4px;';
+ rolesDiv.textContent = `角色: ${roles}`;
+ right.appendChild(rolesDiv);
+ }
+
+ item.appendChild(left);
+ item.appendChild(right);
+ listHistory.appendChild(item);
+ });
+ } catch (e) {
+ console.error('Failed to load history leaderboard:', e);
+ }
+ }
+
+ // Search is handled by the first bindSearch implementation
+
+ async function fetchDirEntries(baseUrl, relPath) {
+ const url = baseUrl.replace(/\/$/, '') + '/' + relPath.replace(/^\/+/, '') + '/';
+ const res = await fetch(url, { cache: 'no-store' });
+ if (!res.ok) return [];
+ const html = await res.text();
+ const doc = new DOMParser().parseFromString(html, 'text/html');
+ const links = Array.from(doc.querySelectorAll('a')).map((a) => a.getAttribute('href') || '');
+ const names = links
+ .map((h) => h.replace(/\/$/, '').replace(/^\//, '')) // Remove both leading and trailing slashes
+ .filter((h) => h && h !== '..' && h !== '.' && !h.includes('?'));
+ console.log('fetchDirEntries result:', names);
+ return names;
+ }
+
+ async function fetchFileText(baseUrl, relPath) {
+ const url = baseUrl.replace(/\/$/, '') + '/' + relPath.replace(/^\/+/, '');
+ console.log('Fetching:', url);
+ const res = await fetch(url, { cache: 'no-store' });
+ console.log(' Status:', res.status, res.ok);
+ if (!res.ok) return { text: '', lastModified: 0 };
+ const text = await res.text();
+ const lm = res.headers.get('last-modified');
+ const lastModified = lm ? new Date(lm).getTime() : 0;
+ console.log(' Got text, length:', text.length);
+ return { text, lastModified };
+ }
+
+ async function findLatestSessionHttp(baseUrl, relPath) {
+ const entries = await fetchDirEntries(baseUrl, relPath);
+ if (!entries.length) return null;
+ entries.sort();
+ let best = null;
+ let bestTs = 0;
+ for (const name of entries) {
+ const game = await fetchFileText(baseUrl, relPath + '/' + name + '/GAME.md');
+ if (!game.text) continue;
+ if ((game.lastModified || 0) > bestTs) {
+ bestTs = game.lastModified || 0;
+ best = name;
+ }
+ }
+ return best || entries[0];
+ }
+
+ async function readLatestRecordHttp(baseUrl, relPath) {
+ const entries = await fetchDirEntries(baseUrl, relPath);
+ const records = entries.filter((n) => n.startsWith('GAME_RECORD_') && n.endsWith('.md'));
+ if (!records.length) return fetchFileText(baseUrl, relPath + '/GAME_RECORD.md');
+ const withTime = await Promise.all(
+ records.map(async (n) => {
+ const file = await fetchFileText(baseUrl, relPath + '/' + n);
+ return { name: n, lastModified: file.lastModified || 0, text: file.text || '' };
+ })
+ );
+ withTime.sort((a, b) => b.lastModified - a.lastModified);
+ return { text: withTime[0].text, lastModified: withTime[0].lastModified };
+ }
+
+ async function resolveWorldMemoryHttp(baseUrl) {
+ const candidates = [
+ 'viking/werewolf_demo/user/referee/memories',
+ 'viking/default/user/default/memories',
+ ];
+ for (const rel of candidates) {
+ const overview = await fetchFileText(baseUrl, rel + '/.overview.md');
+ if (!overview.text) continue;
+ const abstract = await fetchFileText(baseUrl, rel + '/.abstract.md');
+ const entities = await fetchFileText(baseUrl, rel + '/entities/.overview.md');
+ const events = await fetchFileText(baseUrl, rel + '/events/.overview.md');
+ const preferences = await fetchFileText(baseUrl, rel + '/preferences/.overview.md');
+ return {
+ overview: overview.text,
+ abstract: abstract.text,
+ entities: entities.text,
+ events: events.text,
+ preferences: preferences.text,
+ };
+ }
+ return { overview: '', abstract: '', entities: '', events: '', preferences: '' };
+ }
+
+ async function loadDataFromHttp(baseUrl) {
+ const out = { game_record: '', _record_lastModified: 0, _starting: false, world_memory: { overview: '', abstract: '', entities: '', events: '', preferences: '' }, players: [], history: { records: [], player_sessions: {} } };
+ const restartAt = parseInt(localStorage.getItem('ww_restart_at') || '0', 10) || 0;
+ const rootEntries = await fetchDirEntries(baseUrl, '');
+
+ // New format: werewolf/ and bot_api__*
+ // Note: werewolf/ may not appear in root listing but is served via server mapping
+ const hasWerewolf = rootEntries.includes('werewolf') || rootEntries.includes('bot_api__god');
+ const botApiDirs = rootEntries.filter((n) => n.startsWith('bot_api__'));
+
+ if (hasWerewolf) {
+ console.log('hasWerewolf is true, loading data...');
+ console.log('rootEntries:', rootEntries);
+ console.log('botApiDirs:', botApiDirs);
+
+ // Load game record from werewolf/ folder
+ const record = await fetchFileText(baseUrl, 'werewolf/GAME_RECORD.md');
+ console.log('GAME_RECORD.md fetched:', { textLength: record.text.length, lastModified: record.lastModified, textPreview: record.text.substring(0, 200) });
+
+ out._record_lastModified = record.lastModified || 0;
+ if (restartAt && out._record_lastModified && out._record_lastModified < restartAt) {
+ out._starting = true;
+ out.game_record = '';
+ } else {
+ out.game_record = record.text;
+ if (restartAt && out._record_lastModified && out._record_lastModified >= restartAt) {
+ localStorage.removeItem('ww_restart_at');
+ }
+ }
+
+ // Parse actual player list from GAME_RECORD.md
+ const actualPlayers = [];
+ // Support both formats:
+ // 1. Old format: "- 1号: player_1"
+ // 2. New table format: "| 1号 | player_1 | ... |"
+ const playerRe1 = /- (\d+)号\s+(player_\d+):/g;
+ const playerRe2 = /\|\s*(\d+)号\s*\|\s*(player_\d+)\s*\|/g;
+
+ let match;
+ while ((match = playerRe1.exec(out.game_record)) !== null) {
+ actualPlayers.push({ seat: parseInt(match[1], 10), id: match[2] });
+ }
+ // Reset regex and try table format
+ playerRe2.lastIndex = 0;
+ while ((match = playerRe2.exec(out.game_record)) !== null) {
+ const seat = parseInt(match[1], 10);
+ const id = match[2];
+ // Avoid duplicates
+ if (!actualPlayers.find(p => p.id === id)) {
+ actualPlayers.push({ seat, id });
+ }
+ }
+ console.log('Actual players from GAME_RECORD:', actualPlayers);
+
+ // If no players found in record, fall back to checking directories
+ const playersToLoad = actualPlayers.length > 0
+ ? actualPlayers.map(p => ({ id: p.id, botApiId: `bot_api__${p.id}` }))
+ : Array.from({ length: 8 }, (_, i) => ({ id: `player_${i + 1}`, botApiId: `bot_api__player_${i + 1}` }));
+
+ // Load players
+ for (const { id, botApiId } of playersToLoad) {
+ if (botApiDirs.includes(botApiId)) {
+ out.history.player_sessions[id] = [];
+
+ // Load GAME.md directly from bot_api__player_i/
+ const game = await fetchFileText(baseUrl, botApiId + '/GAME.md');
+ const memory = await fetchFileText(baseUrl, botApiId + '/memory/MEMORY.md');
+ const history = await fetchFileText(baseUrl, botApiId + '/memory/HISTORY.md');
+
+ const role = extractRole(game.text);
+ const info = out.game_record ? parseRecordInfo(out.game_record) : { phase: 'day' };
+ const lastSpeech = extractLastSpeech(game.text, info.phase);
+
+ out.players.push({
+ id,
+ game: game.text,
+ memory: memory.text,
+ history: history.text,
+ role,
+ last_speech: lastSpeech,
+ has_session: true,
+ updated_at: String(Math.max(game.lastModified || 0, memory.lastModified || 0, history.lastModified || 0)),
+ });
+ }
+ }
+ }
+
+ out.world_memory = await resolveWorldMemoryHttp(baseUrl);
+ return out;
+ }
+
+ async function bindPickers() {}
+
+ function bindGameControls() {
+ const btnStart = document.getElementById('btnStart');
+ const btnStop = document.getElementById('btnStop');
+ const btnRestart = document.getElementById('btnRestart');
+ const forceBtn = document.getElementById('navForceRestart');
+ const status = document.getElementById('endStatus');
+ const modeSel = document.getElementById('restartMode');
+
+ // 开始游戏 - 只发送"开始"指令
+ if (btnStart) {
+ btnStart.addEventListener('click', async () => {
+ try {
+ const res = await fetch('/api/start', { method: 'POST' });
+ const result = await res.json();
+ if (result.success) {
+ alert('游戏已开始!');
+ } else {
+ alert('启动失败: ' + (result.error || '未知错误'));
+ }
+ } catch (e) {
+ console.error('Start error:', e);
+ alert('启动失败,请检查服务器是否运行');
+ }
+ });
+ }
+
+ // 停止游戏
+ if (btnStop) {
+ btnStop.addEventListener('click', async () => {
+ try {
+ const res = await fetch('/api/stop', { method: 'POST' });
+ const result = await res.json();
+ if (result.success) {
+ alert('游戏已停止!');
+ } else {
+ alert('停止失败: ' + (result.error || '未知错误'));
+ }
+ } catch (e) {
+ console.error('Stop error:', e);
+ alert('停止失败,请检查服务器是否运行');
+ }
+ });
+ }
+
+ // 重新开始游戏 - 重新初始化
+ const doRestart = async (triggerBtn) => {
+ if (triggerBtn) triggerBtn.disabled = true;
+ if (status) status.textContent = '正在开始新局,请稍候...';
+ localStorage.setItem('ww_restart_at', String(Date.now()));
+ uiState.lastSpeechKey = '';
+ uiState.lastData = null;
+ const chatBody = document.getElementById('chatBody');
+ if (chatBody) chatBody.innerHTML = '';
+
+ try {
+ // 调用重启API
+ const res = await fetch('/api/restart', { method: 'POST' });
+ const result = await res.json();
+
+ if (result.success) {
+ if (status) status.textContent = '新局已启动,正在刷新...';
+ // 直接刷新页面
+ setTimeout(() => {
+ window.location.reload();
+ }, 500);
+ } else {
+ alert('重启失败: ' + (result.error || '未知错误'));
+ if (triggerBtn) triggerBtn.disabled = false;
+ }
+ } catch (e) {
+ console.error('Restart error:', e);
+ alert('重启失败,请检查服务器是否运行');
+ if (triggerBtn) triggerBtn.disabled = false;
+ }
+ };
+
+ if (btnRestart) btnRestart.addEventListener('click', () => doRestart(btnRestart));
+ if (forceBtn) forceBtn.addEventListener('click', () => {
+ if (confirm('确定要在游戏中途强制重开吗?')) {
+ doRestart(forceBtn);
+ }
+ });
+ }
+
+ window.onload = () => {
+ // 动态添加游戏控制按钮
+ addGameControlButtons();
+
+ bindViewerButtons();
+ bindPickers();
+ bindGameControls();
+ bindNav();
+ bindSearch();
+ bindDrawer();
+ refreshFromHttp();
+ setInterval(() => {
+ if (uiState.httpBase) {
+ refreshFromHttp();
+ return;
+ }
+ if (uiState.workspaceHandle || uiState.storageHandle) {
+ refreshFromFS();
+ }
+ }, 3000);
+ };
+
+ function addGameControlButtons() {
+ // 在 headerRight 区域添加控制按钮
+ const headerRight = document.querySelector('.headerRight');
+ if (!headerRight) return;
+
+ // 找到强制重开按钮的位置
+ const forceBtn = document.getElementById('navForceRestart');
+ if (!forceBtn) return;
+
+ // 创建开始按钮
+ const btnStart = document.createElement('button');
+ btnStart.id = 'btnStart';
+ btnStart.className = 'btn';
+ btnStart.style.cssText = 'margin-right: 8px; padding: 4px 12px; font-size: 13px; height: 26px; background: rgba(110,231,183,0.15); border-color: rgba(110,231,183,0.5);';
+ btnStart.textContent = '开始游戏';
+
+ // 创建停止按钮
+ const btnStop = document.createElement('button');
+ btnStop.id = 'btnStop';
+ btnStop.className = 'btn';
+ btnStop.style.cssText = 'margin-right: 8px; padding: 4px 12px; font-size: 13px; height: 26px; background: rgba(251,113,133,0.15); border-color: rgba(251,113,133,0.5);';
+ btnStop.textContent = '停止游戏';
+
+ // 插入到强制重开按钮之前
+ headerRight.insertBefore(btnStop, forceBtn);
+ headerRight.insertBefore(btnStart, btnStop);
+ }
+
+ function updateButtonVisibility(status) {
+ const smartButtons = status.smart_buttons || false;
+ const running = status.running || false;
+ const gameEnded = status.game_ended || false;
+ const forceRestarted = status.force_restarted || false;
+
+ const btnStart = document.getElementById('btnStart');
+ const btnStop = document.getElementById('btnStop');
+ const forceBtn = document.getElementById('navForceRestart');
+
+ if (!smartButtons) {
+ if (btnStart) btnStart.style.display = '';
+ if (btnStop) btnStop.style.display = '';
+ if (forceBtn) forceBtn.style.display = '';
+ return;
+ }
+
+ if (btnStart) {
+ if (gameEnded) {
+ btnStart.style.display = 'none';
+ } else if (running) {
+ btnStart.style.display = 'none';
+ } else {
+ btnStart.style.display = '';
+ }
+ }
+
+ if (btnStop) {
+ btnStop.style.display = 'none';
+ }
+
+ if (forceBtn) {
+ if (gameEnded) {
+ forceBtn.style.display = '';
+ forceBtn.textContent = '重新开始';
+ } else if (running) {
+ forceBtn.style.display = 'none';
+ } else {
+ forceBtn.style.display = '';
+ forceBtn.textContent = '重新开始';
+ }
+ }
+
+ updateHumanPlayerUI(status);
+ }
+
+ let humanGameMdContent = '';
+
+ async function updateHumanPlayerUI(status) {
+ const hasHumanPlayer = status.has_human_player || false;
+ const waitingForHuman = status.waiting_for_human || false;
+ const humanPanel = document.getElementById('humanPlayerPanel');
+ const gameWrap = document.getElementById('gameWrap');
+ const humanStatus = document.getElementById('humanStatus');
+ const humanSendBtn = document.getElementById('humanSendBtn');
+ const humanInput = document.getElementById('humanInput');
+
+ if (!hasHumanPlayer) {
+ if (humanPanel) humanPanel.style.display = 'none';
+ if (gameWrap) gameWrap.style.gridTemplateColumns = 'minmax(560px, 1.8fr) minmax(360px, 1fr)';
+ return;
+ }
+
+ if (humanPanel) humanPanel.style.display = '';
+ if (gameWrap) gameWrap.style.gridTemplateColumns = 'minmax(520px, 1.5fr) minmax(340px, 1fr)';
+
+ if (humanStatus) {
+ humanStatus.textContent = waitingForHuman ? '需要你回复!' : '等待中...';
+ }
+
+ if (humanSendBtn) {
+ humanSendBtn.disabled = !waitingForHuman;
+ humanSendBtn.style.opacity = waitingForHuman ? '1' : '0.5';
+ }
+
+ if (humanInput) {
+ humanInput.disabled = !waitingForHuman;
+ humanInput.placeholder = waitingForHuman ? '在此输入你的回复...' : '等待轮到你...';
+ }
+ }
+
+ async function sendHumanMessage() {
+ const input = document.getElementById('humanInput');
+ if (!input || !input.value.trim()) return;
+
+ try {
+ const res = await fetch('/api/human/send', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ message: input.value.trim() })
+ });
+ if (res.ok) {
+ input.value = '';
+ }
+ } catch (e) {
+ console.error('Failed to send human message:', e);
+ }
+ }
+
+ async function loadHumanGameMd() {
+ try {
+ const res = await fetch('/api/human/game-md');
+ if (res.ok) {
+ const data = await res.json();
+ humanGameMdContent = data.content || '';
+ }
+ } catch (e) {
+ console.error('Failed to load human GAME.md:', e);
+ }
+ }
+
+ async function editHumanGameMd() {
+ await loadHumanGameMd();
+ const content = prompt('编辑你的GAME.md(角色、状态等):', humanGameMdContent);
+ if (content !== null) {
+ try {
+ const res = await fetch('/api/human/game-md', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify({ content: content })
+ });
+ if (res.ok) {
+ humanGameMdContent = content;
+ }
+ } catch (e) {
+ console.error('Failed to save human GAME.md:', e);
+ }
+ }
+ }
+
+ async function saveGameToLeaderboard(data, info, status) {
+ if (!info.winner) return;
+
+ const players = data.players || [];
+ const isWolfWin = info.winner.includes('狼人');
+ const dead = info.dead || new Set();
+
+ const gamePlayers = players.map((p, i) => {
+ const role = String(p.role || '');
+ const isWolf = role === 'Werewolf' || role === 'WhiteWolfKing' || role === 'WolfCub' || role === 'WolfBeauty';
+ const won = (isWolfWin && isWolf) || (!isWolfWin && !isWolf);
+ const isDead = dead.has(i);
+
+ let score = 0;
+ if (won) score += 3;
+ if (!isDead) score += 1;
+ else score -= 1;
+
+ return {
+ id: p.id || `player_${i + 1}`,
+ role: role,
+ won: won,
+ dead: isDead,
+ score: score
+ };
+ });
+
+ const gameData = {
+ session_id: status ? status.session_id : '',
+ winner: info.winner,
+ players: gamePlayers
+ };
+
+ try {
+ const res = await fetch('/api/leaderboard/save', {
+ method: 'POST',
+ headers: { 'Content-Type': 'application/json' },
+ body: JSON.stringify(gameData)
+ });
+ if (res.ok) {
+ console.log('Game saved to leaderboard');
+ }
+ } catch (e) {
+ console.error('Failed to save to leaderboard:', e);
+ }
+ }
+
+ async function refreshFromHttp() {
+ if (uiState.loading) return;
+ uiState.loading = true;
+ try {
+ console.log('refreshFromHttp starting...');
+
+ // Load game data (players, game_record)
+ const data = await loadDataFromHttp(uiState.httpBase);
+ console.log('loadDataFromHttp result:', data);
+ uiState.lastData = data;
+
+ // Load status from API for button control
+ const statusRes = await fetch('/api/status');
+ const statusData = await statusRes.json();
+ console.log('/api/status result:', statusData);
+ uiState.lastStatus = statusData;
+
+ // Update button visibility based on status
+ updateButtonVisibility(statusData);
+
+ // Load messages from API
+ const messagesRes = await fetch('/api/messages');
+ const messagesData = await messagesRes.json();
+ console.log('/api/messages result:', messagesData);
+
+ const info = parseRecordInfo(data.game_record || '');
+ console.log('parseRecordInfo result:', info);
+ console.log('Players to render:', data.players);
+
+ // Build latest speech map from messages
+ const latestSpeeches = new Map();
+ for (let i = messagesData.messages.length - 1; i >= 0; i--) {
+ const msg = messagesData.messages[i];
+ if (!msg.is_user && !latestSpeeches.has(msg.channel_id)) {
+ latestSpeeches.set(msg.channel_id, msg.content);
+ }
+ }
+ console.log('Latest speeches from /api/messages:', Object.fromEntries(latestSpeeches));
+
+ // Find the latest speaking player
+ let latestPlayerId = null;
+ let latestTimestamp = 0;
+ for (let i = messagesData.messages.length - 1; i >= 0; i--) {
+ const msg = messagesData.messages[i];
+ if (!msg.is_user && !latestSpeeches.has(msg.channel_id)) {
+ continue;
+ }
+ if (!msg.is_user && msg.timestamp > latestTimestamp) {
+ latestTimestamp = msg.timestamp;
+ latestPlayerId = msg.channel_id;
+ }
+ }
+ console.log('Latest speaking player:', latestPlayerId);
+
+ // Update players with latest speeches - only show latest one
+ const playersWithSpeech = (data.players || []).map(p => ({
+ ...p,
+ last_speech: (p.id === latestPlayerId) ? String(latestSpeeches.get(p.id) || p.last_speech || '') : ''
+ }));
+
+ setHeaderState(info, playersWithSpeech || []);
+ renderArena(playersWithSpeech || [], info, data);
+ setFsState();
+ updateEndOverlay(info);
+ renderChatFromMessages(messagesData.messages, info, data);
+ renderMemoryPage(data);
+ renderRank(data, info);
+
+ // Check if game just ended and save to leaderboard
+ if (info.winner && !uiState.lastGameWinner) {
+ uiState.lastGameWinner = info.winner;
+ saveGameToLeaderboard(data, info, statusData);
+ } else if (!info.winner) {
+ uiState.lastGameWinner = null;
+ }
+
+ console.log('refreshFromHttp completed');
+ } catch (e) {
+ console.error('refreshFromHttp error:', e);
+ } finally {
+ uiState.loading = false;
+ }
+ }
+ </script>
+</body>
+</html>
diff --git a/bot/demo/werewolf/werewolf_server.py b/bot/demo/werewolf/werewolf_server.py
new file mode 100644
index 000000000..ac3a55eec
--- /dev/null
+++ b/bot/demo/werewolf/werewolf_server.py
@@ -0,0 +1,1426 @@
+"""Werewolf game server with message routing and Web UI."""
+
+import asyncio
+import json
+import re
+import time
+from datetime import datetime
+from pathlib import Path
+from typing import Any, Dict, List, Optional
+
+import httpx
+import typer
+from fastapi import FastAPI
+from fastapi.responses import HTMLResponse, FileResponse, JSONResponse
+from loguru import logger
+from dataclasses import dataclass, field
+
+app = typer.Typer()
+
+
+# ============================================================================
+# Data Models
+# ============================================================================
+
+
+@dataclass
+class ChatMessage:
+ """A chat message in the history."""
+ channel_id: str
+ content: str
+ is_user: bool
+ timestamp: float = field(default_factory=lambda: __import__('time').time())
+
+
+@dataclass
+class PendingReply:
+ """Track pending player replies."""
+ channel_id: str
+ message_id: str
+ timestamp: float
+
+
+@dataclass
+class GameState:
+ """Shared game state."""
+ game_id: str
+ vikingbot_url: str
+ config_path: Path
+ running: bool = False
+ channels: List[str] = field(default_factory=list)
+ messages: List[ChatMessage] = field(default_factory=list)
+ session_id: str = ""
+ config: Dict[str, Any] = field(default_factory=dict)
+ storage_path: Path = field(default_factory=Path)
+ router_task: Optional[asyncio.Task] = None
+ pending_replies: Dict[str, PendingReply] = field(default_factory=dict)
+ message_queue: List[Dict[str, Any]] = field(default_factory=list)
+ game_ended: bool = False
+ force_restarted: bool = False
+ has_human_player: bool = False
+ human_player_channel: str = "human"
+ waiting_for_human: bool = False
+ human_player_message: Optional[str] = None
+
+
+# ============================================================================
+# Configuration Loading
+# ============================================================================
+
+
+def load_config(config_path: Path) -> Dict[str, Any]:
+ """Load configuration from JSON file."""
+ if not config_path.exists():
+ raise FileNotFoundError(f"Config file not found: {config_path}")
+ content = config_path.read_text(encoding="utf-8")
+ return json.loads(content)
+
+
+def get_bot_channels(config: Dict[str, Any]) -> List[str]:
+ """Extract bot_api channel IDs from config."""
+ channels = []
+ bot_config = config.get("bot", {})
+ channel_configs = bot_config.get("channels", [])
+ for ch in channel_configs:
+ if ch.get("type") == "bot_api" and ch.get("enabled", False):
+ ch_id = ch.get("id")
+ if ch_id:
+ channels.append(ch_id)
+ return channels
+
+
+def get_storage_path(config: Dict[str, Any]) -> Path:
+ """Get storage path from config."""
+ storage_config = config.get("storage", {})
+ bot_config = config.get("bot", {})
+ sandbox_config = bot_config.get("sandbox", {})
+ storage_workspace = sandbox_config.get("storage_workspace") or storage_config.get("workspace", "~/.openviking/data")
+ return Path(storage_workspace).expanduser()
+
+
+def get_viking_path(config: Dict[str, Any]) -> Path:
+ """Get viking path from config (storage.workspace/viking)."""
+ storage_path = get_storage_path(config)
+ return storage_path / "viking"
+
+
+# ============================================================================
+# API Client
+# ============================================================================
+
+
+async def send_to_channel(
+ vikingbot_url: str,
+ channel_id: str,
+ message: str,
+ session_id: str,
+ user_id: str = "werewolf_server",
+ need_reply: bool = True,
+ timeout: float = 300.0,
+) -> Dict[str, Any]:
+ """
+ Send a message to a specific bot_api channel.
+
+ Returns:
+ The response JSON from vikingbot.
+ """
+ url = f"{vikingbot_url.rstrip('/')}/bot/v1/chat/channel"
+ payload = {
+ "message": message,
+ "session_id": session_id,
+ "user_id": user_id,
+ "stream": False,
+ "channel_id": channel_id,
+ "need_reply": need_reply,
+ }
+
+ timeout_config = httpx.Timeout(connect=10.0, read=timeout, write=30.0, pool=30.0)
+
+ async with httpx.AsyncClient(timeout=timeout_config) as client:
+ response = await client.post(url, json=payload)
+ response.raise_for_status()
+ return response.json()
+
+
+# ============================================================================
+# Message Parsing
+# ============================================================================
+
+
+def parse_mentions(content: str) -> List[str]:
+ """
+ Parse @ mentions from message content.
+
+ Returns:
+ List of channel IDs mentioned (e.g., ["player_1", "player_2"]).
+ """
+ pattern = r"@\s*(\w+)"
+ mentions = re.findall(pattern, content)
+ return mentions
+
+
+def extract_content_without_mentions(content: str) -> str:
+ """
+ Extract message content without the @ mentions.
+
+ Returns:
+ The pure message content.
+ """
+ cleaned = re.sub(r"@\s*\w+\s*", "", content)
+ return cleaned.strip()
+
+
+# ============================================================================
+# UI File Initialization
+# ============================================================================
+
+
+def generate_session_id() -> str:
+ """Generate a session ID based on current time."""
+ return datetime.now().strftime("%Y%m%d_%H%M%S")
+
+
+def save_conversation_to_file(storage_path: Path, session_id: str, messages: List[ChatMessage]):
+ """Save conversation history to a file."""
+ bot_workspace = storage_path / "bot" / "workspace" / "werewolf"
+ bot_workspace.mkdir(parents=True, exist_ok=True)
+
+ file_path = bot_workspace / f"CONVERSATION_{session_id}.md"
+
+ lines = [f"# 狼人杀对话记录 - {session_id}\n"]
+
+ for msg in messages:
+ speaker = msg.channel_id
+ timestamp = datetime.fromtimestamp(msg.timestamp).strftime("%H:%M:%S")
+ lines.append(f"\n## [{timestamp}] {speaker}\n")
+ lines.append(msg.content)
+
+ file_path.write_text("\n".join(lines), encoding="utf-8")
+ logger.info(f"Conversation saved to {file_path}")
+
+
+def load_latest_conversation(storage_path: Path) -> tuple[List[ChatMessage], Optional[str]]:
+ """Load the latest conversation from files. Returns (messages, session_id)."""
+ bot_workspace = storage_path / "bot" / "workspace" / "werewolf"
+ if not bot_workspace.exists():
+ return [], None
+
+ # Find all conversation files
+ conversation_files = sorted(
+ bot_workspace.glob("CONVERSATION_*.md"),
+ key=lambda p: p.stat().st_mtime,
+ reverse=True
+ )
+
+ if not conversation_files:
+ return [], None
+
+ latest_file = conversation_files[0]
+ logger.info(f"Loading latest conversation from {latest_file}")
+
+ # Extract session_id from filename (CONVERSATION_20260331_153000.md)
+ session_id = latest_file.stem.replace("CONVERSATION_", "")
+
+ content = latest_file.read_text(encoding="utf-8")
+ messages = []
+
+ # Parse the markdown format
+ current_speaker = None
+ current_timestamp = None
+ current_content = []
+
+ for line in content.split("\n"):
+ line = line.rstrip()
+ # Match section header: ## [HH:MM:SS] speaker
+ match = re.match(r'^## \[([0-9:]+)\] (.+)$', line)
+ if match:
+ # Save previous message
+ if current_speaker and current_content:
+ # Try to parse timestamp, or use current time
+ try:
+ # We don't have the date, just use current time
+ ts = time.time()
+ except ValueError:
+ ts = time.time()
+
+ messages.append(ChatMessage(
+ channel_id=current_speaker,
+ content="\n".join(current_content).strip(),
+ is_user=(current_speaker == "admin"),
+ timestamp=ts
+ ))
+
+ # Start new message
+ time_str = match.group(1)
+ current_speaker = match.group(2)
+ current_content = []
+ elif line and not line.startswith("# "):
+ # Content line
+ if current_speaker is not None:
+ current_content.append(line)
+
+ # Save the last message
+ if current_speaker and current_content:
+ try:
+ ts = time.time()
+ except ValueError:
+ ts = time.time()
+
+ messages.append(ChatMessage(
+ channel_id=current_speaker,
+ content="\n".join(current_content).strip(),
+ is_user=(current_speaker == "admin"),
+ timestamp=ts
+ ))
+
+ logger.info(f"Loaded {len(messages)} messages from latest conversation, session_id={session_id}")
+ return messages, session_id
+
+
+def init_ui_files(storage_path: Path, channels: List[str], game_id: str = "default"):
+ """Initialize UI file structure.
+
+ Note: Actual game files are maintained by the agents themselves in:
+ - {storage_path}/bot/workspace/bot_api__god/GAME_RECORD.md (god's record)
+ - {storage_path}/bot/workspace/bot_api__player_*/GAME.md (player files)
+ """
+ # Just ensure the bot/workspace directory exists
+ bot_workspace_path = storage_path / "bot" / "workspace"
+ bot_workspace_path.mkdir(parents=True, exist_ok=True)
+
+ logger.info(f"UI files initialized in {storage_path}")
+ logger.info(f" Looking for game records in: {bot_workspace_path}/bot_api__god/GAME_RECORD.md")
+
+
+# ============================================================================
+# New Helper Functions for Multi-Player Routing
+# ============================================================================
+
+
+async def broadcast_to_players(
+ state: GameState,
+ message: str,
+ mentioned_players: List[str],
+ sender_id: str = "god",
+) -> List[Dict[str, Any]]:
+ """
+ Broadcast message to all players:
+ - Mentioned players: need_reply=True, wait for reply
+ - Other players: need_reply=False, just receive
+ - Human player: if mentioned, wait for user input
+
+ Returns:
+ List of replies from mentioned players
+ """
+ import time
+ tasks = []
+ reply_channels = []
+ all_player_channels = []
+ human_mentioned = False
+
+ # Build player seat number map first
+ player_seat_map = {}
+ seat_idx = 1
+ for ch in state.channels:
+ if ch == "god":
+ continue
+ player_seat_map[ch] = seat_idx
+ seat_idx += 1
+
+ # Get sender prefix
+ if sender_id == "god":
+ sender_prefix = "god:"
+ else:
+ sender_seat = player_seat_map.get(sender_id, sender_id)
+ sender_prefix = f"{sender_seat}号:"
+
+ # Check if human player is mentioned
+ if state.has_human_player and state.human_player_channel in mentioned_players:
+ human_mentioned = True
+ mentioned_players = [ch for ch in mentioned_players if ch != state.human_player_channel]
+ logger.info(f"Human player mentioned, will wait for user input")
+
+ for ch in state.channels:
+ if ch == "god":
+ continue
+ if ch == state.human_player_channel:
+ # Skip human player in bot broadcast
+ all_player_channels.append(ch)
+ continue
+ all_player_channels.append(ch)
+
+ is_mentioned = ch in mentioned_players
+
+ message_for_player = f"{sender_prefix}{message}"
+
+ # Create send task with sender_id
+ task = send_to_channel(
+ vikingbot_url=state.vikingbot_url,
+ channel_id=ch,
+ message=message_for_player,
+ session_id=state.session_id,
+ user_id=sender_id,
+ need_reply=is_mentioned,
+ )
+ tasks.append(task)
+
+ if is_mentioned:
+ reply_channels.append(ch)
+
+ logger.info(f"Broadcasting to {len(all_player_channels)} players, {len(reply_channels)} need reply: {reply_channels}")
+
+ # Send all messages concurrently (don't record internal broadcasts)
+ results = await asyncio.gather(*tasks, return_exceptions=True)
+
+ # Record replies from players (these are visible)
+ replies = []
+ result_idx = 0
+ for ch in all_player_channels:
+ if ch == state.human_player_channel:
+ continue
+ result = results[result_idx] if result_idx < len(results) else None
+ result_idx += 1
+
+ is_mentioned = ch in reply_channels
+
+ # If this player was mentioned and replied successfully, record the reply
+ if is_mentioned and not isinstance(result, Exception):
+ response_content = result.get("message", "") or ""
+ state.messages.append(ChatMessage(
+ channel_id=ch,
+ content=response_content,
+ is_user=False,
+ timestamp=time.time(),
+ ))
+ logger.info(f"Received reply from {ch}: {response_content[:100]}...")
+ replies.append({
+ "channel_id": ch,
+ "response": result
+ })
+
+ # Handle human player
+ if human_mentioned:
+ logger.info(f"Waiting for human player input...")
+ state.waiting_for_human = True
+
+ # Record the message to human player
+ human_message = f"{sender_prefix}{message}"
+ state.messages.append(ChatMessage(
+ channel_id=sender_id,
+ content=human_message,
+ is_user=False,
+ timestamp=time.time(),
+ ))
+ if state.session_id:
+ save_conversation_to_file(state.storage_path, state.session_id, state.messages)
+
+ # Wait for human player to respond
+ while state.waiting_for_human and state.running:
+ await asyncio.sleep(0.1)
+
+ if state.human_player_message:
+ # Add human reply
+ reply_content = state.human_player_message
+ state.human_player_message = None
+ replies.append({
+ "channel_id": state.human_player_channel,
+ "response": {"message": reply_content}
+ })
+ logger.info(f"Received human player reply: {reply_content[:100]}...")
+
+ # Save after receiving player replies
+ if state.session_id:
+ save_conversation_to_file(state.storage_path, state.session_id, state.messages)
+
+ return replies
+
+
+async def broadcast_message_to_players(
+ state: GameState,
+ message: str,
+ sender_id: str,
+ exclude_players: List[str] = None,
+):
+ """
+ Broadcast a message to all players (except excluded ones) with need_reply=False.
+ """
+ if exclude_players is None:
+ exclude_players = []
+
+ # Build player seat number map
+ player_seat_map = {}
+ seat_idx = 1
+ for ch in state.channels:
+ if ch == "god":
+ continue
+ player_seat_map[ch] = seat_idx
+ seat_idx += 1
+
+ # Get sender's seat number
+ if sender_id == "god":
+ sender_prefix = "god:"
+ else:
+ sender_seat = player_seat_map.get(sender_id, sender_id)
+ sender_prefix = f"{sender_seat}号:"
+
+ # Collect all player channels except excluded
+ tasks = []
+ for ch in state.channels:
+ if ch == "god":
+ continue
+ if ch in exclude_players:
+ continue
+
+ message_for_player = f"{sender_prefix}{message}"
+
+ task = send_to_channel(
+ vikingbot_url=state.vikingbot_url,
+ channel_id=ch,
+ message=message_for_player,
+ session_id=state.session_id,
+ user_id=sender_id,
+ need_reply=False,
+ )
+ tasks.append(task)
+
+ if tasks:
+ logger.info(f"Broadcasting message from {sender_id} to {len(tasks)} players")
+ await asyncio.gather(*tasks, return_exceptions=True)
+
+
+def build_message_for_god(player_replies: List[Dict[str, Any]], all_channels: List[str]) -> str:
+ """Build a message for god from player replies."""
+ if not player_replies:
+ return "没有玩家回复"
+
+ # Build seat number map first
+ player_seat_map = {}
+ seat_idx = 1
+ for ch in all_channels:
+ if ch == "god":
+ continue
+ player_seat_map[ch] = seat_idx
+ seat_idx += 1
+
+ parts = []
+ for reply in player_replies:
+ content = reply.get("response", {}).get("message", "")
+ channel_id = reply['channel_id']
+ if channel_id == "god":
+ parts.append(f"god:{content}")
+ else:
+ seat_num = player_seat_map.get(channel_id, channel_id)
+ parts.append(f"{seat_num}号:{content}")
+
+ return "\n".join(parts)
+
+
+# ============================================================================
+# Message Router (Rewritten)
+# ============================================================================
+
+
+async def message_router_loop(
+ state: GameState,
+ initial_channel: str = "god",
+ initial_message: str = "开始",
+ is_admin_initiated: bool = True,
+):
+ """
+ Main message routing loop - rewritten for multi-player support.
+
+ Flow:
+ 1. Send message to god (or current channel)
+ 2. Parse @ mentions from god's reply
+ 3. Broadcast to all players:
+ - @mentioned players: need_reply=True
+ - others: need_reply=False
+ 4. Collect replies from mentioned players
+ 5. Send replies back to god
+ 6. Repeat...
+ """
+ import time
+
+ logger.info(f"Starting message router for game {state.game_id}")
+
+ current_channel = initial_channel
+ current_message = initial_message
+ loop_count = 0
+ max_loops = 1000
+ current_sender_id = "admin" # Track who is sending this message
+
+ try:
+ while state.running and loop_count < max_loops:
+ loop_count += 1
+
+ # 0. Record admin message only for the first round (admin -> god)
+ if loop_count == 1:
+ msg_timestamp = time.time()
+ state.messages.append(ChatMessage(
+ channel_id="admin",
+ content=current_message,
+ is_user=True,
+ timestamp=msg_timestamp,
+ ))
+ # Save immediately so UI can show it
+ if state.session_id:
+ save_conversation_to_file(state.storage_path, state.session_id, state.messages)
+
+ # 1. Send message to current channel (usually god)
+ logger.info(f"Sending to {current_channel} (from {current_sender_id}): {current_message[:100]}...")
+ try:
+ response = await send_to_channel(
+ vikingbot_url=state.vikingbot_url,
+ channel_id=current_channel,
+ message=current_message,
+ session_id=state.session_id,
+ user_id=current_sender_id,
+ need_reply=True,
+ )
+ except Exception as e:
+ logger.exception(f"Error sending to {current_channel}: {e}")
+ await asyncio.sleep(1)
+ continue
+
+ # 2. Get response content
+ response_content = response.get("message", "") or ""
+ logger.info(f"Received from {current_channel}: {response_content[:100]}...")
+
+ # 3. Record agent's reply (always record agent responses)
+ state.messages.append(ChatMessage(
+ channel_id=current_channel,
+ content=response_content,
+ is_user=False,
+ timestamp=time.time(),
+ ))
+
+ # 4. Save conversation to file
+ if state.session_id:
+ save_conversation_to_file(state.storage_path, state.session_id, state.messages)
+
+ # 4. Parse mentions from response
+ mentions = parse_mentions(response_content)
+ pure_content = extract_content_without_mentions(response_content)
+ if not pure_content:
+ pure_content = current_message
+
+ if not mentions:
+ # 如果没有 @ 提及,可能是游戏初始化完成,等待继续
+ if "初始化完成" in response_content or "等待" in response_content:
+ logger.info("Game initialized, waiting for start command...")
+ # 保持运行,但不继续发送消息,等待外部命令
+ await asyncio.sleep(1)
+ break # 退出循环,等待下次调用
+ else:
+ logger.info("No mentions in response, waiting for next command")
+ break
+
+ # Validate mentioned channels exist
+ valid_mentions = [m for m in mentions if m in state.channels and m != "god"]
+ if not valid_mentions:
+ logger.warning(f"No valid player mentions in: {mentions}, available: {state.channels}")
+ break
+
+ logger.info(f"Mentioned players: {valid_mentions}")
+
+ # 6. Broadcast to all players - sender is current_channel (god)
+ player_replies = await broadcast_to_players(
+ state=state,
+ message=pure_content,
+ mentioned_players=valid_mentions,
+ sender_id=current_channel,
+ )
+
+ if not player_replies:
+ logger.warning("No player replies received")
+ break
+
+ # 7. First, broadcast player replies to all other players (need_reply=False)
+ if player_replies:
+ for reply in player_replies:
+ reply_channel = reply['channel_id']
+ reply_content = reply.get("response", {}).get("message", "")
+ if reply_content:
+ await broadcast_message_to_players(
+ state=state,
+ message=reply_content,
+ sender_id=reply_channel,
+ exclude_players=[reply_channel],
+ )
+
+ # 8. Build message for god from player replies
+ god_message = build_message_for_god(player_replies, state.channels)
+ logger.info(f"Sending player replies back to god: {god_message[:100]}...")
+
+ # 9. Next iteration: send replies back to god
+ current_channel = "god"
+ current_message = god_message
+
+ await asyncio.sleep(0.1)
+
+ if loop_count >= max_loops:
+ logger.warning(f"Reached max loops ({max_loops}), stopping router")
+
+ except asyncio.CancelledError:
+ logger.info("Message router cancelled")
+ except Exception as e:
+ logger.exception(f"Error in message router: {e}")
+ finally:
+ state.running = False
+ logger.info("Message router stopped")
+
+
+# ============================================================================
+# Web UI - FastAPI
+# ============================================================================
+
+
+def create_fastapi_app(state: GameState) -> FastAPI:
+ """Create the FastAPI application for the Web UI."""
+ fastapi_app = FastAPI(title="Werewolf Game Server")
+
+ ui_html_path = Path(__file__).parent / "werewolfUI.html"
+ ui_html = ""
+ if ui_html_path.exists():
+ ui_html = ui_html_path.read_text(encoding="utf-8")
+ else:
+ ui_html = """
+ <!DOCTYPE html>
+ <html>
+ <head><title>Werewolf Game</title></head>
+ <body><h1>Werewolf UI not found</h1></body>
+ </html>
+ """
+
+ test_html_path = Path(__file__).parent / "test_server.html"
+ test_html = ""
+ if test_html_path.exists():
+ test_html = test_html_path.read_text(encoding="utf-8")
+
+ debug_html_path = Path(__file__).parent / "debug.html"
+ debug_html = ""
+ if debug_html_path.exists():
+ debug_html = debug_html_path.read_text(encoding="utf-8")
+
+ @fastapi_app.get("/", response_class=HTMLResponse)
+ async def index():
+ """Serve the main UI page."""
+ return HTMLResponse(content=ui_html)
+
+ @fastapi_app.get("/test", response_class=HTMLResponse)
+ async def test_page():
+ """Serve the test/control panel page."""
+ return HTMLResponse(content=test_html)
+
+ @fastapi_app.get("/debug", response_class=HTMLResponse)
+ async def debug_page():
+ """Serve the debug page."""
+ return HTMLResponse(content=debug_html)
+
+ @fastapi_app.get("/fonts/{filename}")
+ async def serve_font(filename: str):
+ """Serve font files."""
+ font_path = Path(__file__).parent / filename
+ if font_path.exists():
+ return FileResponse(font_path)
+ return HTMLResponse(content="", status_code=404)
+
+ @fastapi_app.get("/api/status")
+ async def get_status():
+ """Get current game status."""
+ # Check if game has ended by looking at GAME_RECORD.md
+ if not state.game_ended:
+ god_record_path = state.storage_path / "bot" / "workspace" / "bot_api__god" / "GAME_RECORD.md"
+ if god_record_path.exists():
+ try:
+ content = god_record_path.read_text(encoding="utf-8")
+ if "游戏结束" in content:
+ state.game_ended = True
+ # Also set running to False when game ends
+ if state.running:
+ state.running = False
+ except Exception:
+ pass
+
+ return JSONResponse(content={
+ "game_id": state.game_id,
+ "session_id": state.session_id,
+ "running": state.running,
+ "channels": state.channels,
+ "message_count": len(state.messages),
+ "smart_buttons": state.config.get("smart_buttons", False),
+ "game_ended": state.game_ended,
+ "force_restarted": state.force_restarted,
+ "has_human_player": state.has_human_player,
+ "human_player_channel": state.human_player_channel,
+ "waiting_for_human": state.waiting_for_human,
+ })
+
+ @fastapi_app.post("/api/human/send")
+ async def send_human_message(payload: dict):
+ """Send a message from human player."""
+ if not state.has_human_player:
+ return JSONResponse(content={"success": False, "error": "Human player mode not enabled"})
+
+ message = payload.get("message", "")
+ if not message:
+ return JSONResponse(content={"success": False, "error": "Message is empty"})
+
+ import time
+ # Record human message
+ state.messages.append(ChatMessage(
+ channel_id=state.human_player_channel,
+ content=message,
+ is_user=True,
+ timestamp=time.time(),
+ ))
+ if state.session_id:
+ save_conversation_to_file(state.storage_path, state.session_id, state.messages)
+
+ # Set the message for the router
+ state.human_player_message = message
+ state.waiting_for_human = False
+
+ return JSONResponse(content={"success": True})
+
+ @fastapi_app.get("/api/human/game-md")
+ async def get_human_game_md():
+ """Get human player's GAME.md content."""
+ if not state.has_human_player:
+ return JSONResponse(content={"error": "Human player mode not enabled"}, status_code=400)
+
+ human_game_md = state.storage_path / "bot" / "workspace" / "human" / "GAME.md"
+ if not human_game_md.exists():
+ return JSONResponse(content={"content": "# 真实玩家游戏文件\n\n请编辑此文件来设置你的角色和状态。\n"})
+
+ return JSONResponse(content={"content": human_game_md.read_text(encoding="utf-8")})
+
+ @fastapi_app.post("/api/human/game-md")
+ async def save_human_game_md(payload: dict):
+ """Save human player's GAME.md content."""
+ if not state.has_human_player:
+ return JSONResponse(content={"error": "Human player mode not enabled"}, status_code=400)
+
+ content = payload.get("content", "")
+ human_game_md = state.storage_path / "bot" / "workspace" / "human" / "GAME.md"
+ human_game_md.parent.mkdir(parents=True, exist_ok=True)
+ human_game_md.write_text(content, encoding="utf-8")
+
+ return JSONResponse(content={"success": True})
+
+ @fastapi_app.get("/api/messages")
+ async def get_messages():
+ """Get full message history."""
+ return JSONResponse(content={
+ "messages": [
+ {
+ "channel_id": msg.channel_id,
+ "content": msg.content,
+ "is_user": msg.is_user,
+ "timestamp": msg.timestamp
+ }
+ for msg in state.messages
+ ]
+ })
+
+ @fastapi_app.get("/api/players")
+ async def get_players():
+ """Get player info, reading roles from GAME.md."""
+ players = []
+ player_idx = 1
+ for ch in state.channels:
+ if ch == "god":
+ continue
+ if player_idx > 8:
+ break
+
+ # Read this player's GAME.md
+ game_md_path = state.storage_path / "bot" / "workspace" / f"bot_api__{ch}" / "GAME.md"
+ role = "未知"
+ if game_md_path.exists():
+ content = game_md_path.read_text(encoding="utf-8")
+ role_match = re.search(r"身份[::]\s*(.+)", content)
+ if role_match:
+ role = role_match.group(1).strip()
+
+ players.append({
+ "id": ch,
+ "seat": player_idx,
+ "role": role
+ })
+ player_idx += 1
+
+ return JSONResponse(content={"players": players})
+
+ @fastapi_app.post("/api/start")
+ async def start_game():
+ """Start the game."""
+ if state.running:
+ return JSONResponse(content={"success": False, "error": "Game already running"})
+
+ if "god" not in state.channels:
+ return JSONResponse(content={"success": False, "error": "god channel not found"})
+
+ state.running = True
+ state.game_ended = False
+ state.router_task = asyncio.create_task(
+ message_router_loop(state, initial_channel="god", initial_message="开始")
+ )
+ return JSONResponse(content={"success": True})
+
+ @fastapi_app.post("/api/restart")
+ async def restart_game():
+ """Restart the game."""
+ if state.running and state.router_task:
+ state.running = False
+ state.router_task.cancel()
+ try:
+ await state.router_task
+ except asyncio.CancelledError:
+ pass
+ state.router_task = None
+
+ # Generate new session ID and clear messages
+ state.session_id = generate_session_id()
+ state.messages.clear()
+ state.game_ended = False
+ state.force_restarted = True
+
+ if "god" not in state.channels:
+ return JSONResponse(content={"success": False, "error": "god channel not found"})
+
+ # Build restart message with player info and workspace
+ player_list = []
+ player_idx = 1
+ bot_workspace = state.storage_path / "bot" / "workspace"
+ for ch in state.channels:
+ if ch != "god" and player_idx <= 8:
+ player_list.append(f"{player_idx}号: {ch},GAME.md地址:{bot_workspace}/bot_api__{ch}/GAME.md")
+ player_idx += 1
+
+ restart_message = f"""重新开始游戏
+
+游戏配置:
+- 玩家数: {len(player_list)}
+- 玩家列表:
+{chr(10).join(f' - {p}' for p in player_list)}
+- GAME_RECORD.md 位置:{bot_workspace}/bot_api__god/GAME_RECORD.md
+- 对话记录位置:{bot_workspace}/werewolf/CONVERSATION_{state.session_id}.md
+
+请初始化游戏文件,然后等待"开始"指令。"""
+
+ state.running = True
+ state.router_task = asyncio.create_task(
+ message_router_loop(state, initial_channel="god", initial_message=restart_message)
+ )
+ return JSONResponse(content={"success": True, "session_id": state.session_id})
+
+ @fastapi_app.post("/api/stop")
+ async def stop_game():
+ """Stop the game."""
+ if not state.running:
+ return JSONResponse(content={"success": False, "error": "Game not running"})
+
+ state.running = False
+ if state.router_task:
+ state.router_task.cancel()
+ try:
+ await state.router_task
+ except asyncio.CancelledError:
+ pass
+ state.router_task = None
+
+ return JSONResponse(content={"success": True})
+
+ @fastapi_app.get("/api/openviking/tree")
+ async def get_openviking_tree():
+ """Get OpenViking memory directory tree structure.
+
+ Returns the tree structure of:
+ - {viking_path}/default/agent/
+ - {viking_path}/default/user/
+ """
+ viking_path = get_viking_path(state.config)
+ default_path = viking_path / "default"
+
+ tree = {
+ "agent": {"path": str(default_path / "agent"), "files": []},
+ "user": {"path": str(default_path / "user"), "files": []}
+ }
+
+ # Scan agent directory
+ agent_path = default_path / "agent"
+ if agent_path.exists():
+ tree["agent"]["files"] = scan_directory_tree(agent_path, "")
+
+ # Scan user directory
+ user_path = default_path / "user"
+ if user_path.exists():
+ tree["user"]["files"] = scan_directory_tree(user_path, "")
+
+ return JSONResponse(content=tree)
+
+ @fastapi_app.get("/api/openviking/file")
+ async def get_openviking_file(path: str):
+ """Get a specific file from OpenViking memory.
+
+ Path format: "agent/subpath/file.md" or "user/subpath/file.md"
+ """
+ viking_path = get_viking_path(state.config)
+ file_path = viking_path / "default" / path
+
+ if not file_path.exists():
+ return JSONResponse(content={"error": "File not found"}, status_code=404)
+
+ if file_path.is_dir():
+ return JSONResponse(content={"error": "Path is a directory"}, status_code=400)
+
+ try:
+ content = file_path.read_text(encoding="utf-8")
+ return JSONResponse(content={
+ "path": path,
+ "content": content,
+ "name": file_path.name
+ })
+ except Exception as e:
+ return JSONResponse(content={"error": str(e)}, status_code=500)
+
+ @fastapi_app.get("/api/conversations")
+ async def get_conversations():
+ """Get list of conversation files."""
+ bot_workspace = state.storage_path / "bot" / "workspace" / "werewolf"
+
+ if not bot_workspace.exists():
+ return JSONResponse(content={"files": []})
+
+ conversation_files = sorted(
+ bot_workspace.glob("CONVERSATION_*.md"),
+ key=lambda p: p.stat().st_mtime,
+ reverse=True
+ )
+
+ files = []
+ for f in conversation_files:
+ session_id = f.stem.replace("CONVERSATION_", "")
+ files.append({
+ "session_id": session_id,
+ "filename": f.name,
+ "modified": f.stat().st_mtime,
+ "size": f.stat().st_size
+ })
+
+ return JSONResponse(content={"files": files, "current_session_id": state.session_id})
+
+ @fastapi_app.get("/api/conversation/{session_id}")
+ async def get_conversation(session_id: str):
+ """Get a specific conversation file content."""
+ bot_workspace = state.storage_path / "bot" / "workspace" / "werewolf"
+ file_path = bot_workspace / f"CONVERSATION_{session_id}.md"
+
+ if not file_path.exists():
+ return JSONResponse(content={"error": "Conversation not found"}, status_code=404)
+
+ try:
+ content = file_path.read_text(encoding="utf-8")
+ return JSONResponse(content={
+ "session_id": session_id,
+ "content": content,
+ "filename": file_path.name
+ })
+ except Exception as e:
+ return JSONResponse(content={"error": str(e)}, status_code=500)
+
+ @fastapi_app.get("/api/bot-sessions")
+ async def get_bot_sessions():
+ """Get list of bot session files."""
+ sessions_path = state.storage_path / "bot" / "sessions"
+
+ if not sessions_path.exists():
+ return JSONResponse(content={"files": [], "current_session_id": state.session_id})
+
+ session_files = sorted(
+ sessions_path.glob("bot_api__*.jsonl"),
+ key=lambda p: p.stat().st_mtime,
+ reverse=True
+ )
+
+ files = []
+ for f in session_files:
+ # Parse filename: bot_api__player_1__20260331_203954.jsonl
+ parts = f.stem.split("__")
+ if len(parts) >= 3:
+ channel_id = parts[1]
+ file_session_id = "__".join(parts[2:])
+ else:
+ channel_id = "unknown"
+ file_session_id = f.stem
+
+ files.append({
+ "channel_id": channel_id,
+ "session_id": file_session_id,
+ "filename": f.name,
+ "modified": f.stat().st_mtime,
+ "size": f.stat().st_size
+ })
+
+ return JSONResponse(content={"files": files, "current_session_id": state.session_id})
+
+ @fastapi_app.get("/api/bot-session/{filename}")
+ async def get_bot_session(filename: str):
+ """Get a specific bot session file content."""
+ sessions_path = state.storage_path / "bot" / "sessions"
+ file_path = sessions_path / filename
+
+ if not file_path.exists():
+ return JSONResponse(content={"error": "Session file not found"}, status_code=404)
+
+ try:
+ lines = file_path.read_text(encoding="utf-8").splitlines()
+ # Format JSONL as readable text
+ formatted_lines = []
+ for line in lines:
+ if line.strip():
+ try:
+ data = json.loads(line)
+ if data.get("_type") == "metadata":
+ formatted_lines.append(f"# 会话元数据\n")
+ formatted_lines.append(f"- 创建时间: {data.get('created_at', '')}")
+ formatted_lines.append(f"- 更新时间: {data.get('updated_at', '')}")
+ formatted_lines.append("")
+ else:
+ role = data.get("role", "")
+ content = data.get("content", "")
+ timestamp = data.get("timestamp", "")
+ sender = data.get("sender_id", "")
+
+ if role == "user":
+ formatted_lines.append(f"## <user> ({sender}) - {timestamp}")
+ elif role == "assistant":
+ formatted_lines.append(f"## <assistant> ({sender}) - {timestamp}")
+ else:
+ formatted_lines.append(f"## {role} - {timestamp}")
+
+ formatted_lines.append("")
+ formatted_lines.append(content)
+
+ # Add token usage if available
+ token_usage = data.get("token_usage")
+ if token_usage:
+ formatted_lines.append("")
+ formatted_lines.append(f"*Token使用: prompt={token_usage.get('prompt_tokens', 0)}, completion={token_usage.get('completion_tokens', 0)}, total={token_usage.get('total_tokens', 0)}*")
+
+ formatted_lines.append("")
+ except json.JSONDecodeError:
+ formatted_lines.append(line)
+
+ content = "\n".join(formatted_lines)
+ return JSONResponse(content={
+ "filename": filename,
+ "content": content,
+ "raw_content": file_path.read_text(encoding="utf-8")
+ })
+ except Exception as e:
+ return JSONResponse(content={"error": str(e)}, status_code=500)
+
+ @fastapi_app.get("/api/game-file/{channel_id}/{filename}")
+ async def get_game_file(channel_id: str, filename: str):
+ """Get a game file (GAME.md or GAME_RECORD.md) for a channel."""
+ bot_workspace = state.storage_path / "bot" / "workspace"
+
+ if channel_id == "god" and filename == "GAME_RECORD.md":
+ file_path = bot_workspace / "bot_api__god" / "GAME_RECORD.md"
+ else:
+ file_path = bot_workspace / f"bot_api__{channel_id}" / filename
+
+ if not file_path.exists():
+ return JSONResponse(content={"error": "File not found"}, status_code=404)
+
+ try:
+ content = file_path.read_text(encoding="utf-8")
+ return JSONResponse(content={
+ "channel_id": channel_id,
+ "filename": filename,
+ "content": content
+ })
+ except Exception as e:
+ return JSONResponse(content={"error": str(e)}, status_code=500)
+
+ def get_leaderboard_path() -> Path:
+ """Get the path to the leaderboard file."""
+ leaderboard_dir = state.storage_path / "bot" / "workspace" / "werewolf"
+ leaderboard_dir.mkdir(parents=True, exist_ok=True)
+ return leaderboard_dir / "LEADERBOARD.json"
+
+ def load_leaderboard() -> Dict[str, Any]:
+ """Load leaderboard data from file."""
+ leaderboard_path = get_leaderboard_path()
+ if leaderboard_path.exists():
+ try:
+ return json.loads(leaderboard_path.read_text(encoding="utf-8"))
+ except Exception:
+ pass
+ return {"games": [], "players": {}}
+
+ def save_leaderboard(data: Dict[str, Any]):
+ """Save leaderboard data to file."""
+ leaderboard_path = get_leaderboard_path()
+ leaderboard_path.write_text(json.dumps(data, ensure_ascii=False, indent=2), encoding="utf-8")
+
+ @fastapi_app.get("/api/leaderboard")
+ async def get_leaderboard():
+ """Get leaderboard data."""
+ return JSONResponse(content=load_leaderboard())
+
+ @fastapi_app.post("/api/leaderboard/save")
+ async def save_game_to_leaderboard(game_data: Dict[str, Any]):
+ """Save a completed game to leaderboard."""
+ leaderboard = load_leaderboard()
+
+ # Add game record
+ game_record = {
+ "session_id": game_data.get("session_id", state.session_id),
+ "timestamp": time.time(),
+ "winner": game_data.get("winner", ""),
+ "players": game_data.get("players", [])
+ }
+ leaderboard["games"].append(game_record)
+
+ # Update player stats
+ players_data = game_data.get("players", [])
+ for player in players_data:
+ player_id = player.get("id", "")
+ if not player_id:
+ continue
+
+ if player_id not in leaderboard["players"]:
+ leaderboard["players"][player_id] = {
+ "id": player_id,
+ "games_played": 0,
+ "games_won": 0,
+ "total_score": 0,
+ "roles": {}
+ }
+
+ player_stats = leaderboard["players"][player_id]
+ player_stats["games_played"] += 1
+
+ if player.get("won", False):
+ player_stats["games_won"] += 1
+
+ player_stats["total_score"] += player.get("score", 0)
+
+ role = player.get("role", "未知")
+ if role not in player_stats["roles"]:
+ player_stats["roles"][role] = 0
+ player_stats["roles"][role] += 1
+
+ save_leaderboard(leaderboard)
+ return JSONResponse(content={"success": True, "leaderboard": leaderboard})
+
+ def scan_directory_tree(root_path: Path, relative_path: str) -> List[Dict[str, Any]]:
+ """Recursively scan a directory and build a tree structure."""
+ result = []
+
+ try:
+ for item in sorted(root_path.iterdir()):
+ if item.name.startswith('.') and item.is_file():
+ # Skip hidden files but include .abstract.md and .overview.md
+ if item.name not in ['.abstract.md', '.overview.md']:
+ continue
+
+ item_rel_path = f"{relative_path}/{item.name}" if relative_path else item.name
+
+ if item.is_dir():
+ result.append({
+ "name": item.name,
+ "path": item_rel_path,
+ "type": "directory",
+ "children": scan_directory_tree(item, item_rel_path)
+ })
+ else:
+ result.append({
+ "name": item.name,
+ "path": item_rel_path,
+ "type": "file",
+ "size": item.stat().st_size
+ })
+ except Exception as e:
+ logger.warning(f"Error scanning directory {root_path}: {e}")
+
+ return result
+
+ @fastapi_app.get("/data/{path:path}")
+ async def serve_data_file(path: str):
+ """Serve files from storage folder.
+
+ Priority:
+ 1. /data/ -> list bot/workspace/
+ 2. /data/werewolf/GAME_RECORD.md -> bot_api__god/GAME_RECORD.md
+ 3. /data/* -> bot/workspace/*
+ 4. /data/* -> storage_path/*
+ """
+ bot_workspace = state.storage_path / "bot" / "workspace"
+
+ # Special case: root path - list bot/workspace
+ if path == "" or path == "/":
+ return await list_directory(bot_workspace, "")
+
+ # Special handling for werewolf/GAME_RECORD.md - map to god's GAME_RECORD.md
+ if path == "werewolf/GAME_RECORD.md":
+ god_record_path = bot_workspace / "bot_api__god" / "GAME_RECORD.md"
+ if god_record_path.exists():
+ return FileResponse(god_record_path)
+
+ # First try: bot/workspace/{path}
+ workspace_path = bot_workspace / path
+ if workspace_path.exists():
+ if workspace_path.is_file():
+ return FileResponse(workspace_path)
+ elif workspace_path.is_dir():
+ return await list_directory(workspace_path, path)
+
+ # Second try: storage_path/{path}
+ file_path = state.storage_path / path
+ if file_path.exists() and file_path.is_file():
+ return FileResponse(file_path)
+
+ dir_path = state.storage_path / path
+ if dir_path.exists() and dir_path.is_dir():
+ return await list_directory(dir_path, path)
+
+ return HTMLResponse(content="", media_type="text/markdown", status_code=404)
+
+ async def list_directory(dir_path: Path, url_path: str):
+ """Generate a simple HTML directory listing."""
+ entries = []
+ for item in sorted(dir_path.iterdir()):
+ name = item.name
+ if item.is_dir():
+ name += "/"
+ entries.append(f'<a href="{url_path.rstrip("/")}/{name}">{name}</a><br>')
+
+ html = f"""
+ <!DOCTYPE html>
+ <html><body>
+ <h1>/{url_path}</h1>
+ {'<a href="../">../</a><br>' if url_path else ''}
+ {''.join(entries)}
+ </body></html>
+ """
+ return HTMLResponse(content=html)
+
+ return fastapi_app
+
+
+# ============================================================================
+# Main Command
+# ============================================================================
+
+
+def main(
+ port: int = typer.Option(1995, "--port", "-p", help="UI port"),
+ vikingbot_url: str = typer.Option(
+ "http://localhost:18790",
+ "--vikingbot-url",
+ help="Vikingbot API URL"
+ ),
+ config_path: str = typer.Option(
+ "~/.openviking/ov-multi.conf",
+ "--config",
+ "-c",
+ help="Config file path"
+ ),
+ game_id: str = typer.Option("default", "--game-id", help="Game ID"),
+ smart_buttons: bool = typer.Option(False, "--smart-buttons", "-s", help="Enable smart button visibility control"),
+ game_mode: str = typer.Option("all_agents", "--game-mode", "-m", help="Game mode: all_agents or human_player"),
+):
+ """Start the werewolf game server."""
+ import uvicorn
+
+ config_path_resolved = Path(config_path).expanduser()
+
+ logger.info(f"Loading config from {config_path_resolved}")
+ config = load_config(config_path_resolved)
+ channels = get_bot_channels(config)
+ logger.info(f"Loaded channels: {channels}")
+
+ storage_path = get_storage_path(config)
+ logger.info(f"Storage path: {storage_path}")
+
+ has_human_player = game_mode == "human_player"
+ human_channel = "human"
+ if has_human_player:
+ # Remove last bot player and add human
+ if len(channels) > 1 and "god" in channels:
+ # Keep god and remove the last player
+ non_god_channels = [ch for ch in channels if ch != "god"]
+ if len(non_god_channels) > 0:
+ channels = ["god"] + non_god_channels[:-1]
+ channels.append(human_channel)
+ logger.info(f"Human player mode enabled. Channels: {channels}")
+
+ # Create human player GAME.md
+ human_workspace = storage_path / "bot" / "workspace" / "human"
+ human_workspace.mkdir(parents=True, exist_ok=True)
+ human_game_md = human_workspace / "GAME.md"
+ if not human_game_md.exists():
+ human_game_md.write_text("# 真实玩家游戏文件\n\n请编辑此文件来设置你的角色和状态。\n", encoding="utf-8")
+ logger.info(f"Human player GAME.md at: {human_game_md}")
+
+ init_ui_files(storage_path, channels, game_id)
+
+ # Load latest conversation from previous session
+ previous_messages = []
+ previous_session_id = None
+ try:
+ previous_messages, previous_session_id = load_latest_conversation(storage_path)
+ except Exception as e:
+ logger.exception(f"Error loading previous conversation: {e}")
+
+ # Generate initial session ID, or use previous one if available
+ if previous_session_id:
+ initial_session_id = previous_session_id
+ logger.info(f"Using previous session ID: {initial_session_id}")
+ else:
+ initial_session_id = generate_session_id()
+ logger.info(f"Generated new session ID: {initial_session_id}")
+
+ state = GameState(
+ game_id=game_id,
+ vikingbot_url=vikingbot_url,
+ config_path=config_path_resolved,
+ channels=channels,
+ config=config,
+ storage_path=storage_path,
+ session_id=initial_session_id,
+ )
+
+ # Store smart_buttons in config for easy access
+ state.config["smart_buttons"] = smart_buttons
+ state.has_human_player = has_human_player
+ state.human_player_channel = human_channel
+
+ # Load messages if available
+ if previous_messages:
+ state.messages.extend(previous_messages)
+ logger.info(f"Loaded {len(previous_messages)} messages from previous session")
+
+ fastapi_app = create_fastapi_app(state)
+
+ logger.info(f"Starting Werewolf Server on port {port}")
+ logger.info(f"UI will be available at http://localhost:{port}")
+ logger.info(f"Storage path: {storage_path}")
+ logger.info(f"Bot workspace: {storage_path / 'bot' / 'workspace'}")
+ logger.info(f"Checking for GAME_RECORD.md: {storage_path / 'bot' / 'workspace' / 'bot_api__god' / 'GAME_RECORD.md'}")
+
+ uvicorn.run(
+ fastapi_app,
+ host="0.0.0.0",
+ port=port,
+ log_level="warning",
+ access_log=False,
+ )
+
+
+if __name__ == "__main__":
+ typer.run(main)
diff --git a/bot/vikingbot/agent/loop.py b/bot/vikingbot/agent/loop.py
index da980552e..2bfef8e51 100644
--- a/bot/vikingbot/agent/loop.py
+++ b/bot/vikingbot/agent/loop.py
@@ -479,6 +479,16 @@ class AgentLoop:
await self.sessions.save(session)
return None
+ if not msg.need_reply:
+ session.add_message("user", msg.content, sender_id=msg.sender_id)
+ await self.sessions.save(session)
+ return OutboundMessage(
+ session_key=msg.session_key,
+ content=None,
+ metadata=msg.metadata,
+ event_type=OutboundEventType.NO_REPLY,
+ )
+
# Consolidate memory before processing if session is too large
if len(session.messages) > self.memory_window:
# Clone session for async consolidation, then immediately trim original
diff --git a/bot/vikingbot/bus/events.py b/bot/vikingbot/bus/events.py
index b14b67ecb..fb2f03c1c 100644
--- a/bot/vikingbot/bus/events.py
+++ b/bot/vikingbot/bus/events.py
@@ -16,6 +16,7 @@ class OutboundEventType(str, Enum):
TOOL_RESULT = "tool_result" # Result from tool execution
REASONING = "reasoning" # Reasoning content
ITERATION = "iteration" # Iteration marker
+ NO_REPLY = "no_reply" # No reply required
@dataclass
@@ -26,6 +27,7 @@ class InboundMessage:
content: str # Message text
session_key: SessionKey
timestamp: datetime = field(default_factory=datetime.now)
+ need_reply: bool = True
media: list[str] = field(default_factory=list) # Media URLs
metadata: dict[str, Any] = field(default_factory=dict) # Channel-specific data
diff --git a/bot/vikingbot/channels/botchannel.py b/bot/vikingbot/channels/botchannel.py
new file mode 100644
index 000000000..61f211402
--- /dev/null
+++ b/bot/vikingbot/channels/botchannel.py
@@ -0,0 +1,9 @@
+"""Bot Channel configuration.
+
+BotChannel functionality is now integrated into OpenAPIChannel.
+This file keeps the BotChannelConfig for backward compatibility.
+"""
+
+from vikingbot.config.schema import BotChannelConfig
+
+__all__ = ["BotChannelConfig"]
diff --git a/bot/vikingbot/channels/feishu_test.py b/bot/vikingbot/channels/feishu_test.py
new file mode 100644
index 000000000..a77b026a8
--- /dev/null
+++ b/bot/vikingbot/channels/feishu_test.py
@@ -0,0 +1,35 @@
+import json
+
+import lark_oapi as lark
+from lark_oapi.api.contact.v3 import *
+
+
+def main():
+ # 创建client
+ client = lark.Client.builder() \
+ .app_id("") \
+ .app_secret("") \
+ .log_level(lark.LogLevel.DEBUG) \
+ .build()
+
+ # 构造请求对象
+ request: GetUserRequest = GetUserRequest.builder() \
+ .user_id("") \
+ .user_id_type("open_id") \
+ .build()
+
+ # 发起请求
+ response: GetUserResponse = client.contact.v3.user.get(request)
+
+ # 处理失败返回
+ if not response.success():
+ lark.logger.error(
+ f"client.contact.v3.user.get failed, code: {response.code}, msg: {response.msg}, log_id: {response.get_log_id()}, resp: \n{json.dumps(json.loads(response.raw.content), indent=4, ensure_ascii=False)}")
+ return
+
+ # 处理业务结果
+ lark.logger.info(lark.JSON.marshal(response.data, indent=4))
+
+
+if __name__ == "__main__":
+ main()
diff --git a/bot/vikingbot/channels/manager.py b/bot/vikingbot/channels/manager.py
index 93a3aaa42..97c805915 100644
--- a/bot/vikingbot/channels/manager.py
+++ b/bot/vikingbot/channels/manager.py
@@ -226,6 +226,26 @@ class ChannelManager:
await channel.send(msg)
except Exception as e:
logger.exception(f"Error sending to {msg.session_key}: {e}")
+ elif msg.session_key.type == "bot_api":
+ # For bot_api messages, find any channel that can handle it
+ # (typically OpenAPIChannel which integrates BotChannel functionality)
+ handled = False
+ for ch in self.channels.values():
+ # Check if channel has a send method and can handle bot_api messages
+ # OpenAPIChannel identifies itself with name "openapi" and handles bot_api
+ if hasattr(ch, 'name') and ch.name == "openapi":
+ try:
+ await ch.send(msg)
+ handled = True
+ break
+ except Exception as e:
+ logger.exception(f"Error sending bot_api message to {ch.name}: {e}")
+ handled = True
+ break
+ if not handled:
+ logger.warning(
+ f"No channel found to handle bot_api message: {msg.session_key}. Available: {list(self.channels.keys())}"
+ )
else:
logger.warning(
f"Unknown channel: {msg.session_key}. Available: {list(self.channels.keys())}"
diff --git a/bot/vikingbot/channels/openapi.py b/bot/vikingbot/channels/openapi.py
index bcc70f47b..c97238a6e 100644
--- a/bot/vikingbot/channels/openapi.py
+++ b/bot/vikingbot/channels/openapi.py
@@ -26,21 +26,12 @@ from vikingbot.channels.openapi_models import (
SessionInfo,
SessionListResponse,
)
-from vikingbot.config.schema import BaseChannelConfig, Config, SessionKey
-
-
-class OpenAPIChannelConfig(BaseChannelConfig):
- """Configuration for OpenAPI channel."""
-
- enabled: bool = True
- type: str = "cli"
- api_key: str = "" # If empty, no auth required
- allow_from: list[str] = []
- max_concurrent_requests: int = 100
- _channel_id: str = "default"
-
- def channel_id(self) -> str:
- return self._channel_id
+from vikingbot.config.schema import (
+ BaseChannelConfig,
+ Config,
+ SessionKey,
+ BotChannelConfig,
+)
class PendingResponse:
@@ -68,6 +59,20 @@ class PendingResponse:
await self.stream_queue.put(None)
+class OpenAPIChannelConfig(BaseChannelConfig):
+ """Configuration for OpenAPI channel."""
+
+ enabled: bool = True
+ type: str = "cli"
+ api_key: str = "" # If empty, no auth required
+ allow_from: list[str] = []
+ max_concurrent_requests: int = 100
+ _channel_id: str = "default"
+
+ def channel_id(self) -> str:
+ return self._channel_id
+
+
class OpenAPIChannel(BaseChannel):
"""
OpenAPI channel exposing HTTP endpoints for chat API.
@@ -83,15 +88,27 @@ class OpenAPIChannel(BaseChannel):
bus: MessageBus,
workspace_path: Path | None = None,
app: "FastAPI | None" = None,
+ global_config: Config | None = None,
):
super().__init__(config, bus, workspace_path)
self.config = config
+ self._global_config = global_config
+ # Regular OpenAPI pending and sessions
self._pending: Dict[str, PendingResponse] = {}
self._sessions: Dict[str, Dict[str, Any]] = {}
+ # BotChannel pending and sessions - key is channel_id
+ self._bot_pending: Dict[str, Dict[str, PendingResponse]] = {}
+ self._bot_sessions: Dict[str, Dict[str, Dict[str, Any]]] = {}
+ # BotChannel configs - key is channel_id
+ self._bot_configs: Dict[str, BotChannelConfig] = {}
self._router: Optional[APIRouter] = None
self._app = app # External FastAPI app to register routes on
self._server: Optional[asyncio.Task] = None # Server task
+ # Load BotChannel configurations immediately in constructor
+ # so that subscriptions are setup before ChannelManager starts
+ self._load_bot_channels()
+
async def start(self) -> None:
"""Start the channel - register routes to external FastAPI app if provided."""
self._running = True
@@ -108,13 +125,76 @@ class OpenAPIChannel(BaseChannel):
# Complete all pending responses
for pending in self._pending.values():
pending.set_final("")
+ # Complete all bot pending responses
+ for pending_dict in self._bot_pending.values():
+ for pending in pending_dict.values():
+ pending.set_final("")
logger.info("OpenAPI channel stopped")
+ def _load_bot_channels(self) -> None:
+ """Load all BotChannel configurations from the global config."""
+ if self._global_config is None:
+ logger.warning("No global config provided, cannot load BotChannels")
+ return
+
+ # Get all channel configs
+ channels_config = self._global_config.channels_config
+ all_channel_configs = channels_config.get_all_channels()
+
+ for ch_config in all_channel_configs:
+ if isinstance(ch_config, BotChannelConfig) or (
+ hasattr(ch_config, "type") and getattr(ch_config, "type", None) == "bot_api"
+ ):
+ if isinstance(ch_config, dict):
+ bot_config = BotChannelConfig(**ch_config)
+ else:
+ bot_config = ch_config
+
+ if not bot_config.enabled:
+ continue
+
+ channel_id = bot_config.channel_id()
+ self._bot_configs[channel_id] = bot_config
+ # Initialize pending and sessions for this channel
+ self._bot_pending[channel_id] = {}
+ self._bot_sessions[channel_id] = {}
+ logger.info(f"Loaded BotChannel config: {channel_id}")
+
+ # Instead of subscribing per channel, we'll check session type in send()
+ # This is simpler and avoids subscription timing issues
+
async def send(self, msg: OutboundMessage) -> None:
"""
Handle outbound messages - routes to pending responses.
This is called by the message bus dispatcher.
"""
+ # Check if this message is for a BotChannel
+ if msg.session_key.type == "bot_api":
+ channel_id = msg.session_key.channel_id
+ session_id = msg.session_key.chat_id
+
+ if channel_id not in self._bot_pending:
+ logger.warning(f"Unknown BotChannel: {channel_id}")
+ return
+
+ pending = self._bot_pending[channel_id].get(session_id)
+ if not pending:
+ logger.warning(f"No pending request for BotChannel {channel_id} session: {session_id}")
+ return
+
+ if msg.event_type == OutboundEventType.RESPONSE or msg.event_type == OutboundEventType.NO_REPLY:
+ await pending.add_event("response", msg.content or "")
+ pending.set_final(msg.content or "")
+ await pending.close_stream()
+ elif msg.event_type == OutboundEventType.REASONING:
+ await pending.add_event("reasoning", msg.content)
+ elif msg.event_type == OutboundEventType.TOOL_CALL:
+ await pending.add_event("tool_call", msg.content)
+ elif msg.event_type == OutboundEventType.TOOL_RESULT:
+ await pending.add_event("tool_result", msg.content)
+ return
+
+ # Handle as normal OpenAPIChannel message
session_id = msg.session_key.chat_id
pending = self._pending.get(session_id)
@@ -250,6 +330,58 @@ class OpenAPIChannel(BaseChannel):
del channel._sessions[session_id]
return {"deleted": True}
+ # ========== Bot Channel Routes ==========
+
+ async def verify_bot_channel_api_key(x_api_key: Optional[str] = Header(None)) -> Optional[str]:
+ """Verify API key and return it if valid."""
+ return x_api_key
+
+ @router.post("/chat/channel", response_model=ChatResponse)
+ async def chat_channel(
+ request: ChatRequest,
+ x_api_key: Optional[str] = Depends(verify_bot_channel_api_key),
+ ):
+ """Send a chat message to a specific bot channel and get a response."""
+ channel_id = request.channel_id
+ if not channel_id:
+ raise HTTPException(status_code=400, detail="channel_id is required")
+ if channel_id not in channel._bot_configs:
+ raise HTTPException(status_code=404, detail=f"Channel '{channel_id}' not found")
+
+ # Verify API key for the specific channel
+ bot_config = channel._bot_configs[channel_id]
+ if bot_config.api_key:
+ if not x_api_key:
+ raise HTTPException(status_code=401, detail="X-API-Key header required")
+ if not secrets.compare_digest(x_api_key, bot_config.api_key):
+ raise HTTPException(status_code=403, detail="Invalid API key")
+
+ return await channel._handle_bot_chat(channel_id, request)
+
+ @router.post("/chat/channel/stream")
+ async def chat_channel_stream(
+ request: ChatRequest,
+ x_api_key: Optional[str] = Depends(verify_bot_channel_api_key),
+ ):
+ """Send a chat message to a specific bot channel and get a streaming response."""
+ channel_id = request.channel_id
+ if not channel_id:
+ raise HTTPException(status_code=400, detail="channel_id is required")
+ if channel_id not in channel._bot_configs:
+ raise HTTPException(status_code=404, detail=f"Channel '{channel_id}' not found")
+
+ # Verify API key for the specific channel
+ bot_config = channel._bot_configs[channel_id]
+ if bot_config.api_key:
+ if not x_api_key:
+ raise HTTPException(status_code=401, detail="X-API-Key header required")
+ if not secrets.compare_digest(x_api_key, bot_config.api_key):
+ raise HTTPException(status_code=403, detail="Invalid API key")
+
+ if not request.stream:
+ request.stream = True
+ return await channel._handle_bot_chat_stream(channel_id, request)
+
return router
def _setup_routes(self) -> None:
@@ -400,6 +532,154 @@ class OpenAPIChannel(BaseChannel):
},
)
+ async def _handle_bot_chat(self, channel_id: str, request: ChatRequest) -> ChatResponse:
+ """Handle a BotChannel chat request."""
+ # Generate or use provided session ID
+ session_id = request.session_id or str(uuid.uuid4())
+ user_id = request.user_id or "anonymous"
+
+ # Ensure channel has session storage
+ if channel_id not in self._bot_sessions:
+ self._bot_sessions[channel_id] = {}
+
+ # Create session if new
+ if session_id not in self._bot_sessions[channel_id]:
+ self._bot_sessions[channel_id][session_id] = {
+ "user_id": user_id,
+ "created_at": datetime.now(),
+ "last_active": datetime.now(),
+ "message_count": 0,
+ "messages": [],
+ }
+
+ # Update session activity
+ self._bot_sessions[channel_id][session_id]["last_active"] = datetime.now()
+ self._bot_sessions[channel_id][session_id]["message_count"] += 1
+
+ # Create pending response tracker
+ pending = PendingResponse()
+ self._bot_pending[channel_id][session_id] = pending
+
+ try:
+ # Build session key with bot_api type
+ session_key = SessionKey(
+ type="bot_api",
+ channel_id=channel_id,
+ chat_id=session_id,
+ )
+
+ # Build content with context if provided
+ content = request.message
+ if request.context:
+ # Context is handled separately by session manager
+ pass
+
+ # Create and publish inbound message
+ msg = InboundMessage(
+ session_key=session_key,
+ sender_id=user_id,
+ content=content,
+ need_reply=request.need_reply,
+ )
+
+ await self.bus.publish_inbound(msg)
+
+ # Wait for response with timeout
+ try:
+ await asyncio.wait_for(pending.event.wait(), timeout=300.0)
+ except asyncio.TimeoutError:
+ raise HTTPException(status_code=504, detail="Request timeout")
+
+ # Build response
+ response_content = pending.final_content or ""
+
+ return ChatResponse(
+ session_id=session_id,
+ message=response_content,
+ events=pending.events if pending.events else None,
+ )
+
+ except HTTPException:
+ raise
+ except Exception as e:
+ logger.exception(f"Error handling bot chat request for channel {channel_id}: {e}")
+ raise HTTPException(status_code=500, detail=f"Internal error: {str(e)}")
+ finally:
+ # Clean up pending
+ if channel_id in self._bot_pending:
+ self._bot_pending[channel_id].pop(session_id, None)
+
+ async def _handle_bot_chat_stream(self, channel_id: str, request: ChatRequest) -> StreamingResponse:
+ """Handle a BotChannel streaming chat request."""
+ session_id = request.session_id or str(uuid.uuid4())
+ user_id = request.user_id or "anonymous"
+
+ # Ensure channel has session storage
+ if channel_id not in self._bot_sessions:
+ self._bot_sessions[channel_id] = {}
+
+ # Create session if new
+ if session_id not in self._bot_sessions[channel_id]:
+ self._bot_sessions[channel_id][session_id] = {
+ "user_id": user_id,
+ "created_at": datetime.now(),
+ "last_active": datetime.now(),
+ "message_count": 0,
+ "messages": [],
+ }
+
+ self._bot_sessions[channel_id][session_id]["last_active"] = datetime.now()
+ self._bot_sessions[channel_id][session_id]["message_count"] += 1
+
+ pending = PendingResponse()
+ self._bot_pending[channel_id][session_id] = pending
+
+ async def event_generator():
+ try:
+ # Build session key with bot_api type
+ session_key = SessionKey(
+ type="bot_api",
+ channel_id=channel_id,
+ chat_id=session_id,
+ )
+
+ msg = InboundMessage(
+ session_key=session_key,
+ sender_id=user_id,
+ content=request.message,
+ )
+
+ await self.bus.publish_inbound(msg)
+
+ # Stream events as they arrive
+ while True:
+ try:
+ event = await asyncio.wait_for(pending.stream_queue.get(), timeout=300.0)
+ if event is None:
+ break
+ yield f"data: {event.model_dump_json()}\n\n"
+ except asyncio.TimeoutError:
+ yield f"data: {ChatStreamEvent(event=EventType.RESPONSE, data={'error': 'timeout'}).model_dump_json()}\n\n"
+ break
+
+ except Exception as e:
+ logger.exception(f"Error in bot stream generator for channel {channel_id}: {e}")
+ error_event = ChatStreamEvent(event=EventType.RESPONSE, data={"error": str(e)})
+ yield f"data: {error_event.model_dump_json()}\n\n"
+ finally:
+ # Clean up pending
+ if channel_id in self._bot_pending:
+ self._bot_pending[channel_id].pop(session_id, None)
+
+ return StreamingResponse(
+ event_generator(),
+ media_type="text/event-stream",
+ headers={
+ "Cache-Control": "no-cache",
+ "Connection": "keep-alive",
+ },
+ )
+
def get_openapi_router(bus: MessageBus, config: Config) -> APIRouter:
"""
@@ -410,7 +690,9 @@ def get_openapi_router(bus: MessageBus, config: Config) -> APIRouter:
"""
# Find OpenAPI config from channels
openapi_config = None
+
for ch_config in config.channels:
+ # Check for OpenAPI config
if isinstance(ch_config, dict) and ch_config.get("type") == "openapi":
openapi_config = OpenAPIChannelConfig(**ch_config)
break
@@ -422,17 +704,27 @@ def get_openapi_router(bus: MessageBus, config: Config) -> APIRouter:
# Create default config
openapi_config = OpenAPIChannelConfig()
- # Create channel and get router
+ # Create channel and get router - pass global config for BotChannel loading
channel = OpenAPIChannel(
config=openapi_config,
bus=bus,
workspace_path=config.workspace_path,
+ global_config=config,
)
# Register channel's send method as subscriber for outbound messages
+ # Subscribe to cli type
bus.subscribe_outbound(
f"cli__{openapi_config.channel_id()}",
channel.send,
)
+ # Subscribe to all bot_api channels that were loaded
+ for channel_id in channel._bot_configs.keys():
+ bus.subscribe_outbound(
+ f"bot_api__{channel_id}",
+ channel.send,
+ )
+ logger.info(f"Subscribed to bot_api channel: {channel_id}")
+
return channel.get_router()
\ No newline at end of file
diff --git a/bot/vikingbot/channels/openapi_models.py b/bot/vikingbot/channels/openapi_models.py
index eeaf3b537..bc0ef6087 100644
--- a/bot/vikingbot/channels/openapi_models.py
+++ b/bot/vikingbot/channels/openapi_models.py
@@ -48,6 +48,10 @@ class ChatRequest(BaseModel):
context: Optional[List[ChatMessage]] = Field(
default=None, description="Additional context messages"
)
+ need_reply: bool = True
+ channel_id: Optional[str] = Field(
+ default=None, description="Channel ID for multi-channel routing (optional)"
+ )
class ChatResponse(BaseModel):
diff --git a/bot/vikingbot/cli/commands.py b/bot/vikingbot/cli/commands.py
index 322d9093d..dcac8c3f6 100644
--- a/bot/vikingbot/cli/commands.py
+++ b/bot/vikingbot/cli/commands.py
@@ -440,6 +440,7 @@ def prepare_channel(
openapi_config,
bus,
app=fastapi_app, # Pass the external FastAPI app
+ global_config=config,
)
channels.add_channel(openapi_channel)
logger.info(f"OpenAPI channel enabled on port {openapi_port}")
diff --git a/bot/vikingbot/cli/werewolf_game.py b/bot/vikingbot/cli/werewolf_game.py
deleted file mode 100644
index c16896e63..000000000
--- a/bot/vikingbot/cli/werewolf_game.py
+++ /dev/null
@@ -1,2183 +0,0 @@
-"""CLI commands for vikingbot."""
-
-import asyncio
-from dataclasses import dataclass
-import json
-import os
-import random
-import re
-import select
-import sys
-import time
-import warnings
-from pathlib import Path
-from typing import Any
-
-import typer
-from loguru import logger
-from prompt_toolkit import PromptSession
-from prompt_toolkit.formatted_text import HTML
-from prompt_toolkit.history import FileHistory
-from prompt_toolkit.patch_stdout import patch_stdout
-from rich.console import Console
-from rich.markdown import Markdown
-from rich.table import Table
-from rich.text import Text
-
-from vikingbot import __logo__, __version__
-from vikingbot.agent.loop import AgentLoop
-from vikingbot.bus.queue import MessageBus
-from vikingbot.channels.manager import ChannelManager
-from vikingbot.config.loader import ensure_config, get_config_path, get_data_dir, load_config
-from vikingbot.config.schema import SessionKey
-from vikingbot.cron.service import CronService
-from vikingbot.cron.types import CronJob
-from vikingbot.heartbeat.service import HeartbeatService
-from vikingbot.integrations.langfuse import LangfuseClient
-
-# Create sandbox manager
-from vikingbot.sandbox.manager import SandboxManager
-from vikingbot.session.manager import SessionManager
-from vikingbot.utils.helpers import (
- get_bridge_path,
- get_history_path,
- get_source_workspace_path,
- set_bot_data_path,
-)
-
-# Ignore Pydantic V1 compatibility warning with Python 3.14+ from volcenginesdkarkruntime
-warnings.filterwarnings(
- "ignore",
- message="Core Pydantic V1 functionality isn't compatible with Python 3.14 or greater.",
- category=UserWarning,
- module="volcenginesdkarkruntime._compat",
-)
-
-app = typer.Typer(
- name="vikingbot",
- help=f"{__logo__} vikingbot - Personal AI Assistant",
- no_args_is_help=True,
-)
-
-console = Console()
-EXIT_COMMANDS = {"exit", "quit", "/exit", "/quit", ":q"}
-
-
-def get_or_create_machine_id() -> str:
- """Get a unique machine ID using py-machineid.
-
- Uses the system's machine ID, falls back to "default" if unavailable.
- """
- try:
- from machineid import machine_id
-
- return machine_id()
- except ImportError:
- # Fallback if py-machineid is not installed
- pass
- except Exception:
- pass
-
- # Default fallback
- return "default"
-
-
-def _init_bot_data(config):
- """Initialize bot data directory and set global paths."""
- set_bot_data_path(config.bot_data_path)
-
-
-# ---------------------------------------------------------------------------
-# CLI input: prompt_toolkit for editing, paste, history, and display
-# ---------------------------------------------------------------------------
-
-_PROMPT_SESSION: PromptSession | None = None
-_SAVED_TERM_ATTRS = None # original termios settings, restored on exit
-
-
-def _flush_pending_tty_input() -> None:
- """Drop unread keypresses typed while the model was generating output."""
- try:
- fd = sys.stdin.fileno()
- if not os.isatty(fd):
- return
- except Exception:
- return
-
- try:
- import termios
-
- termios.tcflush(fd, termios.TCIFLUSH)
- return
- except Exception:
- pass
-
- try:
- while True:
- ready, _, _ = select.select([fd], [], [], 0)
- if not ready:
- break
- if not os.read(fd, 4096):
- break
- except Exception:
- return
-
-
-def _restore_terminal() -> None:
- """Restore terminal to its original state (echo, line buffering, etc.)."""
- if _SAVED_TERM_ATTRS is None:
- return
- try:
- import termios
-
- termios.tcsetattr(sys.stdin.fileno(), termios.TCSADRAIN, _SAVED_TERM_ATTRS)
- except Exception:
- pass
-
-
-def _init_prompt_session() -> None:
- """Create the prompt_toolkit session with persistent file history."""
- global _PROMPT_SESSION, _SAVED_TERM_ATTRS
-
- # Save terminal state so we can restore it on exit
- try:
- import termios
-
- _SAVED_TERM_ATTRS = termios.tcgetattr(sys.stdin.fileno())
- except Exception:
- pass
-
- history_file = get_history_path() / "cli_history"
- history_file.parent.mkdir(parents=True, exist_ok=True)
-
- _PROMPT_SESSION = PromptSession(
- history=FileHistory(str(history_file)),
- enable_open_in_editor=False,
- multiline=False, # Enter submits (single line mode)
- )
-
-
-def _print_agent_response(response: str, render_markdown: bool) -> None:
- """Render assistant response with consistent terminal styling."""
- content = response or ""
- body = Markdown(content) if render_markdown else Text(content)
- console.print()
- console.print(f"[cyan]{__logo__} vikingbot[/cyan]")
- console.print(body)
- console.print()
-
-
-def _is_exit_command(command: str) -> bool:
- """Return True when input should end interactive chat."""
- return command.lower() in EXIT_COMMANDS
-
-
-async def _read_interactive_input_async() -> str:
- """Read user input using prompt_toolkit (handles paste, history, display).
-
- prompt_toolkit natively handles:
- - Multiline paste (bracketed paste mode)
- - History navigation (up/down arrows)
- - Clean display (no ghost characters or artifacts)
- """
- if _PROMPT_SESSION is None:
- raise RuntimeError("Call _init_prompt_session() first")
- try:
- with patch_stdout():
- return await _PROMPT_SESSION.prompt_async(
- HTML("<b fg='ansiblack'>You:</b> "),
- )
- except EOFError as exc:
- raise KeyboardInterrupt from exc
-
-
-def version_callback(value: bool):
- if value:
- console.print(f"{__logo__} vikingbot v{__version__}")
- raise typer.Exit()
-
-
-def main(
- version: bool = typer.Option(None, "--version", "-v", callback=version_callback, is_eager=True),
-):
- """vikingbot - Personal AI Assistant."""
- pass
-
-
-def _make_provider(config, langfuse_client: None = None):
- """Create LiteLLM provider from configuration."""
- from vikingbot.providers.litellm_provider import LiteLLMProvider
-
- p = config.agents
- model = p.model if p else None
- api_key = p.api_key if p else None
- api_base = p.api_base if p else None
- provider_name = p.provider if p else None
- extra_headers = p.extra_headers if p else {}
-
- if not model:
- raise RuntimeError("No LLM model configured. Please set it in ~/.openviking/ov.conf")
-
- if not api_key and not model.startswith("bedrock/"):
- console.print("[yellow]Warning: No API key configured.[/yellow]")
- console.print("You can configure providers later in the Console UI.")
-
- return LiteLLMProvider(
- api_key=api_key,
- api_base=api_base,
- default_model=model,
- extra_headers=extra_headers,
- provider_name=provider_name,
- langfuse_client=langfuse_client,
- )
-
-
-# ============================================================================
-# Gateway / Server
-# ============================================================================
-
-
-def gateway(
- port: int = typer.Option(18790, "--port", "-p", help="Gateway port"),
- # console_port: int = typer.Option(18791, "--console-port", help="Console web UI port"),
- enable_console: bool = typer.Option(
- True, "--console/--no-console", help="Enable console web UI"
- ),
- agent: bool = typer.Option(
- True, "--agent/--no-agent", help="Enable agent loop for OpenAPI/chat"
- ),
- verbose: bool = typer.Option(False, "--verbose", "-v", help="Verbose output"),
- config_path: str = typer.Option(None, "--config", "-c", help="ov.conf path"),
-):
- """Start the vikingbot gateway with OpenAPI chat enabled by default."""
-
- if verbose:
- import logging
-
- logging.basicConfig(level=logging.DEBUG)
-
- bus = MessageBus()
- path = Path(config_path).expanduser() if config_path is not None else None
- config = ensure_config(path)
- _init_bot_data(config)
- session_manager = SessionManager(config.bot_data_path)
-
- # Create FastAPI app for OpenAPI
- from fastapi import FastAPI
-
- fastapi_app = FastAPI(
- title="Vikingbot OpenAPI",
- description="HTTP API for Vikingbot chat",
- version="1.0.0",
- )
-
- cron = prepare_cron(bus)
- channels = prepare_channel(
- config, bus, fastapi_app=fastapi_app, enable_openapi=True, openapi_port=port
- )
- agent_loop = prepare_agent_loop(config, bus, session_manager, cron)
- heartbeat = prepare_heartbeat(config, agent_loop, session_manager)
-
- async def run():
- import uvicorn
-
- # Start uvicorn server for OpenAPI
- config_uvicorn = uvicorn.Config(
- fastapi_app,
- host="0.0.0.0",
- port=port,
- log_level="info",
- )
- server = uvicorn.Server(config_uvicorn)
-
- tasks = []
- tasks.append(cron.start())
- tasks.append(heartbeat.start())
- tasks.append(channels.start_all())
- tasks.append(agent_loop.run())
- tasks.append(server.serve()) # Start HTTP server
- # if enable_console:
- # tasks.append(start_console(console_port))
-
- await asyncio.gather(*tasks)
-
- asyncio.run(run())
-
-
-def prepare_agent_loop(config, bus, session_manager, cron, quiet: bool = False, eval: bool = False):
- sandbox_parent_path = config.workspace_path
- source_workspace_path = get_source_workspace_path()
- sandbox_manager = SandboxManager(config, sandbox_parent_path, source_workspace_path)
- if config.sandbox.backend == "direct":
- logger.warning("[SANDBOX] disabled (using DIRECT mode - commands run directly on host)")
- else:
- logger.info(
- f"Sandbox: enabled (backend={config.sandbox.backend}, mode={config.sandbox.mode})"
- )
-
- # Initialize Langfuse if enabled
- langfuse_client = None
- # logger.info(f"[LANGFUSE] Config check: has langfuse attr={hasattr(config, 'langfuse')}")
-
- if hasattr(config, "langfuse") and config.langfuse.enabled:
- langfuse_client = LangfuseClient(
- enabled=config.langfuse.enabled,
- secret_key=config.langfuse.secret_key,
- public_key=config.langfuse.public_key,
- base_url=config.langfuse.base_url,
- )
- LangfuseClient.set_instance(langfuse_client)
- if langfuse_client.enabled:
- logger.info(f"Langfuse: enabled (base_url={config.langfuse.base_url})")
- else:
- logger.warning("Langfuse: configured but failed to initialize")
-
- provider = _make_provider(config, langfuse_client)
- # Create agent with cron service
- agent = AgentLoop(
- bus=bus,
- provider=provider,
- workspace=config.workspace_path,
- model=config.agents.model,
- max_iterations=config.agents.max_tool_iterations,
- memory_window=config.agents.memory_window,
- brave_api_key=config.tools.web.search.api_key or None,
- exa_api_key=None,
- gen_image_model=config.agents.gen_image_model,
- exec_config=config.tools.exec,
- cron_service=cron,
- session_manager=session_manager,
- sandbox_manager=sandbox_manager,
- config=config,
- eval=eval,
- )
- # Set the agent reference in cron if it uses the holder pattern
- if hasattr(cron, "_agent_holder"):
- cron._agent_holder["agent"] = agent
- return agent
-
-
-def prepare_cron(bus, quiet: bool = False) -> CronService:
- # Create cron service first (callback set after agent creation)
- cron_store_path = get_data_dir() / "cron" / "jobs.json"
- cron = CronService(cron_store_path)
-
- # Use a mutable holder for the agent reference
- agent_holder = {"agent": None}
-
- # Set cron callback (needs agent)
- async def on_cron_job(job: CronJob) -> str | None:
- """Execute a cron job through the agent."""
- session_key = SessionKey(**json.loads(job.payload.session_key_str))
- message = job.payload.message
-
- if agent_holder["agent"] is None:
- raise RuntimeError("Agent not initialized yet")
-
- # Clear instructions: let agent know this is a cron task to deliver
- cron_instruction = f"""[CRON TASK]
-This is a scheduled task triggered by cron job: '{job.name}'
-Your task is to deliver the following reminder message to the user.
-
-IMPORTANT:
-- This is NOT a user message - it's a scheduled reminder you need to send
-- You should acknowledge/confirm the reminder and send it in a friendly way
-- DO NOT treat this as a question from the user
-- Simply deliver the reminder message as requested
-
-Reminder message to deliver:
-\"\"\"{message}\"\"\"
-"""
-
- response = await agent_holder["agent"].process_direct(
- cron_instruction,
- session_key=session_key,
- )
- if job.payload.deliver:
- from vikingbot.bus.events import OutboundMessage
-
- await bus.publish_outbound(
- OutboundMessage(
- session_key=session_key,
- content=response or "",
- )
- )
- return response
-
- cron.on_job = on_cron_job
- cron._agent_holder = agent_holder
-
- cron_status = cron.status()
- if cron_status["jobs"] > 0 and not quiet:
- logger.info(f"Cron: {cron_status['jobs']} scheduled jobs")
-
- return cron
-
-
-def prepare_channel(
- config, bus, fastapi_app=None, enable_openapi: bool = False, openapi_port: int = 18790
-):
- """Prepare channels for the bot.
-
- Args:
- config: Bot configuration
- bus: Message bus for communication
- fastapi_app: External FastAPI app to register OpenAPI routes on
- enable_openapi: Whether to enable OpenAPI channel for gateway mode
- openapi_port: Port for OpenAPI channel (default: 18790)
- """
- channels = ChannelManager(bus)
- channels.load_channels_from_config(config)
-
- # Enable OpenAPI channel for gateway mode if requested
- if enable_openapi and fastapi_app is not None:
- from vikingbot.channels.openapi import OpenAPIChannel, OpenAPIChannelConfig
-
- openapi_config = OpenAPIChannelConfig(
- enabled=True,
- port=openapi_port,
- api_key="", # No auth required by default
- )
- openapi_channel = OpenAPIChannel(
- openapi_config,
- bus,
- app=fastapi_app, # Pass the external FastAPI app
- )
- channels.add_channel(openapi_channel)
- logger.info(f"OpenAPI channel enabled on port {openapi_port}")
-
- if channels.enabled_channels:
- console.print(f"[green]✓[/green] Channels enabled: {', '.join(channels.enabled_channels)}")
- else:
- console.print("[yellow]Warning: No channels enabled[/yellow]")
- return channels
-
-
-def prepare_heartbeat(config, agent_loop, session_manager) -> HeartbeatService:
- # Create heartbeat service
- async def on_heartbeat(prompt: str, session_key: SessionKey | None = None) -> str:
- return await agent_loop.process_direct(
- prompt,
- session_key=session_key,
- )
-
- heartbeat = HeartbeatService(
- workspace=config.workspace_path,
- on_heartbeat=on_heartbeat,
- interval_s=config.heartbeat.interval_seconds,
- enabled=config.heartbeat.enabled,
- sandbox_mode=config.sandbox.mode,
- session_manager=session_manager,
- )
-
- console.print(
- f"[green]✓[/green] Heartbeat: every {config.heartbeat.interval_seconds}s"
- if config.heartbeat.enabled
- else "[yellow]✗[/yellow] Heartbeat: disabled"
- )
- return heartbeat
-
-
-async def start_console(console_port):
- """Start the console web UI in a separate thread within the same process."""
- try:
- import threading
-
- from vikingbot.console.console_gradio_simple import run_console_server
-
- def run_in_thread():
- try:
- run_console_server(console_port)
- except Exception as e:
- console.print(f"[yellow]Console server error: {e}[/yellow]")
-
- thread = threading.Thread(target=run_in_thread, daemon=True)
- thread.start()
- console.print(f"[green]✓[/green] Console: http://localhost:{console_port}")
- except Exception as e:
- console.print(f"[yellow]Warning: Console not available ({e})[/yellow]")
-
-
-# ============================================================================
-# Agent Commands
-# ============================================================================
-
-
-# Helper for thinking spinner context
-def _thinking_ctx(logs: bool):
- """Return a context manager for showing thinking spinner."""
- if logs:
- from contextlib import nullcontext
-
- return nullcontext()
- return console.status("[dim]vikingbot is thinking...[/dim]", spinner="dots")
-
-
-def prepare_agent_channel(
- config,
- bus,
- message: str | None,
- session_id: str,
- markdown: bool,
- logs: bool,
- eval: bool = False,
- sender: str | None = None,
-):
- """Prepare channel for agent command."""
- from vikingbot.channels.chat import ChatChannel, ChatChannelConfig
- from vikingbot.channels.single_turn import SingleTurnChannel, SingleTurnChannelConfig
-
- channels = ChannelManager(bus)
- if message is not None:
- # Single message mode - use SingleTurnChannel for clean output
- channel_config = SingleTurnChannelConfig()
- channel = SingleTurnChannel(
- channel_config,
- bus,
- workspace_path=config.workspace_path,
- message=message,
- session_id=session_id,
- markdown=markdown,
- eval=eval,
- sender=sender,
- )
- channels.add_channel(channel)
- else:
- # Interactive mode - use ChatChannel with thinking display
- channel_config = ChatChannelConfig()
- channel = ChatChannel(
- channel_config,
- bus,
- workspace_path=config.workspace_path,
- session_id=session_id,
- markdown=markdown,
- logs=logs,
- sender=sender,
- )
- channels.add_channel(channel)
-
- return channels
-
-
-def chat(
- message: str = typer.Option(None, "--message", "-m", help="Message to send to the agent"),
- session_id: str = typer.Option(None, "--session", "-s", help="Session ID"),
- markdown: bool = typer.Option(
- True, "--markdown/--no-markdown", help="Render assistant output as Markdown"
- ),
- logs: bool = typer.Option(
- False, "--logs/--no-logs", help="Show vikingbot runtime logs during chat"
- ),
- eval: bool = typer.Option(
- False, "--eval", "-e", help="Run evaluation mode, output JSON results"
- ),
- config_path: str = typer.Option(
- None, "--config", "-c", help="Path to ov.conf, default .openviking/ov.conf"
- ),
- sender: str = typer.Option(
- None, "--sender", help="Sender ID, same usage as feishu channel sender"
- ),
-):
- """Interact with the agent directly."""
- path = Path(config_path).expanduser() if config_path is not None else None
-
- bus = MessageBus()
- config = ensure_config(path)
- _init_bot_data(config)
-
- logger.remove()
- log_file = get_data_dir() / "log" / f"vikingbot.debug.{os.getpid()}.log"
- logger.add(
- log_file,
- level="DEBUG",
- rotation="10 MB",
- retention="7 days",
- encoding="utf-8",
- backtrace=True,
- diagnose=True,
- )
-
- if logs:
- logger.add(sys.stderr, level="DEBUG")
- else:
- logger.add(sys.stderr, level="ERROR")
-
- session_manager = SessionManager(config.bot_data_path)
-
- is_single_turn = message is not None
- # Use unified default session ID
- if session_id is None:
- session_id = get_or_create_machine_id()
- cron = prepare_cron(bus, quiet=is_single_turn)
- channels = prepare_agent_channel(config, bus, message, session_id, markdown, logs, eval, sender)
- agent_loop = prepare_agent_loop(
- config, bus, session_manager, cron, quiet=is_single_turn, eval=eval
- )
-
- async def run():
- if is_single_turn:
- # Single-turn mode: run channels and agent, exit after response
- task_cron = asyncio.create_task(cron.start())
- task_channels = asyncio.create_task(channels.start_all())
- task_agent = asyncio.create_task(agent_loop.run())
-
- # Wait for channels to complete (it will complete after getting response)
- done, pending = await asyncio.wait([task_channels], return_when=asyncio.FIRST_COMPLETED)
-
- # Cancel all other tasks
- for task in pending:
- task.cancel()
- task_cron.cancel()
- task_agent.cancel()
-
- # Wait for cancellation
- await asyncio.gather(task_cron, task_agent, return_exceptions=True)
- else:
- # Interactive mode: run forever
- tasks = []
- tasks.append(cron.start())
- tasks.append(channels.start_all())
- tasks.append(agent_loop.run())
-
- await asyncio.gather(*tasks)
-
- try:
- asyncio.run(run())
- except KeyboardInterrupt:
- console.print("\nGoodbye!")
-
-
-# ============================================================================
-# Channel Commands
-# ============================================================================
-
-
-channels_app = typer.Typer(help="Manage channels")
-app.add_typer(channels_app, name="channels")
-
-
-@channels_app.command("status")
-def channels_status():
- """Show channel status."""
- from vikingbot.config.schema import ChannelType
-
- config = load_config()
- channels_config = config.channels_config
- all_channels = channels_config.get_all_channels()
-
- table = Table(title="Channel Status")
- table.add_column("Type", style="cyan")
- table.add_column("ID", style="magenta")
- table.add_column("Enabled", style="green")
- table.add_column("Configuration", style="yellow")
-
- for channel in all_channels:
- channel_type = str(channel.type)
- channel_id = channel.channel_id()
-
- config_info = ""
- if channel.type == ChannelType.WHATSAPP:
- config_info = channel.bridge_url
- elif channel.type == ChannelType.FEISHU:
- config_info = f"app_id: {channel.app_id[:10]}..." if channel.app_id else ""
- elif channel.type == ChannelType.DISCORD:
- config_info = channel.gateway_url
- elif channel.type == ChannelType.MOCHAT:
- config_info = channel.base_url or ""
- elif channel.type == ChannelType.TELEGRAM:
- config_info = f"token: {channel.token[:10]}..." if channel.token else ""
- elif channel.type == ChannelType.SLACK:
- config_info = "socket" if channel.app_token and channel.bot_token else ""
-
- table.add_row(
- channel_type, channel_id, "✓" if channel.enabled else "✗", config_info or "[dim]—[/dim]"
- )
-
- if not all_channels:
- table.add_row("[dim]No channels configured[/dim]", "", "", "")
-
- console.print(table)
-
-
-def _get_bridge_dir() -> Path:
- """Get the bridge directory, setting it up if needed."""
- import shutil
- import subprocess
-
- # User's bridge location
- user_bridge = get_bridge_path()
-
- # Check if already built
- if (user_bridge / "dist" / "index.js").exists():
- return user_bridge
-
- # Check for npm
- if not shutil.which("npm"):
- console.print("[red]npm not found. Please install Node.js >= 18.[/red]")
- raise typer.Exit(1)
-
- # Find source bridge: first check package data, then source dir
- pkg_bridge = Path(__file__).parent.parent / "bridge" # vikingbot/bridge (installed)
- src_bridge = Path(__file__).parent.parent.parent / "bridge" # repo root/bridge (dev)
-
- source = None
- if (pkg_bridge / "package.json").exists():
- source = pkg_bridge
- elif (src_bridge / "package.json").exists():
- source = src_bridge
-
- if not source:
- console.print("[red]Bridge source not found.[/red]")
- console.print("Try reinstalling: uv pip install --force-reinstall openviking[bot]")
- raise typer.Exit(1)
-
- console.print(f"{__logo__} Setting up bridge...")
-
- # Copy to user directory
- user_bridge.parent.mkdir(parents=True, exist_ok=True)
- if user_bridge.exists():
- shutil.rmtree(user_bridge)
- shutil.copytree(source, user_bridge, ignore=shutil.ignore_patterns("node_modules", "dist"))
-
- # Install and build
- try:
- console.print(" Installing dependencies...")
- subprocess.run(["npm", "install"], cwd=user_bridge, check=True, capture_output=True)
-
- console.print(" Building...")
- subprocess.run(["npm", "run", "build"], cwd=user_bridge, check=True, capture_output=True)
-
- console.print("[green]✓[/green] Bridge ready\n")
- except subprocess.CalledProcessError as e:
- console.print(f"[red]Build failed: {e}[/red]")
- if e.stderr:
- console.print(f"[dim]{e.stderr.decode()[:500]}[/dim]")
- raise typer.Exit(1)
-
- return user_bridge
-
-
-@channels_app.command("login")
-def channels_login():
- """Link device via QR code."""
- import subprocess
-
- from vikingbot.config.schema import ChannelType
-
- config = load_config()
- bridge_dir = _get_bridge_dir()
-
- console.print(f"{__logo__} Starting bridge...")
- console.print("Scan the QR code to connect.\n")
-
- env = {**os.environ}
-
- # Find WhatsApp channel config
- channels_config = config.channels_config
- all_channels = channels_config.get_all_channels()
- whatsapp_channel = next((c for c in all_channels if c.type == ChannelType.WHATSAPP), None)
-
- if whatsapp_channel and whatsapp_channel.bridge_token:
- env["BRIDGE_TOKEN"] = whatsapp_channel.bridge_token
-
- try:
- subprocess.run(["npm", "start"], cwd=bridge_dir, check=True, env=env)
- except subprocess.CalledProcessError as e:
- console.print(f"[red]Bridge failed: {e}[/red]")
- except FileNotFoundError:
- console.print("[red]npm not found. Please install Node.js.[/red]")
-
-
-# ============================================================================
-# Cron Commands
-# ============================================================================
-
-cron_app = typer.Typer(help="Manage scheduled tasks")
-app.add_typer(cron_app, name="cron")
-
-
-@cron_app.command("list")
-def cron_list(
- all: bool = typer.Option(False, "--all", "-a", help="Include disabled jobs"),
-):
- """List scheduled jobs."""
- from vikingbot.config.loader import get_data_dir
- from vikingbot.cron.service import CronService
-
- store_path = get_data_dir() / "cron" / "jobs.json"
- service = CronService(store_path)
-
- jobs = service.list_jobs(include_disabled=all)
-
- if not jobs:
- console.print("No scheduled jobs.")
- return
-
- table = Table(title="Scheduled Jobs")
- table.add_column("ID", style="cyan")
- table.add_column("Name")
- table.add_column("Schedule")
- table.add_column("Status")
- table.add_column("Next Run")
-
- for job in jobs:
- # Format schedule
- if job.schedule.kind == "every":
- sched = f"every {(job.schedule.every_ms or 0) // 1000}s"
- elif job.schedule.kind == "cron":
- sched = job.schedule.expr or ""
- else:
- sched = "one-time"
-
- # Format next run
- next_run = ""
- if job.state.next_run_at_ms:
- next_time = time.strftime(
- "%Y-%m-%d %H:%M", time.localtime(job.state.next_run_at_ms / 1000)
- )
- next_run = next_time
-
- status = "[green]enabled[/green]" if job.enabled else "[dim]disabled[/dim]"
-
- table.add_row(job.id, job.name, sched, status, next_run)
-
- console.print(table)
-
-
-@cron_app.command("add")
-def cron_add(
- name: str = typer.Option(..., "--name", "-n", help="Job name"),
- message: str = typer.Option(..., "--message", "-m", help="Message for agent"),
- every: int = typer.Option(None, "--every", "-e", help="Run every N seconds"),
- cron_expr: str = typer.Option(None, "--cron", "-c", help="Cron expression (e.g. '0 9 * * *')"),
- at: str = typer.Option(None, "--at", help="Run once at time (ISO format)"),
- deliver: bool = typer.Option(False, "--deliver", "-d", help="Deliver response to channel"),
-):
- """Add a scheduled job."""
- from vikingbot.config.loader import get_data_dir
- from vikingbot.cron.service import CronService
- from vikingbot.cron.types import CronSchedule
-
- # Determine schedule type
- if every:
- schedule = CronSchedule(kind="every", every_ms=every * 1000)
- elif cron_expr:
- schedule = CronSchedule(kind="cron", expr=cron_expr)
- elif at:
- import datetime
-
- dt = datetime.datetime.fromisoformat(at)
- schedule = CronSchedule(kind="at", at_ms=int(dt.timestamp() * 1000))
- else:
- console.print("[red]Error: Must specify --every, --cron, or --at[/red]")
- raise typer.Exit(1)
-
- store_path = get_data_dir() / "cron" / "jobs.json"
- service = CronService(store_path)
-
- session_key = SessionKey(type="cli", channel_id="default", chat_id="default")
-
- job = service.add_job(
- name=name,
- schedule=schedule,
- message=message,
- deliver=deliver,
- session_key=session_key,
- )
-
- console.print(f"[green]✓[/green] Added job '{job.name}' ({job.id})")
-
-
-@cron_app.command("remove")
-def cron_remove(
- job_id: str = typer.Argument(..., help="Job ID to remove"),
-):
- """Remove a scheduled job."""
- from vikingbot.config.loader import get_data_dir
- from vikingbot.cron.service import CronService
-
- store_path = get_data_dir() / "cron" / "jobs.json"
- service = CronService(store_path)
-
- if service.remove_job(job_id):
- console.print(f"[green]✓[/green] Removed job {job_id}")
- else:
- console.print(f"[red]Job {job_id} not found[/red]")
-
-
-@cron_app.command("enable")
-def cron_enable(
- job_id: str = typer.Argument(..., help="Job ID"),
- disable: bool = typer.Option(False, "--disable", help="Disable instead of enable"),
-):
- """Enable or disable a job."""
- from vikingbot.config.loader import get_data_dir
- from vikingbot.cron.service import CronService
-
- store_path = get_data_dir() / "cron" / "jobs.json"
- service = CronService(store_path)
-
- job = service.enable_job(job_id, enabled=not disable)
- if job:
- status = "disabled" if disable else "enabled"
- console.print(f"[green]✓[/green] Job '{job.name}' {status}")
- else:
- console.print(f"[red]Job {job_id} not found[/red]")
-
-
-@cron_app.command("run")
-def cron_run(
- job_id: str = typer.Argument(..., help="Job ID to run"),
- force: bool = typer.Option(False, "--force", "-f", help="Run even if disabled"),
-):
- """Manually run a job."""
- from vikingbot.config.loader import get_data_dir
- from vikingbot.cron.service import CronService
-
- store_path = get_data_dir() / "cron" / "jobs.json"
- service = CronService(store_path)
-
- async def run():
- return await service.run_job(job_id, force=force)
-
- if asyncio.run(run()):
- console.print("[green]✓[/green] Job executed")
- else:
- console.print(f"[red]Failed to run job {job_id}[/red]")
-
-
-# ============================================================================
-# Status Commands
-# ============================================================================
-
-
-def status():
- """Show vikingbot status."""
-
- config_path = get_config_path()
- config = load_config()
- workspace = config.workspace_path
-
- console.print(f"{__logo__} vikingbot Status\n")
-
- console.print(
- f"Config: {config_path} {'[green]✓[/green]' if config_path.exists() else '[red]✗[/red]'}"
- )
- console.print(
- f"Workspace: {workspace} {'[green]✓[/green]' if workspace.exists() else '[red]✗[/red]'}"
- )
-
- if config_path.exists():
- from vikingbot.providers.registry import PROVIDERS
-
- console.print(f"Model: {config.agents.model}")
-
- # Check API keys from registry
- for spec in PROVIDERS:
- p = getattr(config.providers, spec.name, None)
- if p is None:
- continue
- if spec.is_local:
- # Local deployments show api_base instead of api_key
- if p.api_base:
- console.print(f"{spec.label}: [green]✓ {p.api_base}[/green]")
- else:
- console.print(f"{spec.label}: [dim]not set[/dim]")
- else:
- has_key = bool(p.api_key)
- console.print(
- f"{spec.label}: {'[green]✓[/green]' if has_key else '[dim]not set[/dim]'}"
- )
-
-
-# ============================================================================
-# Test Commands
-# ============================================================================
-
-try:
- from vikingbot.cli.test_commands import test_app
-
- app.add_typer(test_app, name="test")
-except ImportError:
- # If test commands not available, don't add them
- pass
-
-
-demo_app = typer.Typer(help="Run built-in demos")
-app.add_typer(demo_app, name="demo")
-
-
-@dataclass(frozen=True)
-class _WerewolfPlayer:
- seat: int
- name: str
- role: str
- session_key: SessionKey
-
-
-def _ww_roles_for_player_count(player_count: int) -> list[str]:
- if player_count == 6:
- return ["Werewolf", "Werewolf", "Seer", "Hunter", "Villager", "Villager"]
- if player_count == 8:
- return [
- "Werewolf",
- "Werewolf",
- "Werewolf",
- "Seer",
- "Witch",
- "Hunter",
- "Villager",
- "Villager",
- ]
- if player_count == 9:
- return [
- "Werewolf",
- "Werewolf",
- "Werewolf",
- "Seer",
- "Witch",
- "Hunter",
- "Villager",
- "Villager",
- "Villager",
- ]
- if player_count == 10:
- return [
- "Werewolf",
- "Werewolf",
- "Werewolf",
- "Werewolf",
- "Seer",
- "Witch",
- "Hunter",
- "Guard",
- "Villager",
- "Villager",
- ]
- if player_count == 12:
- return [
- "Werewolf",
- "Werewolf",
- "Werewolf",
- "Werewolf",
- "Seer",
- "Witch",
- "Hunter",
- "Guard",
- "Idiot",
- "Villager",
- "Villager",
- "Villager",
- ]
- raise ValueError(f"Unsupported player_count={player_count}. Use 6/8/9/10/12.")
-
-
-def _ww_alive_seats(alive: dict[int, bool]) -> list[int]:
- return [seat for seat, ok in sorted(alive.items(), key=lambda x: x[0]) if ok]
-
-
-def _ww_pick_random_target(rng: random.Random, alive_seats: list[int], exclude: set[int] | None = None) -> int:
- exclude = exclude or set()
- candidates = [s for s in alive_seats if s not in exclude]
- if not candidates:
- return alive_seats[0] if alive_seats else 0
- return rng.choice(candidates)
-
-
-def _ww_parse_last_int(text: str) -> int | None:
- nums = re.findall(r"\b(\d{1,2})\b", text or "")
- if not nums:
- return None
- try:
- return int(nums[-1], 10)
- except Exception:
- return None
-
-
-def _ww_read_file(path: Path) -> str:
- if not path.exists():
- return ""
- try:
- return path.read_text(encoding="utf-8")
- except Exception:
- return ""
-
-
-def _ww_append_record(record_path: Path, text: str) -> None:
- record_path.parent.mkdir(parents=True, exist_ok=True)
- prev = _ww_read_file(record_path)
- combined = (prev.rstrip() + "\n\n" + text.strip() + "\n").lstrip()
- record_path.write_text(combined, encoding="utf-8")
-
-
-def _ww_init_player_game_md(player: _WerewolfPlayer, all_players: list[_WerewolfPlayer]) -> str:
- wolves = [p for p in all_players if p.role in ("Werewolf", "WhiteWolfKing")]
- wolf_names = [f"{w.seat + 1}号{w.name}" for w in wolves if w.seat != player.seat]
- teammates = "、".join(wolf_names) if wolf_names else "无"
- skills = []
- if player.role == "Witch":
- skills.append("解药:未使用")
- skills.append("毒药:未使用")
- if player.role == "Hunter":
- skills.append("开枪:可用")
- if player.role == "Idiot":
- skills.append("翻牌:未翻")
- if player.role == "Guard":
- skills.append("守护:未使用")
- skill_status = ";".join(skills) if skills else "无"
- return "\n".join(
- [
- "# 本局身份",
- f"座位:{player.seat + 1}号",
- f"昵称:{player.name}",
- f"身份:{player.role}",
- f"同伴:{teammates if player.role in ('Werewolf', 'WhiteWolfKing') else '无'}",
- f"技能状态:{skill_status}",
- "",
- "# 操作历史",
- "",
- "# 临时信息(裁判写入)",
- "",
- ]
- ).strip() + "\n"
-
-
-def _ww_player_prompt_header(day: int, phase: str, player: _WerewolfPlayer, roster: list[_WerewolfPlayer]) -> str:
- roster_lines = "\n".join([f"- {p.seat + 1}号:{p.name}" for p in roster])
- return (
- "你在参与一局“机器人狼人杀”演示。你必须通过文件完成操作,不要在回复里暴露关键动作细节。\n"
- "规则:\n"
- "1) 先用 read_file 读取 GAME.md(路径:GAME.md)\n"
- "2) 根据裁判要求,把你的决定写回 GAME.md(优先用 edit_file 精准替换,或用 write_file 重写完整文件)\n"
- "3) 最后只回复一行:操作完成\n"
- "\n"
- f"当前:第{day}天 / 阶段:{phase}\n"
- f"你的座位:{player.seat + 1}号,你的昵称:{player.name}\n"
- "本局座位表:\n"
- f"{roster_lines}\n"
- )
-
-
-async def _ww_call_player(agent_loop: AgentLoop, player: _WerewolfPlayer, content: str) -> str:
- return await agent_loop.process_direct(content=content, session_key=player.session_key)
-
-
-@demo_app.command("werewolf")
-def demo_werewolf(
- player_count: int = typer.Option(8, "--players", "-p", help="Player count (6/8/9/10/12)"),
- seed: int = typer.Option(42, "--seed", help="Random seed"),
- days: int = typer.Option(1, "--days", help="How many day cycles to run (demo uses 1 by default)"),
- config_path: str = typer.Option(None, "--config", "-c", help="ov.conf path"),
-):
- path = Path(config_path).expanduser() if config_path is not None else None
- bus = MessageBus()
- config = ensure_config(path)
- _init_bot_data(config)
-
- session_manager = SessionManager(config.bot_data_path)
- cron = prepare_cron(bus, quiet=True)
- agent_loop = prepare_agent_loop(config, bus, session_manager, cron, quiet=True, eval=False)
-
- rng = random.Random(seed)
-
- referee_key = SessionKey(type="demo", channel_id="werewolf", chat_id="referee")
- player_keys = [
- SessionKey(type="demo", channel_id="werewolf", chat_id=f"player_{i + 1:02d}")
- for i in range(player_count)
- ]
-
- roles = _ww_roles_for_player_count(player_count)
- rng.shuffle(roles)
- roster: list[_WerewolfPlayer] = [
- _WerewolfPlayer(
- seat=i,
- name=f"Bot{i + 1:02d}",
- role=roles[i],
- session_key=player_keys[i],
- )
- for i in range(player_count)
- ]
-
- async def run():
- outbound_task = asyncio.create_task(_ww_drain_outbound(bus))
- try:
- if agent_loop.sandbox_manager is None:
- raise RuntimeError("SandboxManager not initialized")
-
- await agent_loop.sandbox_manager.get_sandbox(referee_key)
- for p in roster:
- await agent_loop.sandbox_manager.get_sandbox(p.session_key)
-
- referee_ws = agent_loop.sandbox_manager.get_workspace_path(referee_key)
- record_path = referee_ws / "GAME_RECORD.md"
- _ww_append_record(
- record_path,
- "\n".join(
- [
- "# 狼人杀 Demo 记录",
- f"- 玩家数:{player_count}",
- f"- 随机种子:{seed}",
- f"- 沙箱模式:{config.sandbox.mode}",
- "",
- "## 座位表",
- *[f"- {p.seat + 1}号:{p.name}" for p in roster],
- ]
- ),
- )
-
- for p in roster:
- ws = agent_loop.sandbox_manager.get_workspace_path(p.session_key)
- (ws / "GAME.md").write_text(_ww_init_player_game_md(p, roster), encoding="utf-8")
-
- alive: dict[int, bool] = {p.seat: True for p in roster}
- badge_holder: int | None = None
-
- await _ww_run_badge_election(agent_loop, rng, roster, alive, record_path, day=0)
- badge_holder = _ww_read_badge_holder(roster, alive, agent_loop.sandbox_manager) or badge_holder
- if badge_holder is not None:
- _ww_append_record(record_path, f"警长当选:{badge_holder + 1}号")
-
- for day in range(1, max(1, days) + 1):
- night_result = await _ww_run_night(
- agent_loop=agent_loop,
- rng=rng,
- roster=roster,
- alive=alive,
- record_path=record_path,
- day=day,
- badge_holder=badge_holder,
- )
- if night_result is not None:
- alive[night_result] = False
- _ww_append_record(record_path, f"昨夜死亡:{night_result + 1}号")
-
- winner = _ww_check_winner(roster, alive)
- if winner:
- _ww_append_record(record_path, f"游戏结束:{winner}")
- break
-
- await _ww_run_day(
- agent_loop=agent_loop,
- rng=rng,
- roster=roster,
- alive=alive,
- record_path=record_path,
- day=day,
- badge_holder=badge_holder,
- )
-
- winner = _ww_check_winner(roster, alive)
- if winner:
- _ww_append_record(record_path, f"游戏结束:{winner}")
- break
-
- console.print("\n[green]Demo completed.[/green]")
- console.print(f"Referee workspace: {referee_ws}")
- console.print("Player workspaces:")
- for p in roster:
- ws = agent_loop.sandbox_manager.get_workspace_path(p.session_key)
- console.print(f"- {p.seat + 1}号 {p.name}: {ws}")
- finally:
- outbound_task.cancel()
- try:
- await outbound_task
- except asyncio.CancelledError:
- pass
-
- asyncio.run(run())
-
-
-@demo_app.command("werewolf-continue")
-def demo_werewolf_continue(
- days: int = typer.Option(1, "--days", help="How many additional day cycles to run"),
- seed: int = typer.Option(42, "--seed", help="Random seed"),
- config_path: str = typer.Option(None, "--config", "-c", help="ov.conf path"),
-):
- path = Path(config_path).expanduser() if config_path is not None else None
- bus = MessageBus()
- config = ensure_config(path)
- _init_bot_data(config)
-
- session_manager = SessionManager(config.bot_data_path)
- cron = prepare_cron(bus, quiet=True)
- agent_loop = prepare_agent_loop(config, bus, session_manager, cron, quiet=True, eval=False)
-
- rng = random.Random(seed)
-
- referee_key = SessionKey(type="demo", channel_id="werewolf", chat_id="referee")
-
- async def run():
- outbound_task = asyncio.create_task(_ww_drain_outbound(bus))
- try:
- if agent_loop.sandbox_manager is None:
- raise RuntimeError("SandboxManager not initialized")
-
- await agent_loop.sandbox_manager.get_sandbox(referee_key)
- referee_ws = agent_loop.sandbox_manager.get_workspace_path(referee_key)
- record_path = referee_ws / "GAME_RECORD.md"
- if not record_path.exists():
- raise RuntimeError("GAME_RECORD.md not found, run `demo werewolf` first")
-
- roster = _ww_load_roster_from_workspace(
- workspace_root=agent_loop.sandbox_manager.get_workspace_path(referee_key).parent
- )
- if not roster:
- raise RuntimeError("No player workspaces found")
-
- for p in roster:
- await agent_loop.sandbox_manager.get_sandbox(p.session_key)
-
- alive = _ww_compute_alive_from_record(record_path, roster)
- badge_holder = _ww_read_badge_holder(roster, alive, agent_loop.sandbox_manager)
- start_day = _ww_get_next_day_from_record(record_path)
-
- _ww_append_record(
- record_path,
- f"## 继续游戏:从第{start_day}天开始(追加{max(1, days)}天)",
- )
-
- winner = _ww_check_winner(roster, alive)
- if winner:
- _ww_append_record(record_path, f"游戏结束:{winner}")
- console.print("[yellow]Game already ended.[/yellow]")
- return
-
- for day in range(start_day, start_day + max(1, days)):
- night_result = await _ww_run_night(
- agent_loop=agent_loop,
- rng=rng,
- roster=roster,
- alive=alive,
- record_path=record_path,
- day=day,
- badge_holder=badge_holder,
- )
- if night_result is not None:
- alive[night_result] = False
- _ww_append_record(record_path, f"昨夜死亡:{night_result + 1}号")
-
- winner = _ww_check_winner(roster, alive)
- if winner:
- _ww_append_record(record_path, f"游戏结束:{winner}")
- break
-
- await _ww_run_day(
- agent_loop=agent_loop,
- rng=rng,
- roster=roster,
- alive=alive,
- record_path=record_path,
- day=day,
- badge_holder=badge_holder,
- )
-
- winner = _ww_check_winner(roster, alive)
- if winner:
- _ww_append_record(record_path, f"游戏结束:{winner}")
- break
-
- console.print("\n[green]Continue completed.[/green]")
- console.print(f"Referee workspace: {referee_ws}")
- finally:
- outbound_task.cancel()
- try:
- await outbound_task
- except asyncio.CancelledError:
- pass
-
- asyncio.run(run())
-
-
-@demo_app.command("werewolf-ui")
-def demo_werewolf_ui(
- port: int = typer.Option(18791, "--port", "-p", help="UI port"),
- config_path: str = typer.Option(None, "--config", "-c", help="ov.conf path"),
-):
- path = Path(config_path).expanduser() if config_path is not None else None
- config = ensure_config(path)
- _init_bot_data(config)
-
- from fastapi import FastAPI
- from fastapi.responses import HTMLResponse, JSONResponse
- import uvicorn
-
- workspace_root = config.workspace_path
- storage_root = (config.storage_workspace or "~/.openviking/data")
- storage_root = Path(storage_root).expanduser()
-
- def read_text(path: Path, limit: int = 20000) -> str:
- if not path.exists() or not path.is_file():
- return ""
- try:
- content = path.read_text(encoding="utf-8")
- except Exception:
- return ""
- if len(content) > limit:
- return content[-limit:]
- return content
-
- def extract_role(game_md: str) -> str:
- for line in game_md.splitlines():
- if line.strip().startswith("身份:"):
- return line.split("身份:", 1)[1].strip()
- return "未知"
-
- def extract_last_speech(game_md: str) -> str:
- idx = game_md.rfind("发言:")
- if idx == -1:
- return ""
- segment = game_md[idx:].splitlines()
- if not segment:
- return ""
- first = segment[0].replace("发言:", "").strip()
- return first
-
- def list_players() -> list[dict[str, Any]]:
- if not workspace_root.exists():
- return []
- players = []
- for item in sorted(workspace_root.iterdir()):
- if not item.is_dir():
- continue
- if not item.name.startswith("demo__werewolf__player_"):
- continue
- game_path = item / "GAME.md"
- game_md = read_text(game_path)
- memory_md = read_text(item / "memory" / "MEMORY.md")
- history_md = read_text(item / "memory" / "HISTORY.md")
- role = extract_role(game_md)
- last_speech = extract_last_speech(game_md)
- updated_at = ""
- try:
- updated_at = str(int(game_path.stat().st_mtime))
- except Exception:
- updated_at = ""
- players.append(
- {
- "id": item.name,
- "game": game_md,
- "memory": memory_md,
- "history": history_md,
- "role": role,
- "last_speech": last_speech,
- "updated_at": updated_at,
- }
- )
- return players
-
- def read_world_memory() -> dict[str, str]:
- base = storage_root / "viking" / "default" / "user" / "default" / "memories"
- return {
- "overview": read_text(base / ".overview.md"),
- "abstract": read_text(base / ".abstract.md"),
- "entities": read_text(base / "entities" / ".overview.md"),
- "events": read_text(base / "events" / ".overview.md"),
- "preferences": read_text(base / "preferences" / ".overview.md"),
- }
-
- def read_game_record() -> str:
- referee = workspace_root / "demo__werewolf__referee" / "GAME_RECORD.md"
- return read_text(referee)
-
- app_fastapi = FastAPI()
-
- @app_fastapi.get("/", response_class=HTMLResponse)
- def index():
- html = """
-<!doctype html>
-<html lang="zh">
-<head>
- <meta charset="utf-8"/>
- <meta name="viewport" content="width=device-width, initial-scale=1"/>
- <title>狼人杀 Demo 观战</title>
- <style>
- body { font-family: "Press Start 2P", "Menlo", monospace; margin: 0; background: #0b0d12; color: #f2f2f2; }
- header { padding: 14px 24px; background: #121622; border-bottom: 4px solid #252a36; }
- h1 { margin: 0; font-size: 14px; letter-spacing: 1px; }
- .grid { display: grid; grid-template-columns: 1.2fr 1fr; gap: 16px; padding: 16px 24px; }
- .card { background: #151a2a; border: 2px solid #30384c; border-radius: 10px; padding: 12px; box-shadow: 0 0 0 2px #0b0d12 inset; }
- .card h2 { margin: 0 0 8px 0; font-size: 11px; color: #9aa4b2; }
- pre { white-space: pre-wrap; word-break: break-word; background: #0f1320; padding: 8px; border-radius: 8px; border: 2px solid #2a3246; max-height: 360px; overflow: auto; font-size: 10px; }
- .arena { position: relative; height: 520px; background: radial-gradient(circle at center, #1a2033 0%, #0b0d12 70%); border: 2px solid #30384c; border-radius: 16px; }
- .table { position: absolute; left: 50%; top: 50%; width: 240px; height: 240px; transform: translate(-50%, -50%); border-radius: 50%; background: #2a3246; box-shadow: 0 0 0 6px #1b2135 inset, 0 0 0 2px #0b0d12; }
- .seat { position: absolute; width: 110px; text-align: center; font-size: 9px; }
- .avatar { width: 68px; height: 68px; margin: 0 auto 6px; border-radius: 8px; border: 2px solid #3f4a66; background: #1d2438; display: grid; place-items: center; box-shadow: 0 0 0 2px #0b0d12 inset; }
- .avatar .role { font-size: 8px; line-height: 1.2; }
- .bubble { position: absolute; background: #ffefc0; color: #1c1c1c; border: 2px solid #3a2e1b; padding: 6px 8px; border-radius: 8px; font-size: 8px; width: 140px; transform: translate(-50%, -100%); }
- .bubble:after { content: ""; position: absolute; left: 20px; bottom: -6px; border-width: 6px 6px 0; border-style: solid; border-color: #3a2e1b transparent transparent; }
- .bubble:before { content: ""; position: absolute; left: 22px; bottom: -4px; border-width: 4px 4px 0; border-style: solid; border-color: #ffefc0 transparent transparent; }
- .players { display: grid; grid-template-columns: repeat(2, minmax(0, 1fr)); gap: 12px; }
- .tabs { display: flex; gap: 8px; margin-bottom: 8px; flex-wrap: wrap; }
- .tab { padding: 4px 8px; border-radius: 6px; background: #202533; cursor: pointer; font-size: 10px; }
- .tab.active { background: #3a4255; }
- </style>
- <script>
- async function fetchStatus() {
- const res = await fetch('/status');
- return res.json();
- }
- function setText(id, text) {
- const el = document.getElementById(id);
- if (!el) return;
- el.textContent = text || '';
- }
- function renderPlayers(players) {
- const container = document.getElementById('players');
- container.innerHTML = '';
- const arena = document.getElementById('arena');
- arena.innerHTML = '<div class="table"></div>';
- let latest = null;
- players.forEach(p => {
- if (!latest || (p.updated_at && p.updated_at > latest.updated_at)) latest = p;
- });
-
- const seatPositions = [
- { x: 50, y: 2 },
- { x: 75, y: 8 },
- { x: 92, y: 28 },
- { x: 92, y: 58 },
- { x: 75, y: 78 },
- { x: 50, y: 84 },
- { x: 25, y: 78 },
- { x: 8, y: 58 },
- { x: 8, y: 28 },
- { x: 25, y: 8 },
- { x: 50, y: 8 },
- { x: 50, y: 78 },
- ];
-
- players.forEach((p, i) => {
- const pos = seatPositions[i % seatPositions.length];
- const seat = document.createElement('div');
- seat.className = 'seat';
- seat.style.left = `calc(${pos.x}% - 55px)`;
- seat.style.top = `calc(${pos.y}% - 20px)`;
-
- const avatar = document.createElement('div');
- avatar.className = 'avatar';
- const role = document.createElement('div');
- role.className = 'role';
- role.textContent = p.role || '未知';
- avatar.appendChild(role);
-
- const label = document.createElement('div');
- label.textContent = p.id.replace('demo__werewolf__', '').replace('_', ' ');
-
- seat.appendChild(avatar);
- seat.appendChild(label);
- arena.appendChild(seat);
-
- if (latest && latest.id === p.id && p.last_speech) {
- const bubble = document.createElement('div');
- bubble.className = 'bubble';
- bubble.textContent = p.last_speech;
- bubble.style.left = '50%';
- bubble.style.top = '0%';
- seat.appendChild(bubble);
- }
- });
-
- players.forEach((p, idx) => {
- const card = document.createElement('div');
- card.className = 'card';
- const title = document.createElement('h2');
- title.textContent = p.id;
- card.appendChild(title);
- const tabs = document.createElement('div');
- tabs.className = 'tabs';
- const sections = [
- { key: 'game', label: 'GAME.md' },
- { key: 'memory', label: 'MEMORY.md' },
- { key: 'history', label: 'HISTORY.md' },
- ];
- const pre = document.createElement('pre');
- pre.textContent = p.game || '';
- sections.forEach((s, i) => {
- const tab = document.createElement('div');
- tab.className = 'tab' + (i === 0 ? ' active' : '');
- tab.textContent = s.label;
- tab.onclick = () => {
- tabs.querySelectorAll('.tab').forEach(t => t.classList.remove('active'));
- tab.classList.add('active');
- pre.textContent = p[s.key] || '';
- };
- tabs.appendChild(tab);
- });
- card.appendChild(tabs);
- card.appendChild(pre);
- container.appendChild(card);
- });
- }
- async function refresh() {
- const data = await fetchStatus();
- setText('game_record', data.game_record);
- setText('world_overview', data.world_memory.overview);
- setText('world_entities', data.world_memory.entities);
- setText('world_events', data.world_memory.events);
- setText('world_preferences', data.world_memory.preferences);
- renderPlayers(data.players || []);
- }
- window.onload = () => {
- refresh();
- setInterval(refresh, 2000);
- };
- </script>
-</head>
-<body>
- <header>
- <h1>狼人杀 Demo 观战 + 记忆可视化</h1>
- </header>
- <div class="grid">
- <div class="card">
- <h2>像素狼人杀桌面</h2>
- <div class="arena" id="arena"></div>
- </div>
- <div class="card">
- <h2>裁判记录 GAME_RECORD.md</h2>
- <pre id="game_record"></pre>
- </div>
- <div class="card">
- <h2>世界记忆(OpenViking User Memory)</h2>
- <pre id="world_overview"></pre>
- </div>
- <div class="card">
- <h2>世界记忆 - 实体</h2>
- <pre id="world_entities"></pre>
- </div>
- <div class="card">
- <h2>世界记忆 - 事件</h2>
- <pre id="world_events"></pre>
- </div>
- <div class="card">
- <h2>世界记忆 - 偏好</h2>
- <pre id="world_preferences"></pre>
- </div>
- <div class="card">
- <h2>玩家视角(GAME.md / MEMORY.md / HISTORY.md)</h2>
- <div class="players" id="players"></div>
- </div>
- </div>
-</body>
-</html>
-"""
- return HTMLResponse(content=html)
-
- @app_fastapi.get("/status", response_class=JSONResponse)
- def status():
- return JSONResponse(
- {
- "game_record": read_game_record(),
- "players": list_players(),
- "world_memory": read_world_memory(),
- }
- )
-
- console.print(f"{__logo__} Werewolf UI: http://localhost:{port}")
- uvicorn.run(app_fastapi, host="127.0.0.1", port=port, log_level="warning")
-
-
-async def _ww_drain_outbound(bus: MessageBus) -> None:
- while True:
- msg = await bus.consume_outbound()
- _ = msg
-
-
-def _ww_role_alignment(role: str) -> str:
- if role in ("Werewolf", "WhiteWolfKing"):
- return "wolf"
- return "village"
-
-
-def _ww_check_winner(roster: list[_WerewolfPlayer], alive: dict[int, bool]) -> str | None:
- wolves_alive = 0
- villagers_alive = 0
- specials_alive = 0
- for p in roster:
- if not alive.get(p.seat, False):
- continue
- if _ww_role_alignment(p.role) == "wolf":
- wolves_alive += 1
- elif p.role == "Villager":
- villagers_alive += 1
- else:
- specials_alive += 1
- if wolves_alive == 0:
- return "好人胜利(所有狼人死亡)"
- if villagers_alive == 0 or specials_alive == 0:
- return "狼人胜利(好人阵营瓦解)"
- return None
-
-
-def _ww_load_roster_from_workspace(workspace_root: Path) -> list[_WerewolfPlayer]:
- roster: list[_WerewolfPlayer] = []
- if not workspace_root.exists():
- return roster
- for item in sorted(workspace_root.iterdir()):
- if not item.is_dir() or not item.name.startswith("demo__werewolf__player_"):
- continue
- game_md = _ww_read_file(item / "GAME.md")
- seat = None
- name = None
- role = None
- for line in game_md.splitlines():
- if line.startswith("座位:"):
- val = line.split("座位:", 1)[1].strip().replace("号", "")
- if val.isdigit():
- seat = int(val) - 1
- elif line.startswith("昵称:"):
- name = line.split("昵称:", 1)[1].strip()
- elif line.startswith("身份:"):
- role = line.split("身份:", 1)[1].strip()
- if seat is None:
- try:
- seat = int(item.name.split("_")[-1]) - 1
- except Exception:
- seat = len(roster)
- if not name:
- name = f"Bot{seat + 1:02d}"
- if not role:
- role = "Villager"
- chat_id = item.name.split("demo__werewolf__", 1)[-1]
- roster.append(
- _WerewolfPlayer(
- seat=seat,
- name=name,
- role=role,
- session_key=SessionKey(type="demo", channel_id="werewolf", chat_id=chat_id),
- )
- )
- roster.sort(key=lambda p: p.seat)
- return roster
-
-
-def _ww_compute_alive_from_record(record_path: Path, roster: list[_WerewolfPlayer]) -> dict[int, bool]:
- alive = {p.seat: True for p in roster}
- content = _ww_read_file(record_path)
- for line in content.splitlines():
- m = re.search(r"(昨夜死亡|放逐):\s*(\d{1,2})号", line)
- if not m:
- continue
- seat = int(m.group(2)) - 1
- if seat in alive:
- alive[seat] = False
- return alive
-
-
-def _ww_get_next_day_from_record(record_path: Path) -> int:
- content = _ww_read_file(record_path)
- day_nums = [int(m.group(1)) for m in re.finditer(r"第(\d+)天", content)]
- night_nums = [int(m.group(1)) for m in re.finditer(r"第(\d+)晚", content)]
- max_day = max(day_nums) if day_nums else 0
- max_night = max(night_nums) if night_nums else 0
- last = max(max_day, max_night)
- return max(1, last + 1)
-
-
-async def _ww_run_badge_election(
- agent_loop: AgentLoop,
- rng: random.Random,
- roster: list[_WerewolfPlayer],
- alive: dict[int, bool],
- record_path: Path,
- day: int,
-) -> None:
- _ww_append_record(record_path, "## 警长竞选:开始")
- alive_seats = _ww_alive_seats(alive)
-
- candidates: set[int] = set()
- for seat in alive_seats:
- p = roster[seat]
- header = _ww_player_prompt_header(day=day, phase="警长竞选报名与发言", player=p, roster=roster)
- task = (
- f"{header}\n"
- "任务:\n"
- "1) 决定是否竞选警长(是/否)\n"
- "2) 如果竞选,写一段竞选发言(2-4句)\n"
- "3) 把结果写入 GAME.md 的“操作历史”里,格式示例:\n"
- "## 警长竞选\n"
- "- 是否竞选:是\n"
- "- 竞选发言:...\n"
- "\n"
- "注意:不要在回复里贴发言全文,只把内容写进 GAME.md。\n"
- )
- await _ww_call_player(agent_loop, p, task)
-
- game_md = _ww_read_player_game_md(agent_loop.sandbox_manager, p.session_key)
- if "是否竞选:是" in game_md:
- candidates.add(seat)
-
- if not candidates:
- fallback = rng.choice(alive_seats) if alive_seats else None
- if fallback is not None:
- candidates.add(fallback)
-
- _ww_append_record(
- record_path,
- "候选人:" + "、".join([f"{s + 1}号" for s in sorted(candidates)]) if candidates else "候选人:无",
- )
-
- votes: dict[int, int] = {}
- for seat in alive_seats:
- p = roster[seat]
- header = _ww_player_prompt_header(day=day, phase="警长竞选投票", player=p, roster=roster)
- cand_list = "、".join([f"{s + 1}号" for s in sorted(candidates)])
- task = (
- f"{header}\n"
- f"候选人:{cand_list}\n"
- "任务:从候选人中投票给 1 人,把你的投票写入 GAME.md:\n"
- "## 警长投票\n"
- "- 投票:X号\n"
- )
- await _ww_call_player(agent_loop, p, task)
- game_md = _ww_read_player_game_md(agent_loop.sandbox_manager, p.session_key)
- vote = _ww_extract_vote_from_md(game_md, title="警长投票")
- if vote is None or (vote - 1) not in candidates:
- vote = rng.choice(sorted(candidates)) + 1
- votes[seat] = vote - 1
-
- tally: dict[int, float] = {}
- for voter_seat, target_seat in votes.items():
- weight = 1.0
- tally[target_seat] = tally.get(target_seat, 0.0) + weight
-
- winner_seat = _ww_pick_winner_from_tally(rng, tally)
- if winner_seat is None:
- return
- _ww_append_record(record_path, "警长竞选:结果\n" + _ww_format_tally(tally))
- _ww_append_record(record_path, f"警长当选:{winner_seat + 1}号")
-
- for p in roster:
- if p.seat == winner_seat:
- ws = agent_loop.sandbox_manager.get_workspace_path(p.session_key)
- game_md_path = ws / "GAME.md"
- game_md = _ww_read_file(game_md_path)
- game_md_path.write_text(game_md + "\n\n# 警长信息\n警长:是\n", encoding="utf-8")
- else:
- ws = agent_loop.sandbox_manager.get_workspace_path(p.session_key)
- game_md_path = ws / "GAME.md"
- game_md = _ww_read_file(game_md_path)
- if "\n# 警长信息\n" not in game_md:
- game_md_path.write_text(game_md + "\n\n# 警长信息\n警长:否\n", encoding="utf-8")
-
-
-def _ww_read_player_game_md(sandbox_manager: SandboxManager, session_key: SessionKey) -> str:
- ws = sandbox_manager.get_workspace_path(session_key)
- return _ww_read_file(ws / "GAME.md")
-
-
-def _ww_extract_vote_from_md(game_md: str, title: str) -> int | None:
- if not game_md:
- return None
- idx = game_md.rfind(f"## {title}")
- segment = game_md[idx:] if idx != -1 else game_md
- m = re.search(r"(?:投票|目标|击杀目标|查验目标|守护目标|毒药目标):\s*(\d{1,2})\s*号", segment)
- if not m:
- n = _ww_parse_last_int(segment)
- return n
- try:
- return int(m.group(1), 10)
- except Exception:
- return None
-
-
-def _ww_pick_winner_from_tally(rng: random.Random, tally: dict[int, float]) -> int | None:
- if not tally:
- return None
- max_score = max(tally.values())
- top = [seat for seat, score in tally.items() if score == max_score]
- return rng.choice(sorted(top))
-
-
-def _ww_format_tally(tally: dict[int, float]) -> str:
- lines = []
- for seat, score in sorted(tally.items(), key=lambda x: (-x[1], x[0])):
- lines.append(f"- {seat + 1}号:{score}票")
- return "\n".join(lines)
-
-
-def _ww_read_badge_holder(
- roster: list[_WerewolfPlayer], alive: dict[int, bool], sandbox_manager: SandboxManager
-) -> int | None:
- for p in roster:
- if not alive.get(p.seat, False):
- continue
- game_md = _ww_read_player_game_md(sandbox_manager, p.session_key)
- if re.search(r"^警长:是\s*$", game_md, re.MULTILINE):
- return p.seat
- return None
-
-
-async def _ww_run_night(
- agent_loop: AgentLoop,
- rng: random.Random,
- roster: list[_WerewolfPlayer],
- alive: dict[int, bool],
- record_path: Path,
- day: int,
- badge_holder: int | None,
-) -> int | None:
- _ww_append_record(record_path, f"## 第{day}晚:开始")
- alive_seats = _ww_alive_seats(alive)
-
- wolves = [p for p in roster if alive.get(p.seat, False) and p.role in ("Werewolf", "WhiteWolfKing")]
- wolf_votes: dict[int, int] = {}
- for idx, wolf in enumerate(sorted(wolves, key=lambda x: x.seat)):
- existing = "、".join([f"{voter + 1}号→{target + 1}号" for voter, target in wolf_votes.items()]) or "无"
- ws = agent_loop.sandbox_manager.get_workspace_path(wolf.session_key)
- game_md_path = ws / "GAME.md"
- game_md = _ww_read_file(game_md_path)
- injected = (
- game_md
- + "\n\n## 裁判提示:狼人投票\n"
- + f"- 已有投票:{existing}\n"
- + "- 你需要选择一个击杀目标(存活玩家,不能是你自己)\n"
- )
- game_md_path.write_text(injected, encoding="utf-8")
-
- header = _ww_player_prompt_header(day=day, phase="黑夜第一轮-狼人投票", player=wolf, roster=roster)
- task = (
- f"{header}\n"
- "任务:选择击杀目标,写入 GAME.md:\n"
- "## 第{day}晚-狼人投票\n"
- "- 击杀目标:X号\n"
- ).replace("{day}", str(day))
- await _ww_call_player(agent_loop, wolf, task)
-
- game_md_after = _ww_read_file(game_md_path)
- vote = _ww_extract_vote_from_md(game_md_after, title=f"第{day}晚-狼人投票")
- if vote is None or (vote - 1) not in alive_seats or (vote - 1) == wolf.seat:
- vote = _ww_pick_random_target(rng, alive_seats, exclude={wolf.seat}) + 1
- wolf_votes[wolf.seat] = vote - 1
-
- wolf_tally: dict[int, float] = {}
- for wolf_seat, target in wolf_votes.items():
- weight = 1.0
- if badge_holder is not None and wolf_seat == badge_holder:
- weight = 1.5
- wolf_tally[target] = wolf_tally.get(target, 0.0) + weight
- wolf_target = _ww_pick_winner_from_tally(rng, wolf_tally)
- if wolf_target is None:
- wolf_target = _ww_pick_random_target(rng, alive_seats)
- _ww_append_record(record_path, f"狼人投票结果:\n{_ww_format_tally(wolf_tally)}\n击杀目标:{wolf_target + 1}号")
-
- guard_target = await _ww_run_role_target(
- agent_loop, rng, roster, alive, record_path, day, role="Guard", title="守卫守护", forbid_repeat_key=f"第{day-1}晚-守卫守护"
- )
- seer_target = await _ww_run_role_target(agent_loop, rng, roster, alive, record_path, day, role="Seer", title="预言家查验")
- witch_action = await _ww_run_witch(agent_loop, rng, roster, alive, record_path, day, wolf_target)
-
- protected = guard_target == wolf_target if guard_target is not None else False
- final_dead: int | None = wolf_target
- if protected:
- final_dead = None
- if witch_action.get("save") is True:
- final_dead = None
- poison_target = witch_action.get("poison_target")
- if poison_target is not None and alive.get(poison_target, False):
- if final_dead is None:
- final_dead = poison_target
- else:
- _ww_append_record(record_path, f"女巫毒杀:{poison_target + 1}号(演示版只记录,不额外并发死亡)")
-
- if seer_target is not None and alive.get(seer_target, False):
- seer = next((p for p in roster if alive.get(p.seat, False) and p.role == "Seer"), None)
- if seer is not None:
- is_wolf = _ww_role_alignment(roster[seer_target].role) == "wolf"
- ws = agent_loop.sandbox_manager.get_workspace_path(seer.session_key)
- game_md_path = ws / "GAME.md"
- game_md = _ww_read_file(game_md_path)
- game_md_path.write_text(
- game_md + f"\n\n## 第{day}晚-查验结果\n- 目标:{seer_target + 1}号\n- 结果:{'狼人' if is_wolf else '好人'}\n",
- encoding="utf-8",
- )
-
- return final_dead
-
-
-async def _ww_run_role_target(
- agent_loop: AgentLoop,
- rng: random.Random,
- roster: list[_WerewolfPlayer],
- alive: dict[int, bool],
- record_path: Path,
- day: int,
- role: str,
- title: str,
- forbid_repeat_key: str | None = None,
-) -> int | None:
- actor = next((p for p in roster if alive.get(p.seat, False) and p.role == role), None)
- if actor is None:
- return None
-
- alive_seats = _ww_alive_seats(alive)
- ws = agent_loop.sandbox_manager.get_workspace_path(actor.session_key)
- game_md_path = ws / "GAME.md"
- header = _ww_player_prompt_header(day=day, phase=f"黑夜第二轮-{title}", player=actor, roster=roster)
- extra = ""
- if forbid_repeat_key:
- prev = _ww_extract_vote_from_md(_ww_read_file(game_md_path), title=forbid_repeat_key)
- if prev is not None:
- extra = f"\n限制:不能连续两晚选择 {prev}号。\n"
- task = (
- f"{header}\n"
- f"{extra}"
- f"任务:选择目标(存活玩家,不能是你自己),写入 GAME.md:\n"
- f"## 第{day}晚-{title}\n"
- "- 目标:X号\n"
- )
- await _ww_call_player(agent_loop, actor, task)
- game_md = _ww_read_file(game_md_path)
- target = _ww_extract_vote_from_md(game_md, title=f"第{day}晚-{title}") or _ww_parse_last_int(game_md)
- if target is None:
- target = _ww_pick_random_target(rng, alive_seats, exclude={actor.seat}) + 1
- seat = target - 1
- if seat not in alive_seats or seat == actor.seat:
- seat = _ww_pick_random_target(rng, alive_seats, exclude={actor.seat})
- if forbid_repeat_key:
- prev = _ww_extract_vote_from_md(game_md, title=forbid_repeat_key)
- if prev is not None and prev - 1 == seat:
- seat = _ww_pick_random_target(rng, alive_seats, exclude={actor.seat, seat})
- _ww_append_record(record_path, f"{title}:{seat + 1}号")
- return seat
-
-
-async def _ww_run_witch(
- agent_loop: AgentLoop,
- rng: random.Random,
- roster: list[_WerewolfPlayer],
- alive: dict[int, bool],
- record_path: Path,
- day: int,
- wolf_target: int,
-) -> dict[str, int | bool | None]:
- witch = next((p for p in roster if alive.get(p.seat, False) and p.role == "Witch"), None)
- if witch is None:
- return {"save": None, "poison_target": None}
-
- alive_seats = _ww_alive_seats(alive)
- ws = agent_loop.sandbox_manager.get_workspace_path(witch.session_key)
- game_md_path = ws / "GAME.md"
- game_md = _ww_read_file(game_md_path)
- game_md_path.write_text(
- game_md + f"\n\n## 裁判提示:女巫信息\n- 今夜被杀:{wolf_target + 1}号\n",
- encoding="utf-8",
- )
-
- header = _ww_player_prompt_header(day=day, phase="黑夜第二轮-女巫", player=witch, roster=roster)
- task = (
- f"{header}\n"
- f"今夜被杀:{wolf_target + 1}号\n"
- "任务:决定是否用药,并写入 GAME.md:\n"
- f"## 第{day}晚-女巫\n"
- "- 解药:是/否\n"
- "- 毒药:是/否\n"
- "- 毒药目标:X号(如果毒药=是)\n"
- )
- await _ww_call_player(agent_loop, witch, task)
- after = _ww_read_file(game_md_path)
-
- idx = after.rfind(f"## 第{day}晚-女巫")
- seg = after[idx:] if idx != -1 else after
- save = None
- poison = None
- if re.search(r"解药:\s*是", seg):
- save = True
- if re.search(r"解药:\s*否", seg):
- save = False
- if re.search(r"毒药:\s*是", seg):
- poison = True
- if re.search(r"毒药:\s*否", seg):
- poison = False
-
- poison_target = None
- m = re.search(r"毒药目标:\s*(\d{1,2})\s*号", seg)
- if m:
- try:
- poison_target = int(m.group(1), 10) - 1
- except Exception:
- poison_target = None
- if poison is True and poison_target is None:
- poison_target = _ww_pick_random_target(rng, alive_seats, exclude={witch.seat})
-
- if poison_target is not None and (poison_target not in alive_seats or poison_target == witch.seat):
- poison_target = None
-
- _ww_append_record(
- record_path,
- "女巫操作:"
- + (f"解药={'用' if save else '不用'};" if save is not None else "")
- + (f"毒药={'用' if poison else '不用'}" if poison is not None else ""),
- )
- if poison_target is not None:
- _ww_append_record(record_path, f"女巫毒药目标:{poison_target + 1}号")
-
- return {"save": save, "poison_target": poison_target}
-
-
-async def _ww_run_day(
- agent_loop: AgentLoop,
- rng: random.Random,
- roster: list[_WerewolfPlayer],
- alive: dict[int, bool],
- record_path: Path,
- day: int,
- badge_holder: int | None,
-) -> None:
- _ww_append_record(record_path, f"## 第{day}天:开始")
- alive_seats = _ww_alive_seats(alive)
-
- for seat in alive_seats:
- p = roster[seat]
- header = _ww_player_prompt_header(day=day, phase="白天发言", player=p, roster=roster)
- task = (
- f"{header}\n"
- "任务:写一段白天发言(2-4句),写入 GAME.md:\n"
- f"## 第{day}天-发言\n"
- "- 发言:...\n"
- )
- await _ww_call_player(agent_loop, p, task)
-
- _ww_append_record(record_path, f"第{day}天发言:已完成(见各玩家 GAME.md)")
-
- votes: dict[int, int] = {}
- for seat in alive_seats:
- p = roster[seat]
- header = _ww_player_prompt_header(day=day, phase="白天投票", player=p, roster=roster)
- task = (
- f"{header}\n"
- "任务:投票放逐 1 名存活玩家(不能是你自己),写入 GAME.md:\n"
- f"## 第{day}天-投票\n"
- "- 投票:X号\n"
- )
- await _ww_call_player(agent_loop, p, task)
- game_md = _ww_read_player_game_md(agent_loop.sandbox_manager, p.session_key)
- vote = _ww_extract_vote_from_md(game_md, title=f"第{day}天-投票")
- if vote is None:
- vote = _ww_pick_random_target(rng, alive_seats, exclude={p.seat}) + 1
- target = vote - 1
- if target not in alive_seats or target == p.seat:
- target = _ww_pick_random_target(rng, alive_seats, exclude={p.seat})
- votes[seat] = target
-
- tally: dict[int, float] = {}
- for voter_seat, target_seat in votes.items():
- weight = 1.0
- if badge_holder is not None and voter_seat == badge_holder:
- weight = 1.5
- tally[target_seat] = tally.get(target_seat, 0.0) + weight
-
- out_seat = _ww_pick_winner_from_tally(rng, tally)
- if out_seat is None:
- return
-
- _ww_append_record(record_path, f"第{day}天投票结果:\n{_ww_format_tally(tally)}\n放逐:{out_seat + 1}号")
- alive[out_seat] = False
-
-
-
-if __name__ == "__main__":
- app()
diff --git a/bot/vikingbot/config/schema.py b/bot/vikingbot/config/schema.py
index 0b5a885ae..0ae4bfff3 100644
--- a/bot/vikingbot/config/schema.py
+++ b/bot/vikingbot/config/schema.py
@@ -21,6 +21,7 @@ class ChannelType(str, Enum):
SLACK = "slack"
QQ = "qq"
OPENAPI = "openapi"
+ BOT_API = "bot_api"
class SandboxBackend(str, Enum):
@@ -273,6 +274,21 @@ class OpenAPIChannelConfig(BaseChannelConfig):
return self._channel_id
+class BotChannelConfig(BaseChannelConfig):
+ """Bot channel configuration for multi-channel support."""
+
+ type: ChannelType = ChannelType.BOT_API
+ enabled: bool = True
+ api_key: str = "" # If empty, no auth required
+ allow_from: list[str] = Field(default_factory=list)
+ max_concurrent_requests: int = 100
+ need_mention: bool = False
+ id: str = "default" # Channel identifier for multi-channel support
+
+ def channel_id(self) -> str:
+ return self.id
+
+
class ChannelsConfig(BaseModel):
"""Configuration for chat channels - array of channel configs."""
@@ -372,6 +388,8 @@ class ChannelsConfig(BaseModel):
return QQChannelConfig(**config)
elif channel_type == ChannelType.OPENAPI:
return OpenAPIChannelConfig(**config)
+ elif channel_type == ChannelType.BOT_API:
+ return BotChannelConfig(**config)
else:
return BaseChannelConfig(**config)
@@ -593,6 +611,7 @@ class SandboxConfig(BaseModel):
backend: SandboxBackend = SandboxBackend.DIRECT
mode: SandboxMode = SandboxMode.SHARED
backends: SandboxBackendsConfig = Field(default_factory=SandboxBackendsConfig)
+ restrict_workspaces: dict[str, str] = Field(default_factory=dict)
class Config(BaseSettings):
diff --git a/bot/vikingbot/sandbox/backends/direct.py b/bot/vikingbot/sandbox/backends/direct.py
index a273d21f1..f51b72df5 100644
--- a/bot/vikingbot/sandbox/backends/direct.py
+++ b/bot/vikingbot/sandbox/backends/direct.py
@@ -24,6 +24,7 @@ class DirectBackend(SandboxBackend):
self.session_key = session_key
self._workspace = workspace
self._running = False
+ self.restrict_workspaces = config.restrict_workspaces
async def start(self) -> None:
"""Start the backend (no-op for direct backend)."""
@@ -140,3 +141,27 @@ class DirectBackend(SandboxBackend):
for item in sorted(sandbox_path.iterdir()):
items.append((item.name, item.is_dir()))
return items
+
+ def _check_path_restriction(self, path: Path) -> None:
+ """Check if path is within workspace (if restricted).
+
+ Args:
+ path: Path to check
+
+ Raises:
+ PermissionError: If path outside workspace and restriction is enabled
+ """
+
+ workspace = self.workspace.resolve()
+ resolved = path.resolve()
+
+ if self.restrict_workspaces and self.session_key in self.restrict_workspaces:
+ restrict_path = Path(self.restrict_workspaces[self.session_key]).resolve()
+ logger.info(f"Restricted workspace: {restrict_path}")
+ logger.info(f"Checking path: {resolved}")
+ if resolved != restrict_path and restrict_path not in resolved.parents:
+ raise PermissionError(f"Path outside restricted workspace: {path}")
+ return
+
+ if resolved != workspace and workspace not in resolved.parents:
+ raise PermissionError(f"Path outside workspace: {path}")
\ No newline at end of file