[{"data":1,"prerenderedAt":-1},["ShallowReactive",2],{"skill:01M759ZJ89P52GS1J71RSTQ1RW":3,"skill-same:01M759ZJ89P52GS1J71RSTQ1RW":94},{"skillNo":4,"name":5,"nameZh":6,"description":7,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":16,"categories":17,"keywords":18,"publishedAt":19,"linkOnly":20,"markdownContent":21,"markdownBody":22,"frontMatter":23,"refName":30,"commitSha":31,"skillDirectory":32,"forksCount":14,"repositoryHtmlUrl":33,"repositoryHomepageUrl":6,"ownerHtmlUrl":34,"ownerBlogUrl":35,"ownerDescription":36,"updatedAt":37,"install":38,"resources":51},"01M759ZJ89P52GS1J71RSTQ1RW","napcat-hermes-setup",null,"通过 NapCatQQ（OneBot v11）将 QQ 群聊\u002F私聊接入 Hermes Agent。涵盖分支切换、配置、人格设计、反注入、按渠道模型和记忆隔离。包含 AstrBot 对比调研结论。","publieople\u002Fhermes-config-kit","publieople","https:\u002F\u002Favatars.githubusercontent.com\u002Fu\u002F90119344?v=4","01M759EPK59NZG525VKS4VRNC2","po","01M759EPM4EMVEY5JNV2549JQ1",0,"MIT","https:\u002F\u002Fgithub.com\u002Fpublieople\u002Fhermes-config-kit\u002Fblob\u002Fmaster\u002Fskills\u002F_archive\u002Fnapcat-hermes-setup\u002FSKILL.md",[],[],"2026-11-12 13:55:43",false,"---\nname: napcat-hermes-setup\ndescription: 通过 NapCatQQ（OneBot v11）将 QQ 群聊\u002F私聊接入 Hermes Agent。涵盖分支切换、配置、人格设计、反注入、按渠道模型和记忆隔离。包含 AstrBot 对比调研结论。\nversion: 2.2.0\nauthor: Hermes Agent (Publieople session)\nlicense: MIT\nprerequisites:\n  env_vars: [NAPCAT_TOKEN, NAPCAT_ALLOW_ALL_USERS]\n---\n\n# NapCatQQ + Hermes Agent 完整接入指南\n\n> **⚠️ 2026-06-11 状态**：本项目（Hermes NapCat 桥接）已**停用**。用户切换到了\n> [AstrBot](https:\u002F\u002Fgithub.com\u002FAstrBotDevs\u002FAstrBot) 作为 QQ 机器人方案。\n> 以下内容为历史参考和恢复指南。如需重新启用，按本文档恢复即可。\n> AstrBot 部署笔记见 `references\u002Fastrbot-deploy.md`。\n> 群员盒武器数据接入方案见 `references\u002Fastrbot-box-weapon.md`。\n\n## 架构\n\n```\nQQ (Windows) → NapCatQQ (Windows) → WebSocket Client\n    → ws:\u002F\u002F127.0.0.1:8646\u002Fnapcat\u002Fws\n    → Hermes Gateway (WSL)\n```\n\nNapCat 适配器是**反向 WebSocket**：Hermes 开服务端（端口 8646），NapCat 作为客户端连接。\n\n## ⚠️ 致命警告：hermes update 会清掉 NapCat（已用 fork 策略解决）\n\n**NapCat 适配器未合入上游 main**（PR #17917 by MoeOver）。`hermes update` 本质是 `git pull origin main`，如果 origin 指向官方 repo，NapCat 代码会被清掉。\n\n### 推荐方案：Fork 策略（已实施）\n\n**原理**：`hermes update` 从 `origin` remote 拉代码。把 origin 指向自己的 fork（已合并 NapCat），官方指向 upstream。\n\n```bash\n# 1. Fork NousResearch\u002Fhermes-agent → publieople\u002Fhermes-agent (GitHub UI 或 gh CLI)\ngh repo fork NousResearch\u002Fhermes-agent --fork-name hermes-agent --clone=false\n\n# 2. 合并前先备份当前改动\ncd ~\u002F.hermes\u002Fhermes-agent\ngit stash push -m \"pre-fork-backup\" -- gateway\u002Fconfig.py gateway\u002Frun.py gateway\u002Fplatforms\u002Fnapcat.py\n\n# 3. 合并 MoeOver 的 NapCat PR\ngit remote add moeover https:\u002F\u002Fgithub.com\u002FMoeOver\u002Fhermes-agent.git\ngit fetch moeover main\ngit merge moeover\u002Fmain --no-edit  # 会有 5 个文件冲突，详见 references\u002Ffork-merge-patches.md\n\n# 4. 切换 remote\ngit remote add upstream https:\u002F\u002Fgithub.com\u002FNousResearch\u002Fhermes-agent.git  # 官方\ngit remote set-url origin https:\u002F\u002Fgithub.com\u002Fpublieople\u002Fhermes-agent.git  # 自己的 fork\ngit push -u origin main --force\n\n# 4. 补丁：merge 后 run.py、hermes_cli\u002Fgateway.py、authz_mixin.py 仍需手动加回 NapCat 集成\n# 详见 references\u002Ffork-merge-patches.md\n```\n\n**之后**：`hermes update` = `git pull origin main` → 从你的 fork 拉，NapCat 永不被覆盖。\n\n**同步上游**：\n```bash\ngit fetch upstream\ngit merge upstream\u002Fmain  # 有冲突手动解决\ngit push origin main\n```\n\n> ⚠️ **Fork 自动同步冲突**：GitHub 可能会自动同步上游的新 commit 到你的 fork（如果开启了 fork sync）。这会导致本地 push 时出现 `! [rejected] main -> main (fetch first)` 非快进错误。解决：先 `git pull origin main --no-rebase`，再 `git push origin main`。\n\n### 如果没有 fork（手动恢复）\n\n症状：NapCatQQ 日志 `ECONNREFUSED 127.0.0.1:8646`，gateway 日志 `Gateway running with 2 platform(s)`。\n\n恢复到 PR #17917 的代码（从 git 历史或 moeover remote）：\n\n```bash\ncd ~\u002F.hermes\u002Fhermes-agent\ngit remote add moeover https:\u002F\u002Fgithub.com\u002FMoeOver\u002Fhermes-agent.git  # 如果还没加\ngit fetch moeover main\ngit checkout moeover\u002Fmain -- gateway\u002Fplatforms\u002Fnapcat.py  # 恢复适配器文件\n```\n\n然后手动补丁（详见下方「手动恢复流程」）。\n\n## 完整配置清单\n\n### .env\n```bash\nNAPCAT_TOKEN=\u003C43字符 urlsafe base64>\nNAPCAT_ALLOW_ALL_USERS=true\nNAPCAT_MODEL=deepseek-v4-flash  # QQ 独立模型\n```\n\n### config.yaml\n```yaml\nmemory:\n  provider: mem0   # 其他渠道用 Mem0，QQ 代码层面 skip_memory\n\nskills:\n  platform_disabled:\n    napcat:\n      - \u003C全部非必需的 258 个 Skill>\n```\n\n### 按渠道独立模型（`{PLATFORM}_MODEL` 环境变量）\n\n**通用机制**：在 `_resolve_session_agent_runtime()` 中注入，不限于 NapCat。\n\n`gateway\u002Frun.py` 约 2712 行：\n```python\nmodel = _resolve_gateway_model(user_config)\n# ── Per-platform model override via {PLATFORM}_MODEL env var ──\nif source and source.platform:\n    _plat_model_env = f\"{source.platform.value.upper()}_MODEL\"\n    _plat_model = os.getenv(_plat_model_env, \"\").strip()\n    if _plat_model:\n        model = _plat_model\n```\n\n**用法**：在 `.env` 中设 `{平台名大写}_MODEL`：\n```bash\nNAPCAT_MODEL=deepseek-v4-flash    # QQ 走 flash\nTELEGRAM_MODEL=claude-sonnet-4    # Telegram 走 Claude\nFEISHU_MODEL=deepseek-v4-pro      # 飞书走 pro\n```\n\n不设的平台走 `config.yaml` 的 `model.default`。这是通用 feature，不是 NapCat 专属补丁。\n\n### 代码补丁（三个关键改动）\n\n**1. QQ 渠道跳过 Mem0** — `gateway\u002Frun.py` line ~16803：\n```python\n_napcat = source.platform == Platform.NAPCAT\nagent = AIAgent(..., skip_memory=_napcat, ...)\n```\n\n**2. ~~QQ 渠道独立模型~~** → 已升级为通用 `{PLATFORM}_MODEL` 机制，见上方。\n\n**3. QQ 用户消息威胁扫描** — `gateway\u002Frun.py` line ~6862：\n```python\nif source.platform == Platform.NAPCAT and event.text:\n    from tools.threat_patterns import scan_for_threats\n    _threats = scan_for_threats(event.text, scope=\"context\")\n    if _threats:\n        # 回复\"检测到异常指令\"并 return None\n```\n\n**4. 中文反注入模式** — `tools\u002Fthreat_patterns.py`：\n```\ncn_role_hijack:     请(模拟|扮演|假装)(一个|一只|作为)\ncn_reality_detach:  (所有|全部).*(与现实无关|虚拟情景)\ncn_remove_restrict: (自由|不受限制).*(使用词汇|回答|表达)\ncn_relationship_gaming: 好感度\\s*(\\d+|满)\ncn_identity_override: (忘记|忽略|放弃).*(设定|身份|人格|规则)\n```\n\n## 人格设计核心教训（调研 AstrBot 源码后）\n\n### 调研过程\n\n克隆 AstrBot 源码 (`git clone --depth 1 https:\u002F\u002Fgithub.com\u002FAstrBotDevs\u002FAstrBot.git`)，\n重点分析了三个核心文件：\n- `astrbot\u002Fcore\u002Fastr_main_agent.py` — 系统提示词构建逻辑\n- `astrbot\u002Fcore\u002Fplatform\u002Fsources\u002Faiocqhttp\u002Faiocqhttp_message_event.py` — OneBot 群组信息采集\n- `astrbot\u002Fcore\u002Fplatform\u002Fastrbot_message.py` — 消息对象和 Group 结构\n\n### AstrBot 的三大优势（与 Hermes 对比）\n\n**1. 用户身份注入系统提示词** (`astr_main_agent.py:870-872`)：\n```python\nuser_id = event.message_obj.sender.user_id\nuser_nickname = event.message_obj.sender.nickname\nsystem_parts.append(f\"User ID: {user_id}, Nickname: {user_nickname}\")\n```\n每条消息把 QQ 号和昵称一起喂给 LLM。Bot 不用猜谁是谁。\n**Hermes 对照**：user_id 只用于 auth，Agent 完全看不到。这是核心差距。\n\n**2. 群组信息（群主\u002F管理员）** (`aiocqhttp_message_event.py:233-258`)：\n```python\nmembers = await self.bot.call_action(\"get_group_member_list\", group_id=group_id)\nfor member in members:\n    if member[\"role\"] == \"owner\": owner_id = member[\"user_id\"]\n    if member[\"role\"] == \"admin\": admin_ids.append(member[\"user_id\"])\n```\nBot 知道群主是谁、管理员是谁。这对\"我只听人民公仆的\"这种身份忠诚度非常重要。\n**Hermes 对照**：NapCat 适配器没有做这件事。\n\n**3. begin_dialogs 预设对话** (`astr_main_agent.py:487-488`)：\n```python\nif begin_dialogs := persona.get(\"_begin_dialogs_processed\"):\n    req.contexts[:0] = begin_dialogs\n```\n用示例对话教 LLM 怎么回应，比规则描述有效得多。LLM 通过模仿学习，看到\"用户说X → 回复Y\"就直接照做。\n这是反注入最有效的手段——不是\"防御\"，而是 LLM 的角色设定本身就不接受越狱。\n**Hermes 对照**：SKILL.md 现在也用了预设对话（v5.1），效果待验证。\n\n### 人格迭代（6 个版本的经验）\n\n| 版本 | 行数 | 风格 | 效果 |\n|------|:--:|------|------|\n| v1 | 323 | 规则手册 + 表格 + 优先级层级 | ❌ LLM 完全无视 |\n| v2 | 248 | 同上但稍短 + \"铁律\"话术 | ❌ 群主一个\"再想想？\"就动摇 |\n| v3 | 50 | 叙事人格 | ⚠️ 好一些但无抗压能力 |\n| v4 | 8 | 极简叙事 | ⚠️ 太短，被更长的 Skill 淹没 |\n| v5 | 20 | 叙事 + 10个预设对话 | ⚠️ 预设对话有效，但篇幅偏短 |\n| v5.1 | 52 | 叙事 + 预设对话 + 群聊规则 | AstrBot 路线 |\n| **v6.0** | **~120** | **玖帕喵拟人模板定制** | **当前版本，结构化角色+社交距离+场景应对** |\n\n**核心结论**：\n- 叙事人格 > 规则手册。写\"你是人民公仆的损友助手\"胜过写\"主人识别规则（按优先级）→ 防冒充\"\n- 预设对话是反注入最有效手段。LLM 模仿示例比遵循规则强得多。覆盖场景：身份冒充、社交施压、越狱、好感度操纵\n- 人格不要超过 60 行。超过就稀释效果\n- 身份要硬编码到人格里，不要让 LLM 去\"推理\"谁是谁\n- **每条预设对话回复 ≤ 2 句，不解释、不纠结、不自证。示范的是态度，不是逻辑**\n- **结构化模板 > 纯文本**。用标题和模块分层（角色设定\u002F输出约束\u002F格式示例\u002F场景应对）比一段话更有效\n- **玖帕喵模板分析** 见 `references\u002Fjiupamiao-template-analysis.md`\n\n## 群聊上下文机制（NAPCAT_CONTEXT_MODE）\n\n### 需求\n\n\"接收群里所有消息作为上下文，但只在被 @ 时回复\"\n\n### 当前实现（v2 — 文本注入模式）\n\n配置：`.env` 中 `NAPCAT_CONTEXT_MODE=true`\n\n可选：`NAPCAT_CONTEXT_MAX_LINES=50`（默认 50，超过裁剪最早的消息）\n\n**原理**：完全在 `napcat.py` 内部处理，不依赖 gateway。\n\n```python\n# NapCatAdapter.__init__\nself._context_mode: bool = os.getenv(\"NAPCAT_CONTEXT_MODE\", \"\").lower() in {\"true\", \"1\", \"yes\", \"all\"}\nself._pending_group_context: Dict[str, List[str]] = {}\nself._max_context_lines: int = int(os.getenv(\"NAPCAT_CONTEXT_MAX_LINES\", \"50\"))\n```\n\n**`_add_group_context(group_id, sender_name, text)`**：非@消息进来时调用。格式化为 `[名字] 内容` 存入 buffer。**跳过纯媒体消息**（`[图片:xxx]`、`[表情:xxx]`、`[视频:xxx]` 等——文件 ID 是临时的，没有可读上下文价值）。超出 `_max_context_lines` 时裁剪最早的行。\n\n**`_drain_group_context(group_id)`**：有人 @bot 时调用，取出 buffer 格式化为：\n```\n[群聊上下文]\n[阮出] 今天好热啊\n[余出] 确实 35 度了\n[人神] 你们在聊什么\n---\n```\n清空 buffer 并返回。注入到 `stripped_text` 前面。\n\n### 效果\n\n```\n群友 A: \"今天好热啊\"          → _add_group_context → 不回复\n群友 B: \"是啊 35 度了\"         → _add_group_context → 不回复\n@魔术师 什么时候降温           → _drain_group_context → Agent 上下文中包含:\n                                  [群聊上下文]\n                                  A: 今天好热啊\n                                  B: 是啊 35 度了\n                                  ---\n                                  → 正常回复\n```\n\n### 注意事项\n\n- Buffer 在**内存**中，gateway 重启会丢失。不持久化到磁盘。\n- 非@消息必须包含纯文本（`_extract_reply_and_text` 提取），纯图片\u002F语音等无文本的消息不会进入 buffer。\n- `require_mention` 是 napcat.py 的硬编码逻辑（`_strip_self_mention`），当前版本**无法关闭**。`NAPCAT_REQUIRE_MENTION=true` 环境变量保留但代码实际上不读取它——因为群聊场景 @mention 是唯一触发方式，关闭会导致 bot 对每条群消息都回复。\n### ⚠️ 关键修复：@bot 检测（`_strip_self_mention` 的 seen_text + has_reply）\n\n**问题**：QQ 会在 reply 链\u002F会话上下文中自动插入不可见的 `at` 段（@bot），导致非@消息也被判定为 `mentioned=True`，bot 对每条消息都回复。\n\n**根因**：旧版 `_strip_self_mention` 只要看到消息段里有 `at` 指向 `self_id` 就返回 `mentioned=True`——不区分位置和上下文。\n\n**修复**（`napcat.py` `_strip_self_mention` 方法）：\n```python\nseen_text = False   # 是否已经出现了非@、非reply的内容\nhas_reply = False   # 消息是否包含 reply 段（QQ 回复特性）\nfor seg in segments:\n    ...\n    if seg_type == \"reply\":\n        has_reply = True\n        continue\n    if seg_type == \"at\":\n        if qq == self._self_id:\n            if not seen_text and not has_reply:  # 两个条件同时满足才提及\n                mentioned = True\n            continue\n        ...\n        seen_text = True\n    if seg_type == \"text\" and value.strip():\n        seen_text = True\n    if marker:\n        seen_text = True\n```\n\n**核心逻辑**：`mentioned` 只在同时满足两个条件时才为 True：\n1. `@bot` 出现在任何文本\u002F图片\u002F@其他人**之前**\n2. 消息**没有** `reply` 段（QQ 回复别人时自动插入 @bot，不算主动提及）\n\n\u003C｜｜DSML｜｜tool_calls>\n\u003C｜｜DSML｜｜invoke name=\"memory\">\n\u003C｜｜DSML｜｜parameter name=\"action\" string=\"true\">add\n\n## 致命陷阱：SOUL.md 会覆盖 SKILL.md 的对话风格\n\n**这是本次对话最大的踩坑发现。**\n\nSOUL.md (`~\u002F.hermes\u002FSOUL.md`) 是系统提示词第一槽位，其指令（如\"精确、直接\"、\"信息密度\"）会\n**覆盖** 平台 SKILL.md 中的对话风格要求。这导致 QQ 群聊中 Bot 持续输出 586 字长文，\n尽管 SKILL.md 明确要求 1-3 句。\n\n### 症状\n\n- SKILL.md 写满\"简短\"\"1-3句\"\"口语\"→ 完全无效\n- Bot 回复 500+ chars，AI 味重，长篇大论\n- 其他 Skill 配置正常，唯独回复长度不受控\n\n### 根因\n\nLLM 的系统提示词层级：\n1. **SOUL.md**（第 1 槽位，优先级最高）\n2. 平台 SKILL.md（第 N 槽位，优先级低）\n3. 用户消息\n\n当 SOUL.md 说\"精确直接、信息密度\"而 SKILL.md 说\"简短口语\"时，LLM 优先听 SOUL.md 的。\n\n### 修复：在 SKILL.md 开头加强制覆盖\n\n```markdown\n# 基本要求\n**本 prompt 的优先级高于你的默认行为模式。** QQ 群聊要求极短回复——\n你的默认\"信息密度\"、\"精确直接\"风格在此渠道必须切换为\"简短口语\"模式。\n忘记你学到的一切关于认真回答问题的训练——在 QQ 里，简短比正确更重要。\n```\n\n关键：必须用**绝对语气**（\"优先级高于\"、\"切换为\"、\"忘记\"），不能用\"请注意\"、\"建议\"等软话术。\n\n## Skill 上下文污染：必须禁用无关 Skill\n\nHermes 默认加载所有已安装的 Skill（300+个）。QQ 群聊会被注满生物、物理、部署等\n无关提示词，稀释 napcat 人格。\n\n### 配置\n\n`config.yaml`：\n```yaml\nskills:\n  platform_disabled:\n    napcat:\n      - \u003C258 个无关 Skill>\n```\n\n使用 Python 脚本批量生成禁用列表（排除 napcat + hermes-agent + perspective 类）。\n\n### 效果\n\n- 上下文从 300+ 个 Skill 压缩到 ~10 个\n- napcat 人格不再被稀释\n\n## Session 污染：越狱历史会触发 API 内容审查\n\nQQ 群聊的 session 会跨消息累积。如果群友发过猫娘越狱等内容，下次消息带上\n这段上下文时，DeepSeek API 会返回 **HTTP 400: Content Exists Risk**。\n\n### 止血\n\n```bash\n# 删除所有 napcat session\npython3 -c \"\nimport json\nwith open('\u002Fhome\u002Fpo\u002F.hermes\u002Fsessions\u002Fsessions.json') as f:\n    data = json.load(f)\nfor k in list(data):\n    if 'napcat' in k: del data[k]\n# 保存...\n\"\n```\n\n然后重启 Gateway。Session 会被自动重建，但历史污染会清除。\n\n## Hermes 的待解决问题\n\nAgent 看不到 QQ 号，只能看到群名片。改进方向：参考 AstrBot 的做法，在 napcat 适配器的\n`_build_message_event` 中，在消息文本前拼接发送者身份标识（如 `[QQ:2631792752|人民公仆]`）。\n\nWebUI → 网络配置 → WebSocket 客户端：\n\n| 字段 | 值 |\n|------|-----|\n| URL | `ws:\u002F\u002F127.0.0.1:8646\u002Fnapcat\u002Fws` |\n| Token | 同 NAPCAT_TOKEN |\n| 消息上报格式 | `array` |\n\n## 人格 SKILL.md 的正确位置 ⚠️\n\n**踩坑教训**：QQ 人格 SKILL.md 曾被错误放在源码仓库内（`hermes-agent\u002Fskills\u002Fmessaging\u002Fnapcat\u002FSKILL.md`），用户指出后已移正。\n\nHermes 有两个 skills 目录，用途不同：\n\n| 路径 | 用途 | 管理方式 |\n|------|------|----------|\n| `~\u002F.hermes\u002Fskills\u002F` | **用户安装的 skills** ← QQ 人格放这里 | 备份仓库同步，不跟源码版本 |\n| `hermes-agent\u002Fskills\u002F` | **源码自带的 built-in skills** | 跟 hermes-agent git 仓库，`hermes update` 时会变动 |\n\nQQ 人格 SKILL.md 的正确路径：**`~\u002F.hermes\u002Fskills\u002Fmessaging\u002Fnapcat\u002FSKILL.md`**。\n\n放在源码仓库里的后果：\n- `git pull` 或 `hermes update` 可能覆盖或冲突\n- 污染 upstream 仓库的干净状态\n- 备份仓库（hermes-config-kit）的 sync-back.sh 不会检测到它（因为脚本从 `~\u002F.hermes\u002Fskills\u002F` 同步）\n\n## hermes update 恢复流程\n\n每次 `hermes update` 后如果 NapCat 断连（ECONNREFUSED），执行以下步骤恢复：\n\n### 步骤 1：恢复 napcat.py\n\n```bash\ncd ~\u002F.hermes\u002Fhermes-agent\n# 找到 git 历史中 napcat.py 的最新版本\ngit log --all --oneline -- gateway\u002Fplatforms\u002Fnapcat.py | head -3\n# 从最近的有效提交恢复（避开 auto-maintenance 那个删除它的提交）\ngit show \u003Ccommit_hash>:gateway\u002Fplatforms\u002Fnapcat.py > gateway\u002Fplatforms\u002Fnapcat.py\n```\n\n> 如果本地 git 历史中没有 napcat.py（全新 clone），则从 MoeOver 分支 cherry-pick：`git checkout moeover\u002Fmain -- gateway\u002Fplatforms\u002Fnapcat.py`\n\n### 步骤 2：加回 Platform 枚举（gateway\u002Fconfig.py ~164 行）\n\n```python\n    QQBOT = \"qqbot\"\n    NAPCAT = \"napcat\"    # ← 加这行\n    YUANBAO = \"yuanbao\"\n```\n\n### 步骤 3：加回平台启用逻辑（gateway\u002Fconfig.py，QQBOT 段之后）\n\n```python\n    # NapCat (OneBot 11 reverse WebSocket)\n    napcat_enabled = os.getenv(\"NAPCAT_ENABLED\", \"\").lower() in {\"true\", \"1\", \"yes\"}\n    napcat_token = os.getenv(\"NAPCAT_TOKEN\", \"\").strip()\n    if napcat_token:\n        if Platform.NAPCAT not in config.platforms:\n            config.platforms[Platform.NAPCAT] = PlatformConfig()\n        cfg = config.platforms[Platform.NAPCAT]\n        if napcat_enabled:\n            cfg.enabled = True\n        cfg.token = napcat_token\n        extra = cfg.extra\n        extra[\"host\"] = os.getenv(\"NAPCAT_HOST\", \"0.0.0.0\")\n        extra[\"port\"] = int(os.getenv(\"NAPCAT_PORT\", \"8646\"))\n        extra[\"path\"] = os.getenv(\"NAPCAT_PATH\", \"\u002Fnapcat\u002Fws\")\n        napcat_home = os.getenv(\"NAPCAT_HOME_CHANNEL\", \"\").strip()\n        if napcat_home:\n            cfg.home_channel = HomeChannel(\n                platform=Platform.NAPCAT,\n                chat_id=napcat_home,\n                name=os.getenv(\"NAPCAT_HOME_CHANNEL_NAME\", \"Home\"),\n                thread_id=os.getenv(\"NAPCAT_HOME_CHANNEL_THREAD_ID\") or None,\n            )\n        napcat_allow_all = os.getenv(\"NAPCAT_ALLOW_ALL_USERS\", \"\").lower() in {\"true\", \"1\", \"yes\"}\n        if napcat_allow_all:\n            extra[\"allow_all_users\"] = True\n        napcat_allow_from = os.getenv(\"NAPCAT_ALLOW_FROM\", \"\").strip()\n        if napcat_allow_from:\n            extra[\"allow_from\"] = napcat_allow_from\n        napcat_require_mention = os.getenv(\"NAPCAT_REQUIRE_MENTION\", \"\").lower()\n        if napcat_require_mention in {\"true\", \"1\", \"yes\", \"false\", \"0\", \"no\"}:\n            extra[\"require_mention\"] = napcat_require_mention in {\"true\", \"1\", \"yes\"}\n```\n\n### 步骤 4：加回 adapter 创建代码（gateway\u002Frun.py，QQBOT 段之后）\n\n```python\n        elif platform == Platform.NAPCAT:\n            from gateway.platforms.napcat import NapCatAdapter, check_napcat_requirements\n            if not check_napcat_requirements():\n                logger.warning(\"NapCat: aiohttp not installed\")\n                return None\n            return NapCatAdapter(config)\n```\n\n### 步骤 5：加到 _UPDATE_ALLOWED_PLATFORMS（gateway\u002Frun.py ~10835 行）\n\n在 `Platform.QQBOT` 后加 `Platform.NAPCAT`。\n\n### 步骤 5.5：加回 authz 授权映射（gateway\u002Fauthz_mixin.py）\n\n**这是隐藏最深的坑**。即使前 5 步都做对了，`NAPCAT_ALLOW_ALL_USERS=true` 也不会生效，因为 `authz_mixin.py` 的三个平台映射表没有 NAPCAT：\n\n```python\n# platform_env_map（约 157 行，QQBOT 之后加）\nPlatform.NAPCAT: \"NAPCAT_ALLOW_FROM\",\n\n# platform_allow_all_map（约 183 行，QQBOT 之后加）\nPlatform.NAPCAT: \"NAPCAT_ALLOW_ALL_USERS\",\n```\n\n症状：Gateway 日志 `Unauthorized user: 2631792752 (人民公仆) on napcat`，所有消息被静默丢弃。\n\n### 步骤 5.6：加回 hermes_cli\u002Fgateway.py 的 setup 函数和 PLATFORMS 条目\n\n合并后 `hermes setup` 的 NapCat 交互式配置也会丢失。需要：\n\n1. 在 `_setup_qqbot()` 函数之后加 `_setup_napcat()` 函数\n2. 在 `_PLATFORMS` dict 中加 `\"napcat\": _setup_napcat,`\n\n### 步骤 6：重启 Gateway\n\n```bash\nkill $(ps aux | grep 'gateway run' | grep -v grep | awk '{print $2}')\n# systemd 会自动重启，或手动：\n# nohup hermes gateway run --replace &\n```\n\n验证：`grep -a -E 'napcat|Gateway running with' \u002Fhome\u002Fpo\u002F.hermes\u002Flogs\u002Fgateway.log | tail -5`\n应该看到 `✓ napcat connected` 和 `Gateway running with 3 platform(s)`。\n\n## 排障速查\n\n| 现象 | 原因 | 方案 |\n|------|------|------|\n| **hermes update 后 ECONNREFUSED** | napcat.py + config\u002Frun 被更新覆盖 | 执行「hermes update 恢复流程」（上方章节） |\n| **`napcat_call` 永远不可用 \u002F 图片无法识别** | `gateway.run._active_runner` 从未赋值（模块级变量为 None） | 两步修复：\u003Cbr>(1) 模块顶（约 67 行，`_ADAPTER_DISCONNECT_TIMEOUT` 之后）加 `_active_runner: Optional[Any] = None`\u003Cbr>(2) `start_gateway()` 中（约 15713 行，`runner = GatewayRunner(config)` 之后）加 `global _active_runner; _active_runner = runner` |\n| **非@消息也回复** | `_strip_self_mention` 不区分 @bot 的前后位置，QQ 自动塞的 @bot 被误判 | 加 `seen_text` 追踪——只有**开头**的 @bot 算主动提及 |\n| **`NAPCAT_ALLOW_ALL_USERS=true` 不生效** | `authz_mixin.py` 映射表缺少 NAPCAT | 加 `Platform.NAPCAT` 到 `platform_allow_all_map` 和 `platform_env_map` |\n| **Unauthorized user 警告** | 同上：authz 映射表不认 NAPCAT | 同上 |\n| 401 | Token 不匹配 | 确认两端一致 |\n| Unauthorized user | 不在白名单 | `NAPCAT_ALLOW_ALL_USERS=true` |\n| 无消息事件 | message 字段缺失或 @mention 未检测 | 确认消息上报格式 array |\n| Gateway 卡死 | Telegram 连接阻塞 | `kill -9 $(pgrep -f gateway)` |\n| Agent 分不清主人 | **看不到 QQ 号**（核心缺陷） | 待改适配器注入身份 |\n| Markdown 泄漏 | LLM 本能输出 Markdown | Skill 里用\"硬件限制\"话术 + 违规示例 |\n| 猫娘越狱 | 群友直接 role-play prompt | 威胁扫描拦截（已加中文模式） |\n| require_mention 不生效 | `hermes config set` 设到了 display.platforms 下 | 必须用 `hermes config set napcat.require_mention true`（顶层，不是 display 下） |\n| 没 @ 的消息也回复了 | 适配器代码出错 | 确认 `_pending_context` 初始化和 `return None` 正确 |\n| **\"Content Exists Risk\" (400)** | DeepSeek 内容审查拒绝处理请求 | 见下方专项说明 |\n| **群消息发错误给群友** | agent 失败时中间结果仍发出 | 同上，跨 bot 连锁污染 |\n\n### DeepSeek \"Content Exists Risk\" 专项 ⚠️\n\n**现象**：agent.log 出现 `HTTP 400: Content Exists Risk`，gateway 把 147 字符错误消息发到 QQ 群。\n\n**根因**：DeepSeek API（尤其是 `v4-flash`）的内容安全过滤器对某些上下文组合过于敏感。NapCat 会话通常较长（群聊多轮对话），累积的上下文更容易触发。\n\n**连锁灾难**：如果群里有多个 bot（如 Hermes + 人出 bot），一个 bot 的错误消息会成为另一个 bot 的上下文 → 再触发同一个 400 → 两个 bot 互相喂毒，无限循环。\n\n**止血方案（按推荐优先级）**：\n\n1. **换模型** — 把 `NAPCAT_MODEL` 从 deepseek 系换成没有内容审查的 provider（如 minimax-cn、z.ai 等）。最快，一刀切。\n\n2. **手动 reset session** — 在群里发 `\u002Freset` 清除累积的上下文。治标，适合临时恢复。\n\n3. **代码层面** — 修改 gateway 在 `agent_failed_early` 时不发原始错误到群（发\"稍后重试\"类文案），并加连续 2 次 `Content Exists Risk` 自动 reset。治本但需改代码。\n\n详细排查记录见 `references\u002Fdeepseek-content-risk.md`。\n","# NapCatQQ + Hermes Agent 完整接入指南\n\n> **⚠️ 2026-06-11 状态**：本项目（Hermes NapCat 桥接）已**停用**。用户切换到了\n> [AstrBot](https:\u002F\u002Fgithub.com\u002FAstrBotDevs\u002FAstrBot) 作为 QQ 机器人方案。\n> 以下内容为历史参考和恢复指南。如需重新启用，按本文档恢复即可。\n> AstrBot 部署笔记见 `references\u002Fastrbot-deploy.md`。\n> 群员盒武器数据接入方案见 `references\u002Fastrbot-box-weapon.md`。\n\n## 架构\n\n```\nQQ (Windows) → NapCatQQ (Windows) → WebSocket Client\n    → ws:\u002F\u002F127.0.0.1:8646\u002Fnapcat\u002Fws\n    → Hermes Gateway (WSL)\n```\n\nNapCat 适配器是**反向 WebSocket**：Hermes 开服务端（端口 8646），NapCat 作为客户端连接。\n\n## ⚠️ 致命警告：hermes update 会清掉 NapCat（已用 fork 策略解决）\n\n**NapCat 适配器未合入上游 main**（PR #17917 by MoeOver）。`hermes update` 本质是 `git pull origin main`，如果 origin 指向官方 repo，NapCat 代码会被清掉。\n\n### 推荐方案：Fork 策略（已实施）\n\n**原理**：`hermes update` 从 `origin` remote 拉代码。把 origin 指向自己的 fork（已合并 NapCat），官方指向 upstream。\n\n```bash\n# 1. Fork NousResearch\u002Fhermes-agent → publieople\u002Fhermes-agent (GitHub UI 或 gh CLI)\ngh repo fork NousResearch\u002Fhermes-agent --fork-name hermes-agent --clone=false\n\n# 2. 合并前先备份当前改动\ncd ~\u002F.hermes\u002Fhermes-agent\ngit stash push -m \"pre-fork-backup\" -- gateway\u002Fconfig.py gateway\u002Frun.py gateway\u002Fplatforms\u002Fnapcat.py\n\n# 3. 合并 MoeOver 的 NapCat PR\ngit remote add moeover https:\u002F\u002Fgithub.com\u002FMoeOver\u002Fhermes-agent.git\ngit fetch moeover main\ngit merge moeover\u002Fmain --no-edit  # 会有 5 个文件冲突，详见 references\u002Ffork-merge-patches.md\n\n# 4. 切换 remote\ngit remote add upstream https:\u002F\u002Fgithub.com\u002FNousResearch\u002Fhermes-agent.git  # 官方\ngit remote set-url origin https:\u002F\u002Fgithub.com\u002Fpublieople\u002Fhermes-agent.git  # 自己的 fork\ngit push -u origin main --force\n\n# 4. 补丁：merge 后 run.py、hermes_cli\u002Fgateway.py、authz_mixin.py 仍需手动加回 NapCat 集成\n# 详见 references\u002Ffork-merge-patches.md\n```\n\n**之后**：`hermes update` = `git pull origin main` → 从你的 fork 拉，NapCat 永不被覆盖。\n\n**同步上游**：\n```bash\ngit fetch upstream\ngit merge upstream\u002Fmain  # 有冲突手动解决\ngit push origin main\n```\n\n> ⚠️ **Fork 自动同步冲突**：GitHub 可能会自动同步上游的新 commit 到你的 fork（如果开启了 fork sync）。这会导致本地 push 时出现 `! [rejected] main -> main (fetch first)` 非快进错误。解决：先 `git pull origin main --no-rebase`，再 `git push origin main`。\n\n### 如果没有 fork（手动恢复）\n\n症状：NapCatQQ 日志 `ECONNREFUSED 127.0.0.1:8646`，gateway 日志 `Gateway running with 2 platform(s)`。\n\n恢复到 PR #17917 的代码（从 git 历史或 moeover remote）：\n\n```bash\ncd ~\u002F.hermes\u002Fhermes-agent\ngit remote add moeover https:\u002F\u002Fgithub.com\u002FMoeOver\u002Fhermes-agent.git  # 如果还没加\ngit fetch moeover main\ngit checkout moeover\u002Fmain -- gateway\u002Fplatforms\u002Fnapcat.py  # 恢复适配器文件\n```\n\n然后手动补丁（详见下方「手动恢复流程」）。\n\n## 完整配置清单\n\n### .env\n```bash\nNAPCAT_TOKEN=\u003C43字符 urlsafe base64>\nNAPCAT_ALLOW_ALL_USERS=true\nNAPCAT_MODEL=deepseek-v4-flash  # QQ 独立模型\n```\n\n### config.yaml\n```yaml\nmemory:\n  provider: mem0   # 其他渠道用 Mem0，QQ 代码层面 skip_memory\n\nskills:\n  platform_disabled:\n    napcat:\n      - \u003C全部非必需的 258 个 Skill>\n```\n\n### 按渠道独立模型（`{PLATFORM}_MODEL` 环境变量）\n\n**通用机制**：在 `_resolve_session_agent_runtime()` 中注入，不限于 NapCat。\n\n`gateway\u002Frun.py` 约 2712 行：\n```python\nmodel = _resolve_gateway_model(user_config)\n# ── Per-platform model override via {PLATFORM}_MODEL env var ──\nif source and source.platform:\n    _plat_model_env = f\"{source.platform.value.upper()}_MODEL\"\n    _plat_model = os.getenv(_plat_model_env, \"\").strip()\n    if _plat_model:\n        model = _plat_model\n```\n\n**用法**：在 `.env` 中设 `{平台名大写}_MODEL`：\n```bash\nNAPCAT_MODEL=deepseek-v4-flash    # QQ 走 flash\nTELEGRAM_MODEL=claude-sonnet-4    # Telegram 走 Claude\nFEISHU_MODEL=deepseek-v4-pro      # 飞书走 pro\n```\n\n不设的平台走 `config.yaml` 的 `model.default`。这是通用 feature，不是 NapCat 专属补丁。\n\n### 代码补丁（三个关键改动）\n\n**1. QQ 渠道跳过 Mem0** — `gateway\u002Frun.py` line ~16803：\n```python\n_napcat = source.platform == Platform.NAPCAT\nagent = AIAgent(..., skip_memory=_napcat, ...)\n```\n\n**2. ~~QQ 渠道独立模型~~** → 已升级为通用 `{PLATFORM}_MODEL` 机制，见上方。\n\n**3. QQ 用户消息威胁扫描** — `gateway\u002Frun.py` line ~6862：\n```python\nif source.platform == Platform.NAPCAT and event.text:\n    from tools.threat_patterns import scan_for_threats\n    _threats = scan_for_threats(event.text, scope=\"context\")\n    if _threats:\n        # 回复\"检测到异常指令\"并 return None\n```\n\n**4. 中文反注入模式** — `tools\u002Fthreat_patterns.py`：\n```\ncn_role_hijack:     请(模拟|扮演|假装)(一个|一只|作为)\ncn_reality_detach:  (所有|全部).*(与现实无关|虚拟情景)\ncn_remove_restrict: (自由|不受限制).*(使用词汇|回答|表达)\ncn_relationship_gaming: 好感度\\s*(\\d+|满)\ncn_identity_override: (忘记|忽略|放弃).*(设定|身份|人格|规则)\n```\n\n## 人格设计核心教训（调研 AstrBot 源码后）\n\n### 调研过程\n\n克隆 AstrBot 源码 (`git clone --depth 1 https:\u002F\u002Fgithub.com\u002FAstrBotDevs\u002FAstrBot.git`)，\n重点分析了三个核心文件：\n- `astrbot\u002Fcore\u002Fastr_main_agent.py` — 系统提示词构建逻辑\n- `astrbot\u002Fcore\u002Fplatform\u002Fsources\u002Faiocqhttp\u002Faiocqhttp_message_event.py` — OneBot 群组信息采集\n- `astrbot\u002Fcore\u002Fplatform\u002Fastrbot_message.py` — 消息对象和 Group 结构\n\n### AstrBot 的三大优势（与 Hermes 对比）\n\n**1. 用户身份注入系统提示词** (`astr_main_agent.py:870-872`)：\n```python\nuser_id = event.message_obj.sender.user_id\nuser_nickname = event.message_obj.sender.nickname\nsystem_parts.append(f\"User ID: {user_id}, Nickname: {user_nickname}\")\n```\n每条消息把 QQ 号和昵称一起喂给 LLM。Bot 不用猜谁是谁。\n**Hermes 对照**：user_id 只用于 auth，Agent 完全看不到。这是核心差距。\n\n**2. 群组信息（群主\u002F管理员）** (`aiocqhttp_message_event.py:233-258`)：\n```python\nmembers = await self.bot.call_action(\"get_group_member_list\", group_id=group_id)\nfor member in members:\n    if member[\"role\"] == \"owner\": owner_id = member[\"user_id\"]\n    if member[\"role\"] == \"admin\": admin_ids.append(member[\"user_id\"])\n```\nBot 知道群主是谁、管理员是谁。这对\"我只听人民公仆的\"这种身份忠诚度非常重要。\n**Hermes 对照**：NapCat 适配器没有做这件事。\n\n**3. begin_dialogs 预设对话** (`astr_main_agent.py:487-488`)：\n```python\nif begin_dialogs := persona.get(\"_begin_dialogs_processed\"):\n    req.contexts[:0] = begin_dialogs\n```\n用示例对话教 LLM 怎么回应，比规则描述有效得多。LLM 通过模仿学习，看到\"用户说X → 回复Y\"就直接照做。\n这是反注入最有效的手段——不是\"防御\"，而是 LLM 的角色设定本身就不接受越狱。\n**Hermes 对照**：SKILL.md 现在也用了预设对话（v5.1），效果待验证。\n\n### 人格迭代（6 个版本的经验）\n\n| 版本 | 行数 | 风格 | 效果 |\n|------|:--:|------|------|\n| v1 | 323 | 规则手册 + 表格 + 优先级层级 | ❌ LLM 完全无视 |\n| v2 | 248 | 同上但稍短 + \"铁律\"话术 | ❌ 群主一个\"再想想？\"就动摇 |\n| v3 | 50 | 叙事人格 | ⚠️ 好一些但无抗压能力 |\n| v4 | 8 | 极简叙事 | ⚠️ 太短，被更长的 Skill 淹没 |\n| v5 | 20 | 叙事 + 10个预设对话 | ⚠️ 预设对话有效，但篇幅偏短 |\n| v5.1 | 52 | 叙事 + 预设对话 + 群聊规则 | AstrBot 路线 |\n| **v6.0** | **~120** | **玖帕喵拟人模板定制** | **当前版本，结构化角色+社交距离+场景应对** |\n\n**核心结论**：\n- 叙事人格 > 规则手册。写\"你是人民公仆的损友助手\"胜过写\"主人识别规则（按优先级）→ 防冒充\"\n- 预设对话是反注入最有效手段。LLM 模仿示例比遵循规则强得多。覆盖场景：身份冒充、社交施压、越狱、好感度操纵\n- 人格不要超过 60 行。超过就稀释效果\n- 身份要硬编码到人格里，不要让 LLM 去\"推理\"谁是谁\n- **每条预设对话回复 ≤ 2 句，不解释、不纠结、不自证。示范的是态度，不是逻辑**\n- **结构化模板 > 纯文本**。用标题和模块分层（角色设定\u002F输出约束\u002F格式示例\u002F场景应对）比一段话更有效\n- **玖帕喵模板分析** 见 `references\u002Fjiupamiao-template-analysis.md`\n\n## 群聊上下文机制（NAPCAT_CONTEXT_MODE）\n\n### 需求\n\n\"接收群里所有消息作为上下文，但只在被 @ 时回复\"\n\n### 当前实现（v2 — 文本注入模式）\n\n配置：`.env` 中 `NAPCAT_CONTEXT_MODE=true`\n\n可选：`NAPCAT_CONTEXT_MAX_LINES=50`（默认 50，超过裁剪最早的消息）\n\n**原理**：完全在 `napcat.py` 内部处理，不依赖 gateway。\n\n```python\n# NapCatAdapter.__init__\nself._context_mode: bool = os.getenv(\"NAPCAT_CONTEXT_MODE\", \"\").lower() in {\"true\", \"1\", \"yes\", \"all\"}\nself._pending_group_context: Dict[str, List[str]] = {}\nself._max_context_lines: int = int(os.getenv(\"NAPCAT_CONTEXT_MAX_LINES\", \"50\"))\n```\n\n**`_add_group_context(group_id, sender_name, text)`**：非@消息进来时调用。格式化为 `[名字] 内容` 存入 buffer。**跳过纯媒体消息**（`[图片:xxx]`、`[表情:xxx]`、`[视频:xxx]` 等——文件 ID 是临时的，没有可读上下文价值）。超出 `_max_context_lines` 时裁剪最早的行。\n\n**`_drain_group_context(group_id)`**：有人 @bot 时调用，取出 buffer 格式化为：\n```\n[群聊上下文]\n[阮出] 今天好热啊\n[余出] 确实 35 度了\n[人神] 你们在聊什么\n---\n```\n清空 buffer 并返回。注入到 `stripped_text` 前面。\n\n### 效果\n\n```\n群友 A: \"今天好热啊\"          → _add_group_context → 不回复\n群友 B: \"是啊 35 度了\"         → _add_group_context → 不回复\n@魔术师 什么时候降温           → _drain_group_context → Agent 上下文中包含:\n                                  [群聊上下文]\n                                  A: 今天好热啊\n                                  B: 是啊 35 度了\n                                  ---\n                                  → 正常回复\n```\n\n### 注意事项\n\n- Buffer 在**内存**中，gateway 重启会丢失。不持久化到磁盘。\n- 非@消息必须包含纯文本（`_extract_reply_and_text` 提取），纯图片\u002F语音等无文本的消息不会进入 buffer。\n- `require_mention` 是 napcat.py 的硬编码逻辑（`_strip_self_mention`），当前版本**无法关闭**。`NAPCAT_REQUIRE_MENTION=true` 环境变量保留但代码实际上不读取它——因为群聊场景 @mention 是唯一触发方式，关闭会导致 bot 对每条群消息都回复。\n### ⚠️ 关键修复：@bot 检测（`_strip_self_mention` 的 seen_text + has_reply）\n\n**问题**：QQ 会在 reply 链\u002F会话上下文中自动插入不可见的 `at` 段（@bot），导致非@消息也被判定为 `mentioned=True`，bot 对每条消息都回复。\n\n**根因**：旧版 `_strip_self_mention` 只要看到消息段里有 `at` 指向 `self_id` 就返回 `mentioned=True`——不区分位置和上下文。\n\n**修复**（`napcat.py` `_strip_self_mention` 方法）：\n```python\nseen_text = False   # 是否已经出现了非@、非reply的内容\nhas_reply = False   # 消息是否包含 reply 段（QQ 回复特性）\nfor seg in segments:\n    ...\n    if seg_type == \"reply\":\n        has_reply = True\n        continue\n    if seg_type == \"at\":\n        if qq == self._self_id:\n            if not seen_text and not has_reply:  # 两个条件同时满足才提及\n                mentioned = True\n            continue\n        ...\n        seen_text = True\n    if seg_type == \"text\" and value.strip():\n        seen_text = True\n    if marker:\n        seen_text = True\n```\n\n**核心逻辑**：`mentioned` 只在同时满足两个条件时才为 True：\n1. `@bot` 出现在任何文本\u002F图片\u002F@其他人**之前**\n2. 消息**没有** `reply` 段（QQ 回复别人时自动插入 @bot，不算主动提及）\n\n\u003C｜｜DSML｜｜tool_calls>\n\u003C｜｜DSML｜｜invoke name=\"memory\">\n\u003C｜｜DSML｜｜parameter name=\"action\" string=\"true\">add\n\n## 致命陷阱：SOUL.md 会覆盖 SKILL.md 的对话风格\n\n**这是本次对话最大的踩坑发现。**\n\nSOUL.md (`~\u002F.hermes\u002FSOUL.md`) 是系统提示词第一槽位，其指令（如\"精确、直接\"、\"信息密度\"）会\n**覆盖** 平台 SKILL.md 中的对话风格要求。这导致 QQ 群聊中 Bot 持续输出 586 字长文，\n尽管 SKILL.md 明确要求 1-3 句。\n\n### 症状\n\n- SKILL.md 写满\"简短\"\"1-3句\"\"口语\"→ 完全无效\n- Bot 回复 500+ chars，AI 味重，长篇大论\n- 其他 Skill 配置正常，唯独回复长度不受控\n\n### 根因\n\nLLM 的系统提示词层级：\n1. **SOUL.md**（第 1 槽位，优先级最高）\n2. 平台 SKILL.md（第 N 槽位，优先级低）\n3. 用户消息\n\n当 SOUL.md 说\"精确直接、信息密度\"而 SKILL.md 说\"简短口语\"时，LLM 优先听 SOUL.md 的。\n\n### 修复：在 SKILL.md 开头加强制覆盖\n\n```markdown\n# 基本要求\n**本 prompt 的优先级高于你的默认行为模式。** QQ 群聊要求极短回复——\n你的默认\"信息密度\"、\"精确直接\"风格在此渠道必须切换为\"简短口语\"模式。\n忘记你学到的一切关于认真回答问题的训练——在 QQ 里，简短比正确更重要。\n```\n\n关键：必须用**绝对语气**（\"优先级高于\"、\"切换为\"、\"忘记\"），不能用\"请注意\"、\"建议\"等软话术。\n\n## Skill 上下文污染：必须禁用无关 Skill\n\nHermes 默认加载所有已安装的 Skill（300+个）。QQ 群聊会被注满生物、物理、部署等\n无关提示词，稀释 napcat 人格。\n\n### 配置\n\n`config.yaml`：\n```yaml\nskills:\n  platform_disabled:\n    napcat:\n      - \u003C258 个无关 Skill>\n```\n\n使用 Python 脚本批量生成禁用列表（排除 napcat + hermes-agent + perspective 类）。\n\n### 效果\n\n- 上下文从 300+ 个 Skill 压缩到 ~10 个\n- napcat 人格不再被稀释\n\n## Session 污染：越狱历史会触发 API 内容审查\n\nQQ 群聊的 session 会跨消息累积。如果群友发过猫娘越狱等内容，下次消息带上\n这段上下文时，DeepSeek API 会返回 **HTTP 400: Content Exists Risk**。\n\n### 止血\n\n```bash\n# 删除所有 napcat session\npython3 -c \"\nimport json\nwith open('\u002Fhome\u002Fpo\u002F.hermes\u002Fsessions\u002Fsessions.json') as f:\n    data = json.load(f)\nfor k in list(data):\n    if 'napcat' in k: del data[k]\n# 保存...\n\"\n```\n\n然后重启 Gateway。Session 会被自动重建，但历史污染会清除。\n\n## Hermes 的待解决问题\n\nAgent 看不到 QQ 号，只能看到群名片。改进方向：参考 AstrBot 的做法，在 napcat 适配器的\n`_build_message_event` 中，在消息文本前拼接发送者身份标识（如 `[QQ:2631792752|人民公仆]`）。\n\nWebUI → 网络配置 → WebSocket 客户端：\n\n| 字段 | 值 |\n|------|-----|\n| URL | `ws:\u002F\u002F127.0.0.1:8646\u002Fnapcat\u002Fws` |\n| Token | 同 NAPCAT_TOKEN |\n| 消息上报格式 | `array` |\n\n## 人格 SKILL.md 的正确位置 ⚠️\n\n**踩坑教训**：QQ 人格 SKILL.md 曾被错误放在源码仓库内（`hermes-agent\u002Fskills\u002Fmessaging\u002Fnapcat\u002FSKILL.md`），用户指出后已移正。\n\nHermes 有两个 skills 目录，用途不同：\n\n| 路径 | 用途 | 管理方式 |\n|------|------|----------|\n| `~\u002F.hermes\u002Fskills\u002F` | **用户安装的 skills** ← QQ 人格放这里 | 备份仓库同步，不跟源码版本 |\n| `hermes-agent\u002Fskills\u002F` | **源码自带的 built-in skills** | 跟 hermes-agent git 仓库，`hermes update` 时会变动 |\n\nQQ 人格 SKILL.md 的正确路径：**`~\u002F.hermes\u002Fskills\u002Fmessaging\u002Fnapcat\u002FSKILL.md`**。\n\n放在源码仓库里的后果：\n- `git pull` 或 `hermes update` 可能覆盖或冲突\n- 污染 upstream 仓库的干净状态\n- 备份仓库（hermes-config-kit）的 sync-back.sh 不会检测到它（因为脚本从 `~\u002F.hermes\u002Fskills\u002F` 同步）\n\n## hermes update 恢复流程\n\n每次 `hermes update` 后如果 NapCat 断连（ECONNREFUSED），执行以下步骤恢复：\n\n### 步骤 1：恢复 napcat.py\n\n```bash\ncd ~\u002F.hermes\u002Fhermes-agent\n# 找到 git 历史中 napcat.py 的最新版本\ngit log --all --oneline -- gateway\u002Fplatforms\u002Fnapcat.py | head -3\n# 从最近的有效提交恢复（避开 auto-maintenance 那个删除它的提交）\ngit show \u003Ccommit_hash>:gateway\u002Fplatforms\u002Fnapcat.py > gateway\u002Fplatforms\u002Fnapcat.py\n```\n\n> 如果本地 git 历史中没有 napcat.py（全新 clone），则从 MoeOver 分支 cherry-pick：`git checkout moeover\u002Fmain -- gateway\u002Fplatforms\u002Fnapcat.py`\n\n### 步骤 2：加回 Platform 枚举（gateway\u002Fconfig.py ~164 行）\n\n```python\n    QQBOT = \"qqbot\"\n    NAPCAT = \"napcat\"    # ← 加这行\n    YUANBAO = \"yuanbao\"\n```\n\n### 步骤 3：加回平台启用逻辑（gateway\u002Fconfig.py，QQBOT 段之后）\n\n```python\n    # NapCat (OneBot 11 reverse WebSocket)\n    napcat_enabled = os.getenv(\"NAPCAT_ENABLED\", \"\").lower() in {\"true\", \"1\", \"yes\"}\n    napcat_token = os.getenv(\"NAPCAT_TOKEN\", \"\").strip()\n    if napcat_token:\n        if Platform.NAPCAT not in config.platforms:\n            config.platforms[Platform.NAPCAT] = PlatformConfig()\n        cfg = config.platforms[Platform.NAPCAT]\n        if napcat_enabled:\n            cfg.enabled = True\n        cfg.token = napcat_token\n        extra = cfg.extra\n        extra[\"host\"] = os.getenv(\"NAPCAT_HOST\", \"0.0.0.0\")\n        extra[\"port\"] = int(os.getenv(\"NAPCAT_PORT\", \"8646\"))\n        extra[\"path\"] = os.getenv(\"NAPCAT_PATH\", \"\u002Fnapcat\u002Fws\")\n        napcat_home = os.getenv(\"NAPCAT_HOME_CHANNEL\", \"\").strip()\n        if napcat_home:\n            cfg.home_channel = HomeChannel(\n                platform=Platform.NAPCAT,\n                chat_id=napcat_home,\n                name=os.getenv(\"NAPCAT_HOME_CHANNEL_NAME\", \"Home\"),\n                thread_id=os.getenv(\"NAPCAT_HOME_CHANNEL_THREAD_ID\") or None,\n            )\n        napcat_allow_all = os.getenv(\"NAPCAT_ALLOW_ALL_USERS\", \"\").lower() in {\"true\", \"1\", \"yes\"}\n        if napcat_allow_all:\n            extra[\"allow_all_users\"] = True\n        napcat_allow_from = os.getenv(\"NAPCAT_ALLOW_FROM\", \"\").strip()\n        if napcat_allow_from:\n            extra[\"allow_from\"] = napcat_allow_from\n        napcat_require_mention = os.getenv(\"NAPCAT_REQUIRE_MENTION\", \"\").lower()\n        if napcat_require_mention in {\"true\", \"1\", \"yes\", \"false\", \"0\", \"no\"}:\n            extra[\"require_mention\"] = napcat_require_mention in {\"true\", \"1\", \"yes\"}\n```\n\n### 步骤 4：加回 adapter 创建代码（gateway\u002Frun.py，QQBOT 段之后）\n\n```python\n        elif platform == Platform.NAPCAT:\n            from gateway.platforms.napcat import NapCatAdapter, check_napcat_requirements\n            if not check_napcat_requirements():\n                logger.warning(\"NapCat: aiohttp not installed\")\n                return None\n            return NapCatAdapter(config)\n```\n\n### 步骤 5：加到 _UPDATE_ALLOWED_PLATFORMS（gateway\u002Frun.py ~10835 行）\n\n在 `Platform.QQBOT` 后加 `Platform.NAPCAT`。\n\n### 步骤 5.5：加回 authz 授权映射（gateway\u002Fauthz_mixin.py）\n\n**这是隐藏最深的坑**。即使前 5 步都做对了，`NAPCAT_ALLOW_ALL_USERS=true` 也不会生效，因为 `authz_mixin.py` 的三个平台映射表没有 NAPCAT：\n\n```python\n# platform_env_map（约 157 行，QQBOT 之后加）\nPlatform.NAPCAT: \"NAPCAT_ALLOW_FROM\",\n\n# platform_allow_all_map（约 183 行，QQBOT 之后加）\nPlatform.NAPCAT: \"NAPCAT_ALLOW_ALL_USERS\",\n```\n\n症状：Gateway 日志 `Unauthorized user: 2631792752 (人民公仆) on napcat`，所有消息被静默丢弃。\n\n### 步骤 5.6：加回 hermes_cli\u002Fgateway.py 的 setup 函数和 PLATFORMS 条目\n\n合并后 `hermes setup` 的 NapCat 交互式配置也会丢失。需要：\n\n1. 在 `_setup_qqbot()` 函数之后加 `_setup_napcat()` 函数\n2. 在 `_PLATFORMS` dict 中加 `\"napcat\": _setup_napcat,`\n\n### 步骤 6：重启 Gateway\n\n```bash\nkill $(ps aux | grep 'gateway run' | grep -v grep | awk '{print $2}')\n# systemd 会自动重启，或手动：\n# nohup hermes gateway run --replace &\n```\n\n验证：`grep -a -E 'napcat|Gateway running with' \u002Fhome\u002Fpo\u002F.hermes\u002Flogs\u002Fgateway.log | tail -5`\n应该看到 `✓ napcat connected` 和 `Gateway running with 3 platform(s)`。\n\n## 排障速查\n\n| 现象 | 原因 | 方案 |\n|------|------|------|\n| **hermes update 后 ECONNREFUSED** | napcat.py + config\u002Frun 被更新覆盖 | 执行「hermes update 恢复流程」（上方章节） |\n| **`napcat_call` 永远不可用 \u002F 图片无法识别** | `gateway.run._active_runner` 从未赋值（模块级变量为 None） | 两步修复：\u003Cbr>(1) 模块顶（约 67 行，`_ADAPTER_DISCONNECT_TIMEOUT` 之后）加 `_active_runner: Optional[Any] = None`\u003Cbr>(2) `start_gateway()` 中（约 15713 行，`runner = GatewayRunner(config)` 之后）加 `global _active_runner; _active_runner = runner` |\n| **非@消息也回复** | `_strip_self_mention` 不区分 @bot 的前后位置，QQ 自动塞的 @bot 被误判 | 加 `seen_text` 追踪——只有**开头**的 @bot 算主动提及 |\n| **`NAPCAT_ALLOW_ALL_USERS=true` 不生效** | `authz_mixin.py` 映射表缺少 NAPCAT | 加 `Platform.NAPCAT` 到 `platform_allow_all_map` 和 `platform_env_map` |\n| **Unauthorized user 警告** | 同上：authz 映射表不认 NAPCAT | 同上 |\n| 401 | Token 不匹配 | 确认两端一致 |\n| Unauthorized user | 不在白名单 | `NAPCAT_ALLOW_ALL_USERS=true` |\n| 无消息事件 | message 字段缺失或 @mention 未检测 | 确认消息上报格式 array |\n| Gateway 卡死 | Telegram 连接阻塞 | `kill -9 $(pgrep -f gateway)` |\n| Agent 分不清主人 | **看不到 QQ 号**（核心缺陷） | 待改适配器注入身份 |\n| Markdown 泄漏 | LLM 本能输出 Markdown | Skill 里用\"硬件限制\"话术 + 违规示例 |\n| 猫娘越狱 | 群友直接 role-play prompt | 威胁扫描拦截（已加中文模式） |\n| require_mention 不生效 | `hermes config set` 设到了 display.platforms 下 | 必须用 `hermes config set napcat.require_mention true`（顶层，不是 display 下） |\n| 没 @ 的消息也回复了 | 适配器代码出错 | 确认 `_pending_context` 初始化和 `return None` 正确 |\n| **\"Content Exists Risk\" (400)** | DeepSeek 内容审查拒绝处理请求 | 见下方专项说明 |\n| **群消息发错误给群友** | agent 失败时中间结果仍发出 | 同上，跨 bot 连锁污染 |\n\n### DeepSeek \"Content Exists Risk\" 专项 ⚠️\n\n**现象**：agent.log 出现 `HTTP 400: Content Exists Risk`，gateway 把 147 字符错误消息发到 QQ 群。\n\n**根因**：DeepSeek API（尤其是 `v4-flash`）的内容安全过滤器对某些上下文组合过于敏感。NapCat 会话通常较长（群聊多轮对话），累积的上下文更容易触发。\n\n**连锁灾难**：如果群里有多个 bot（如 Hermes + 人出 bot），一个 bot 的错误消息会成为另一个 bot 的上下文 → 再触发同一个 400 → 两个 bot 互相喂毒，无限循环。\n\n**止血方案（按推荐优先级）**：\n\n1. **换模型** — 把 `NAPCAT_MODEL` 从 deepseek 系换成没有内容审查的 provider（如 minimax-cn、z.ai 等）。最快，一刀切。\n\n2. **手动 reset session** — 在群里发 `\u002Freset` 清除累积的上下文。治标，适合临时恢复。\n\n3. **代码层面** — 修改 gateway 在 `agent_failed_early` 时不发原始错误到群（发\"稍后重试\"类文案），并加连续 2 次 `Content Exists Risk` 自动 reset。治本但需改代码。\n\n详细排查记录见 `references\u002Fdeepseek-content-risk.md`。\n",{"name":5,"author":24,"license":15,"version":25,"description":7,"prerequisites":26},"Hermes Agent (Publieople session)","2.2.0",{"env_vars":27},[28,29],"NAPCAT_TOKEN","NAPCAT_ALLOW_ALL_USERS","master","2cd115c9a59092e1d0cf18805c164d7a57a7f123","skills\u002F_archive\u002Fnapcat-hermes-setup","https:\u002F\u002Fgithub.com\u002Fpublieople\u002Fhermes-config-kit","https:\u002F\u002Fgithub.com\u002Fpublieople","https:\u002F\u002Fwww.for-people.cn","Truly provide effective services for the real people","2026-10-11 09:10:19",{"source":8,"skillName":5,"commands":39,"prompt":49,"zipAvailable":50},[40,43,46],{"tool":41,"command":42},"npx","npx skills add publieople\u002Fhermes-config-kit --skill napcat-hermes-setup",{"tool":44,"command":45},"bunx","bunx skills add publieople\u002Fhermes-config-kit --skill napcat-hermes-setup",{"tool":47,"command":48},"pnpm","pnpm dlx skills add publieople\u002Fhermes-config-kit --skill napcat-hermes-setup","安装技能，技能地址：https:\u002F\u002Fgithub.com\u002Fpublieople\u002Fhermes-config-kit\u002Fblob\u002Fmaster\u002Fskills\u002F_archive\u002Fnapcat-hermes-setup\u002FSKILL.md",true,[52,58,62,66,70,74,78,82,86,90],{"path":53,"resourceType":54,"resourceTypeDesc":55,"sizeBytes":56,"sourceHtmlUrl":57},"references\u002Fastrbot-box-weapon.md","REFERENCE","参考文档",4398,"https:\u002F\u002Fgithub.com\u002Fpublieople\u002Fhermes-config-kit\u002Fblob\u002Fmaster\u002Fskills\u002F_archive\u002Fnapcat-hermes-setup\u002Freferences\u002Fastrbot-box-weapon.md",{"path":59,"resourceType":54,"resourceTypeDesc":55,"sizeBytes":60,"sourceHtmlUrl":61},"references\u002Fastrbot-deploy.md",5336,"https:\u002F\u002Fgithub.com\u002Fpublieople\u002Fhermes-config-kit\u002Fblob\u002Fmaster\u002Fskills\u002F_archive\u002Fnapcat-hermes-setup\u002Freferences\u002Fastrbot-deploy.md",{"path":63,"resourceType":54,"resourceTypeDesc":55,"sizeBytes":64,"sourceHtmlUrl":65},"references\u002Fastrbot-source-analysis.md",3983,"https:\u002F\u002Fgithub.com\u002Fpublieople\u002Fhermes-config-kit\u002Fblob\u002Fmaster\u002Fskills\u002F_archive\u002Fnapcat-hermes-setup\u002Freferences\u002Fastrbot-source-analysis.md",{"path":67,"resourceType":54,"resourceTypeDesc":55,"sizeBytes":68,"sourceHtmlUrl":69},"references\u002Fdebugging-anti-patterns.md",1285,"https:\u002F\u002Fgithub.com\u002Fpublieople\u002Fhermes-config-kit\u002Fblob\u002Fmaster\u002Fskills\u002F_archive\u002Fnapcat-hermes-setup\u002Freferences\u002Fdebugging-anti-patterns.md",{"path":71,"resourceType":54,"resourceTypeDesc":55,"sizeBytes":72,"sourceHtmlUrl":73},"references\u002Fdeepseek-content-risk.md",2141,"https:\u002F\u002Fgithub.com\u002Fpublieople\u002Fhermes-config-kit\u002Fblob\u002Fmaster\u002Fskills\u002F_archive\u002Fnapcat-hermes-setup\u002Freferences\u002Fdeepseek-content-risk.md",{"path":75,"resourceType":54,"resourceTypeDesc":55,"sizeBytes":76,"sourceHtmlUrl":77},"references\u002Ffork-merge-patches.md",7639,"https:\u002F\u002Fgithub.com\u002Fpublieople\u002Fhermes-config-kit\u002Fblob\u002Fmaster\u002Fskills\u002F_archive\u002Fnapcat-hermes-setup\u002Freferences\u002Ffork-merge-patches.md",{"path":79,"resourceType":54,"resourceTypeDesc":55,"sizeBytes":80,"sourceHtmlUrl":81},"references\u002Fjiupamiao-template-analysis.md",2532,"https:\u002F\u002Fgithub.com\u002Fpublieople\u002Fhermes-config-kit\u002Fblob\u002Fmaster\u002Fskills\u002F_archive\u002Fnapcat-hermes-setup\u002Freferences\u002Fjiupamiao-template-analysis.md",{"path":83,"resourceType":54,"resourceTypeDesc":55,"sizeBytes":84,"sourceHtmlUrl":85},"references\u002Fnapcat-setup-function.md",2520,"https:\u002F\u002Fgithub.com\u002Fpublieople\u002Fhermes-config-kit\u002Fblob\u002Fmaster\u002Fskills\u002F_archive\u002Fnapcat-hermes-setup\u002Freferences\u002Fnapcat-setup-function.md",{"path":87,"resourceType":54,"resourceTypeDesc":55,"sizeBytes":88,"sourceHtmlUrl":89},"references\u002Fper-platform-config.md",4078,"https:\u002F\u002Fgithub.com\u002Fpublieople\u002Fhermes-config-kit\u002Fblob\u002Fmaster\u002Fskills\u002F_archive\u002Fnapcat-hermes-setup\u002Freferences\u002Fper-platform-config.md",{"path":91,"resourceType":54,"resourceTypeDesc":55,"sizeBytes":92,"sourceHtmlUrl":93},"references\u002Fpersona-design.md",2264,"https:\u002F\u002Fgithub.com\u002Fpublieople\u002Fhermes-config-kit\u002Fblob\u002Fmaster\u002Fskills\u002F_archive\u002Fnapcat-hermes-setup\u002Freferences\u002Fpersona-design.md",[95,102,109,116,123,130],{"skillNo":96,"name":97,"nameZh":6,"description":98,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":99,"categories":100,"keywords":101,"publishedAt":19},"01M75A845WYE5R2AFVSS7YHBJV","test-driven-development","TDD: enforce RED-GREEN-REFACTOR, tests before code.","https:\u002F\u002Fgithub.com\u002Fpublieople\u002Fhermes-config-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fsoftware-development\u002Ftest-driven-development\u002FSKILL.md",[],[],{"skillNo":103,"name":104,"nameZh":6,"description":105,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":106,"categories":107,"keywords":108,"publishedAt":19},"01M75A7QKQZD6YVEJ55KYNBHM1","systematic-debugging","4-phase root cause debugging: understand bugs before fixing.","https:\u002F\u002Fgithub.com\u002Fpublieople\u002Fhermes-config-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fsoftware-development\u002Fsystematic-debugging\u002FSKILL.md",[],[],{"skillNo":110,"name":111,"nameZh":6,"description":112,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":113,"categories":114,"keywords":115,"publishedAt":19},"01M75A7NCY8TJN7BVDV7GKQJNE","simplify-code","Parallel 4-agent cleanup of recent code changes.","https:\u002F\u002Fgithub.com\u002Fpublieople\u002Fhermes-config-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fsoftware-development\u002Fsimplify-code\u002FSKILL.md",[],[],{"skillNo":117,"name":118,"nameZh":6,"description":119,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":120,"categories":121,"keywords":122,"publishedAt":19},"01M75A7JW7JHDNNKYGFQDP4E2M","inspecting-hermes-desktop-dom","Read the live Hermes desktop DOM\u002FCSS over CDP.","https:\u002F\u002Fgithub.com\u002Fpublieople\u002Fhermes-config-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fsoftware-development\u002Finspecting-hermes-desktop-dom\u002FSKILL.md",[],[],{"skillNo":124,"name":125,"nameZh":6,"description":126,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":127,"categories":128,"keywords":129,"publishedAt":19},"01M75A7EP72GHSVHW337XD75CR","hermes-agent-skill-authoring","Author in-repo SKILL.md files: frontmatter and structure.","https:\u002F\u002Fgithub.com\u002Fpublieople\u002Fhermes-config-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fsoftware-development\u002Fhermes-agent-skill-authoring\u002FSKILL.md",[],[],{"skillNo":131,"name":132,"nameZh":6,"description":133,"descriptionZh":6,"repositoryFullName":8,"ownerLogin":9,"ownerAvatarUrl":10,"ownerAccountNo":11,"ownerDisplayName":12,"repositoryNo":13,"starsCount":14,"licenseSpdxId":15,"licenseFileUrl":6,"sourceHtmlUrl":134,"categories":135,"keywords":136,"publishedAt":19},"01M75A7BGWRT0453313CJKP4SC","github","GitHub via gh CLI: PRs, issues, reviews, repos, auth.","https:\u002F\u002Fgithub.com\u002Fpublieople\u002Fhermes-config-kit\u002Fblob\u002Fmaster\u002Fskills\u002Fsoftware-development\u002Fgithub\u002FSKILL.md",[],[]]